Previously, you were introduced to several technical skills that security analysts need to develop. You were also introduced to some tools entry-level security analysts may have in their toolkit. In this reading, you’ll learn more about how technical skills and tools help security analysts mitigate risks.
An entry-level analyst’s toolkit
Every organization may provide a different toolkit, depending on its security needs. As a future analyst, it’s important that you are familiar with industry standard tools and can demonstrate your ability to learn how to use similar tools in a potential workplace.
Security information and event management (SIEM) tools
A SIEM tool is an application that collects and analyzes log data to monitor critical activities in an organization. A log is a record of events that occur within an organization’s systems. Depending on the amount of data you’re working with, it could take hours or days to filter through log data on your own. SIEM tools reduce the amount of data an analyst must review by providing alerts for specific types of threats, risks, and vulnerabilities.
SIEM tools provide a series of dashboardsthat visually organize data into categories, allowing users to select the data they wish to analyze. Different SIEM toolshave different dashboard types that display the information you have access to.
SIEM tools also come with different hosting options, including on-premise and cloud. Organizations may choose one hosting option over another based on a security team member’s expertise. For example, because a cloud-hosted version tends to be easier to set up, use, and maintain than an on-premise version, a less experienced security team may choose this option for their organization.
Network protocol analyzers (packet sniffers)
A network protocol analyzer, also known as a packet sniffer, is a tool designed to capture and analyze data traffic in a network. This means that the tool keeps a record of all the data that a computer within an organization's network encounters. Later in the program, you’ll have an opportunity to practice using some common network protocol analyzer (packet sniffer) tools.
Playbooks
A playbook is a manual that provides details about any operational action, such as how to respond to a security incident. Organizations usually have multiple playbooks documenting processes and procedures for their teams to follow. Playbooks vary from one organization to the next, but they all have a similar purpose: To guide analysts through a series of steps to complete specific security-related tasks.
For example, consider the following scenario: You are working as a security analyst for an incident response firm. You are given a case involving a small medical practice that has suffered a security breach. Your job is to help with the forensic investigation and provide evidence to a cybersecurity insurance company. They will then use your investigative findings to determine whether the medical practice will receive their insurance payout.
In this scenario, playbooks would outline the specific actions you need to take to conduct the investigation. Playbooks also help ensure that you are following proper protocols and procedures. When working on a forensic case, there are two playbooks you might follow:
The first type of playbook you might consult is called the chain of custody playbook.Chain of custody is the process of documenting evidence possession and control during an incident lifecycle. As a security analyst involved in a forensic analysis, you will work with the computer data that was breached. You and the forensic team will also need to document who, what, where, and why you have the collected evidence. The evidence is your responsibility while it is in your possession. Evidence must be kept safe and tracked. Every time evidence is moved, it should be reported. This allows all parties involved to know exactly where the evidence is at all times.
The second playbook your team might use is called the protecting and preserving evidence playbook. Protecting and preserving evidence is the process of properly working with fragile and volatile digital evidence. As a security analyst, understanding what fragile and volatile digital evidence is, along with why there is a procedure, is critical. As you follow this playbook, you will consult the order of volatility,which is a sequence outlining the order of data that must be preserved from first to last. It prioritizes volatile data, which is data that may be lost if the device in question powers off, regardless of the reason. While conducting an investigation, improper management of digital evidence can compromise and alter that evidence. When evidence is improperly managed during an investigation, it can no longer be used. For this reason, the first priority in any investigation is to properly preserve the data. You can preserve the data by making copies and conducting your investigation using those copies.
Key takeaways
In this reading, you learned about a few tools a security analyst may have in their toolkit, depending on where they work. You also explored two important types of playbooks: chain of custody and protecting and preserving evidence. However, these are only two procedures that occur at the beginning of a forensic investigation. If forensic investigations interest you, you are encouraged to further explore this career path or security practice. In the process, you may learn about forensic tools that you want to add to your toolkit. While all of the forensic components that make up an investigation will not be covered in this certificate program, some forensic concepts will be discussed in later courses.
Use tools to protect business operations
Previously, you were introduced to programming, operating systems, and tools commonly used by cybersecurity professionals. In this reading, you’ll learn more about programming and operating systems, as well as other tools that entry-level analysts use to help protect organizations and the people they serve.
Tools and their purposes
Programming
Programming is a process that can be used to create a specific set of instructions for a computer to execute tasks. Security analysts use programming languages, such as Python, to execute automation. Automation is the use of technology to reduce human and manual effort in performing common and repetitive tasks. Automation also helps reduce the risk of human error.
Another programming language used by analysts is called Structured Query Language (SQL). SQL is used to create, interact with, and request information from a database. A database is an organized collection of information or data. There can be millions of data pointsin a database. A data point is a specific piece of information.
Operating systems
An operating system is the interface between computer hardware and the user. Linux®, macOS®, and Windows are operating systems. They each offer different functionality and user experiences.
Previously, you were introduced to Linux as an open-source operating system. Open source means that the code is available to the public and allows people to make contributions to improve the software. Linux is not a programming language; however, it does involve the use of a command line within the operating system. A command is an instruction telling the computer to do something. A command-line interfaceis a text-based user interface that uses commands to interact with the computer. You will learn more about Linux, including the Linux kernel and GNU, in a later course.
Web vulnerability
A web vulnerability is a unique flaw in a web application that a threat actor could exploit by using malicious code or behavior, to allow unauthorized access, data theft, and malware deployment.
Antivirus software is a software program used to prevent, detect, and eliminate malware and viruses. It is also called anti-malware. Depending on the type of antivirus software, it can scan the memory of a device to find patterns that indicate the presence of malware.
Intrusion detection system
An intrusion detection system (IDS) is an application that monitors system activity and alerts on possible intrusions. The system scans and analyzes network packets, which carry small amounts of data through a network. The small amount of data makes the detection process easier for an IDS to identify potential threats to sensitive data. Other occurrences an IDS might detect can include theft and unauthorized access.
Encryption
Encryption makes data unreadable and difficult to decode for an unauthorized user; its main goal is to ensure confidentiality of private data. Encryption is the process of converting data from a readable format to a cryptographically encoded format. Cryptographic encoding means converting plaintext into secure ciphertext. Plaintext is unencrypted information and secure ciphertext is the result of encryption.
Note: Encoding and encryption serve different purposes. Encoding uses a public conversion algorithm to enable systems that use different data representations to share information.
Penetration testing
Penetration testing, also called pen testing, is the act of participating in a simulated attack that helps identify vulnerabilities in systems, networks, websites, applications, and processes. It is a thorough risk assessment that can evaluate and identify external and internal threats as well as weaknesses.
Key takeaways
In this reading, you learned more about programming and operating systems. You were also introduced to several new tools and processes. Every organization selects their own set of tools. Therefore, the more tools you know, the more valuable you are to an organization. Tools help security analysts complete their tasks more efficiently and effectively.
Previously, you were introduced to security frameworks and how they provide a structured approach to implementing a security lifecycle. As a reminder, a security lifecycle is a constantly evolving set of policies and standards. In this reading, you will learn more about how security frameworks, controls, and compliance regulations—or laws—are used together to manage security and make sure everyone does their part to minimize risk.
How controls, frameworks, and compliance are related
The confidentiality, integrity, and availability (CIA) triad is a model that helps inform how organizations consider risk when setting up systems and security policies.
CIA are the three foundational principles used by cybersecurity professionals to establish appropriate controls that mitigate threats, risks, and vulnerabilities.
As you may recall, securitycontrols are safeguards designed to reduce specific security risks. So they are used alongside frameworks to ensure that security goals and processes are implemented correctly and that organizations meet regulatory compliance requirements.
Security frameworks are guidelines used for building plans to help mitigate risks and threats to data and privacy. They have four core components:
Identifying and documenting security goals
Setting guidelines to achieve security goals
Implementing strong security processes
Monitoring and communicating results
Compliance is the process of adhering to internal standards and external regulations.
Specific controls, frameworks, and compliance
The National Institute of Standards and Technology (NIST) is a U.S.-based agency that develops multiple voluntary compliance frameworks that organizations worldwide can use to help manage risk. The more aligned an organization is with compliance, the lower the risk.
Examples of frameworks include the NIST Cybersecurity Framework (CSF) and the NIST Risk Management Framework (RMF).
Note: Specifications and guidelines can change depending on the type of organization you work for.
In addition to the NIST CSF and NIST RMF, there are several other controls, frameworks, and compliance standards that are important for security professionals to be familiar with to help keep organizations and the people they serve safe.
The Federal Energy Regulatory Commission - North American Electric Reliability Corporation (FERC-NERC)
FERC-NERC is a regulation that applies to organizations that work with electricity or that are involved with the U.S. and North American power grid. These types of organizations have an obligation to prepare for, mitigate, and report any potential security incident that can negatively affect the power grid. They are also legally required to adhere to the Critical Infrastructure Protection (CIP) Reliability Standards defined by the FERC.
The Federal Risk and Authorization Management Program (FedRAMP®)
FedRAMP is a U.S. federal government program that standardizes security assessment, authorization, monitoring, and handling of cloud services and product offerings. Its purpose is to provide consistency across the government sector and third-party cloud providers.
Center for Internet Security (CIS®)
CIS is a nonprofit with multiple areas of emphasis. It provides a set of controls that can be used to safeguard systems and networks against attacks. Its purpose is to help organizations establish a better plan of defense. CIS also provides actionable controls that security professionals may follow if a security incident occurs.
General Data Protection Regulation (GDPR)
GDPR is a European Union (E.U.) general data regulation that protects the processing of E.U. residents’ data and their right to privacy in and out of E.U. territory. For example, if an organization is not being transparent about the data they are holding about an E.U. citizen and why they are holding that data, this is an infringement that can result in a fine to the organization. Additionally, if a breach occurs and an E.U. citizen’s data is compromised, they must be informed. The affected organization has 72 hours to notify the E.U. citizen about the breach.
Payment Card Industry Data Security Standard (PCI DSS)
PCI DSS is an international security standard meant to ensure that organizations storing, accepting, processing, and transmitting credit card information do so in a secure environment. The objective of this compliance standard is to reduce credit card fraud.
The Health Insurance Portability and Accountability Act (HIPAA)
HIPAA is a U.S. federal law established in 1996 to protect patients' health information. This law prohibits patient information from being shared without their consent. It is governed by three rules:
Privacy
Security
Breach notification
Organizations that store patient data have a legal obligation to inform patients of a breach because if patients' Protected Health Information (PHI) is exposed, it can lead to identity theft and insurance fraud. PHI relates to the past, present, or future physical or mental health or condition of an individual, whether it’s a plan of care or payments for care. Along with understanding HIPAA as a law, security professionals also need to be familiar with the Health Information Trust Alliance (HITRUST®), which is a security framework and assurance program that helps institutions meet HIPAA compliance.
International Organization for Standardization (ISO)
ISO was created to establish international standards related to technology, manufacturing, and management across borders. It helps organizations improve their processes and procedures for staff retention, planning, waste, and services.
System and Organizations Controls (SOC type 1, SOC type 2)
The American Institute of Certified Public Accountants® (AICPA) auditing standards board developed this standard. The SOC1 and SOC2 are a series of reports that focus on an organization's user access policies at different organizational levels such as:
Associate
Supervisor
Manager
Executive
Vendor
Others
They are used to assess an organization’s financial compliance and levels of risk. They also cover confidentiality, privacy, integrity, availability, security, and overall data safety. Control failures in these areas can lead to fraud.
Pro tip: There are a number of regulations that are frequently revised. You are encouraged to keep up-to-date with changes and explore more frameworks, controls, and compliance. Two suggestions to research: the Gramm-Leach-Bliley Act and the Sarbanes-Oxley Act.
Key takeaways
In this reading you learned more about controls, frameworks, and compliance. You also learned how they work together to help organizations maintain a low level of risk.
As a security analyst, it’s important to stay up-to-date on common frameworks, controls, and compliance regulations and be aware of changes to the cybersecurity landscape to help ensure the safety of both organizations and people.
Ethical concepts that guide cybersecurity decisions
Previously, you were introduced to the concept of security ethics. Security ethics are guidelines for making appropriate decisions as a security professional. Being ethical requires that security professionals remain unbiased and maintain the security and confidentiality of private data. Having a strong sense of ethics can help you navigate your decisions as a cybersecurity professional so you’re able to mitigate threats posed by threat actors’ constantly evolving tactics and techniques. In this reading, you’ll learn about more ethical concepts that are essential to know so you can make appropriate decisions about how to legally and ethically respond to attacks in a way that protects organizations and people alike.
Ethical concerns and laws related to counterattacks
United States standpoint on counterattacks
In the U.S., deploying a counterattack on a threat actor is illegal because of laws like the Computer Fraud and Abuse Act of 1986 and the Cybersecurity Information Sharing Act of 2015, among others. You can only defend. The act of counterattacking in the U.S. is perceived as an act of vigilantism. Avigilante is a person who is not a member of law enforcement who decides to stop a crime on their own. And because threat actors are criminals, counterattacks can lead to further escalation of the attack, which can cause even more damage and harm. Lastly, if the threat actor in question is a state-sponsored hacktivist, a counterattack can lead to serious international implications. A hacktivist is a person who uses hacking to achieve a political goal. The political goal may be to promote social change or civil disobedience.
For these reasons, the only individuals in the U.S. who are allowed to counterattack are approved employees of the federal government or military personnel.
International standpoint on counterattacks
The International Court of Justice (ICJ), which updates its guidance regularly, states that a person or group can counterattack if:
The counterattack will only affect the party that attacked first.
The counterattack is a direct communication asking the initial attacker to stop.
The counterattack does not escalate the situation.
The counterattack effects can be reversed.
Organizations typically do not counterattack because the above scenarios and parameters are hard to measure. There is a lot of uncertainty dictating what is and is not lawful, and at times negative outcomes are very difficult to control. Counterattack actions generally lead to a worse outcome, especially when you are not an experienced professional in the field.
To learn more about specific scenarios and ethical concerns from an international perspective, review updates provided in the Tallinn Manual online.
Ethical principles and methodologies
Because counterattacks are generally disapproved of or illegal, the security realm has created frameworks and controls—such as the confidentiality, integrity, and availability (CIA) triad and others discussed earlier in the program—to address issues of confidentiality, privacy protections, and laws. To better understand the relationship between these issues and the ethical obligations of cybersecurity professionals, review the following key concepts as they relate to using ethics to protect organizations and the people they serve.
Confidentiality means that only authorized users can access specific assets or data. Confidentiality as it relates to professional ethics means that there needs to be a high level of respect for privacy to safeguard private assets and data.
Privacy protection means safeguarding personal information from unauthorized use. Personally identifiable information (PII) and sensitive personally identifiable information (SPII)are types of personal data that can cause people harm if they are stolen. PII data is any information used to infer an individual's identity, like their name and phone number. SPII data is a specific type of PII that falls under stricter handling guidelines, including social security numbers and credit card numbers. To effectively safeguard PII and SPIIdata, security professionals hold an ethical obligation to secure private information, identify security vulnerabilities, manage organizational risks, and align security with business goals.
Laws are rules that are recognized by a community and enforced by a governing entity. As a security professional, you will have an ethical obligation to protect your organization, its internal infrastructure, and the people involved with the organization. To do this:
You must remain unbiased and conduct your work honestly, responsibly, and with the highest respect for the law.
Be transparent and just, and rely on evidence.
Ensure that you are consistently invested in the work you are doing, so you can appropriately and ethically address issues that arise.
Stay informed and strive to advance your skills, so you can contribute to the betterment of the cyber landscape.
As an example, consider the Health Insurance Portability and Accountability Act (HIPAA), which is a U.S. federal law established to protect patients' health information, also known as PHI, or protected health information. This law prohibits patient information from being shared without their consent. So, as a security professional, you might help ensure that the organization you work for adheres to both its legal and ethical obligation to inform patients of a breach if their health care data is exposed.
Key takeaways
As a future security professional, ethics will play a large role in your daily work. Understanding ethics and laws will help you make the correct choices if and when you encounter a security threat or an incident that results in a breach.
Terms and definitions from Course 1, Module 3
Asset: An item perceived as having value to an organization
Availability: The idea that data is accessible to those who are authorized to access it
Compliance: The process of adhering to internal standards and external regulations
Confidentiality: The idea that only authorized users can access specific assets or data
Confidentiality, integrity, availability (CIA) triad: A model that helps inform how organizations consider risk when setting up systems and security policies
Hacktivist: A person who uses hacking to achieve a political goal
Health Insurance Portability and Accountability Act (HIPAA): A U.S. federal law established to protect patients' health information
Integrity: The idea that the data is correct, authentic, and reliable
National Institute of Standards and Technology (NIST) Cyber Security Framework (CSF): A voluntary framework that consists of standards, guidelines, and best practices to manage cybersecurity risk
Privacy protection: The act of safeguarding personal information from unauthorized use
Protected health information (PHI): Information that relates to the past, present, or future physical or mental health or condition of an individual
Security architecture: A type of security design composed of multiple components, such as tools and processes, that are used to protect an organization from risks and external threats
Security controls: Safeguards designed to reduce specific security risks
Security ethics: Guidelines for making appropriate decisions as a security professional
Security frameworks: Guidelines used for building plans to help mitigate risk and threats to data and privacy
Security governance: Practices that help support, define, and direct security efforts of an organization
Sensitive personally identifiable information (SPII): A specific type of PII that falls under stricter handling guidelines
공격 시나리오: OSINT(직원 정보 수집) -> Imersonation(사칭) -> Phishing(직원 피싱) -> VPNcred(직원용 VPN 계정 탈취) -> Pivot(VPN 계정 탈취 및 내부망 이동, DB 액세스)
공격 시나리오
내부 인프라 정보: 실제 타깃(raccoooncoin.site)의 내부 인프라 정보를 명세해놨다. 타겟 페이지가 어떤 식으로 구성되어 있고, 굴러 가는지 분석한 부분이다.
내부 인프라 정보
www.raccooncoin.site → Cloudflare → Origin: Oracle VPS(140.238.x.x): 사용자가 raccooncoin.site에 접속하면 Cloudflare로 먼저 들어오고, Cloudflare가 내부적으로 Oracle VPS(140.238.x.x)에 트래픽을 전달하는 구조. 공격자는 이를 역으로 OSINT로 파악하여 "진짜 서버는 140.238.x.x 대역에 있다"라고 기록한 것.
raccooncoin.site/singin.html → 오타 기반 피싱 탐색: 원래는 로그인용 페이지인 signin.html 이어야 할 텐데 오타가 발생한 페이지이다. 피싱 페이지로 악용하기 좋은 소스가 될 수 있어 메모해 둔 듯.
vpn.raccooncoin.site → 직원 VPN 포털: 내부 직원들이 사용하는 Staff VPN 로그인 페이지일 확률이 매우 높다.
(2) Social Engineering Plan
OSINT(직원 정보 수집) -> Imersonation(사칭) -> Phishing(직원 피싱) -> VPN cred(직원용 VPN 계정 탈취) -> Pivot(VPN 계정 탈취 및 내부망 이동, DB 액세스) 중 Imersonation(사칭) 부분에 대한 상세 계획이다. plan.txt 에 나온 시나리오대로라면 socket puppet 이 있을 것이다. 이들의깃헙 레포와 링크드인도 있을 것이다.
(3) Phishing Scenario
공격자가 현재까지 파악한 타겟 상세 정보들 및 이를 바탕으로 현재까지 세운 시나리오 정보
현재까지 파악한 타겟 상세 정보
VPN credentials for C-levels. (Check db in the zip file): 이미 임원 정보를 해커 쪽에서 털었고 zip파일 내 db에 이게 포함되어 있음.
Some internal IP ranges: 10.10.0.0/16. : 타겟 사이트의 내부망 주소까지 파악된 상태
Evidence that RedRaccoon TI (threat-intel@redraccoon.kr) had "pending" VPN account : 방어팀이 내부 VPN 계정을 신청한 기록이 보였음. 공격자는 이를 보고 공격 표면이 더 넓다는 것을 알고 있음
198.51.100.44 → used for failed VPN attempts against "groot". Might be previous attacker or misconfigured testing box.: 이미 공격 당한 흔적이 있음→ 여기 저기서 인기 많은 타겟.
185.199.111.153 → GitHub pages / static hosting. Seen as login source for rr-ti1/wget → maybe Red Raccoon scanner. : RedRaccoon 팀이 wget 등으로 GitHub Pages에 올린 자료(흔히 OSINT용)을 스캔했을 확률이 있다. 즉, 방어팀(위협 인텔팀)의 분석 활동 흔적을 공격자가 보고 있다.
이를 바탕으로 한 인프라 구축 계획
Stand up redirector on cheap VPS. : 이건 우리가 이미 발견한 리다이렉트 서버의 존재(http://140.238.194.224)
Use it as: - HTTP(S) phishing landing page - SSH C2 pivot (port 80/443 masquerading) : 이 부분을 통해 현재 시나리오에 쓰인 서버들이 HTTP 리다이렉션 형태로 구성 되었음을 알 수 있다. 구체적으로는, 사용자가 피싱 페이지에 입력한 정보는 바로 공격자 서버로 넘어가는 것이 아니라, 이 경유지 서버를 한 번 거쳐서 공격자 서버(C2, Command & Controll)로 넘어간다.
(4) Future Plan
[ ] Finish fake LinkedIn + GitHub profiles and age them for a few days. : 가짜 링크드인 및 깃헙 페이지 설정 및 며칠간 계정을 숙성(aging)시키는 과정까지 해서 계정의 신뢰도를 높이는 작업까지 계획한 상태.
[ ] Join Korean security / crypto groups and casually interact to build trust.: 자연스럽게 한국 보안, 크립토 커뮤니티에 들어가 자연스럽게 질문하고, 활동하고, 댓글 남기면서 신뢰를 쌓으려는 전략.
[ ] Finalize phishing email template in both English and Korean.: 다국어 피싱 이메일 준비.
[ ] Deploy cloned VPN login page and test credential logging.: 앞서 발견했다고 알려진 VPN 포털 페이지를 클론 및 로그인 폼을 공격자 서버에 재현, 입력한 아이디/비밀번호를 공격자 서버에 저장(logging)
[ ] Prepare OSINT trail so that investigators (CTF players) can: - find this notes file - pivot from leaked SQL → email addresses → social media → fake profiles → onion/redirector infra. : 사실상 이 부분이 가장 중요하다. 우리를 위해 남겨둔 문제 출제자의 힌트이다. "leaekd SQL 파일이 있고, 여기서 가계정 이메일 주소를 알 수 있으며, 해당 가계정들의 소셜 미디어(위에서 언급된 링크드인, GitHub이겠지), 가계정 정보 알아내고, 이후 경유지 서버를 통해 최종 공격자 서버(C2)까지 알아낼 수 있다"는 것을 이 부분에서 짐작할 수 있다.
2️⃣ db.sql:
decoy flag 발견 / FLAG{KOREAN#1COMMUNITYRR}
- socket puppet 을 만드는데 사용된 듯한 sql 문이다.
- 2개의 socket puppet 이 있어보인다. Soyeong Park, Tony Racoon.
- 그리고 퀴즈 풀이에 쓰이는 것으로 보이는 중간 FLAG. 몇 번 문제 정답인지는 모르지만 우선 확인만 해두자.
3️⃣ Source Code.zip: 공격 시나리오에 쓰인 C2 서버의 소스 코드이다. README.md를 읽어보면 더 자세히 알 수 있다.
💡 잠깐 : HTTP Redirect 개념 이해하기
지금까지 경유지 서버(http://140.238.194.224:8081)를 발견했고, nmap 포트 스캐닝을 통해 열린 포트를 확인했다.(22❌, 80❌, 8081✅). 그리고 열려 있는 8081 포트로 들어가, 공격자 추적을 위한 몇 가지 단서들(타겟 서버 아키텍처, 타 공격자 여부, 내부 인프라 정보, 전반적인 공격 시나이로 등)을 얻을 수 있었다. 이렇게 얻어낸 전반적인 공격 시나리오는 처음 문제에서 주어진 것과 같다.
- SSH 통신: Secure Shell(SSH). 네트워크로 안전하게 다른 컴퓨터에 접속해 명령, 파일 전송, 터널링을 할 수 있게 만드는 통신 프로토콜.즉, 원격 서버에 로그인해서 Linux 터미널을 쓰게 해주는 것. - SSH 접속이 왜 강력한 이유 : SSH에 성공한다는 건 곧, 상대 서버의 OS를 직접 사용할 권한을 얻는다는 것.
- Socket 통신: 컴퓨터끼리 데이터를 주고받기 위해 만들어 놓은 ‘가상의 파이프(연결 통로)’. 소켓(socket)이 바로 이 통로를 “열고/읽고/쓰는 주체”. OS 내부에서는 소켓이 파일처럼 동작.
- 비컨(beacon): 해커가 설치한, 공격자 C2 서버로 주기적으로 연결을 시도하는 프로그램. 타깃 PC 안에 몰래 심어놓은 “스파이” 같은 것.
1. 리다이렉터 22/tcp 로 ssh 접속: 공격자 서버가 피싱 사이트 사이에 경유지 서버 포트 포워딩을 만들기 위해 접속.
ssh -i id_ed25519 spark@redirector_ip
* 포트 포워딩(Port Forwarding) 개념과 사용 이유 :
2. (ssh) 리다이렉터:2222 -> 팀서버:443 Remote Port Forwarding : 경유지 서버의 포트 2222번을 팀서버(공격자 서버) 443번이랑 연결해줘.
이 단계를 통해 리다이렉터 2222 포트 == 팀 서버 443 포트(SSH 터널을 이용한 가상의 직통 회선) 설정. 경유지에 ‘공격자 서버로 향하는 비밀문’ 2222번을 하나 만든 것이라고 생각하면 됨.
3. (socat) 리다이렉터:443 -> 리다이렉터:2222
sudo socat TCP-LISTEN:443,fork TCP:localhost:2222
socat 통신 이용해(외부/피싱사이트) -> 경유지 443포트 == 경유지 2222 포트 == 공격자 서버 443 포트 설정. 이렇게 되면서 “리다이렉터 443 = 팀 서버 443” 으로 생각해도 될 정도가 됨.
이 단계는 왜 필요한가? SSH Remote Port Forwarding(-R)은 리다이렉터의 ‘임의 포트(2222)’에는 바인딩할 수 있지만, 시스템 포트(1~1023, 예: 443(HTTPS 포트) )에는 직접 바인딩할 수 없기 때문. 즉, SSH 기술적 제약 문제.
socket 통신은 왜 필요한가? 그러나 타깃이 콜백할 포트는 반드시 443 이어야 한다. 왜냐하면, 많은 조직 방화벽은 아웃바운드 443만 허용하기도 하고, C2 비컨 트래픽은 HTTPS처럼 보이게 하려고 443 사용하기 때문.
1~3단계에서 공격자가 설정한 포트 포워딩으로, 공격자의 비컨이 경유지를 통해 인터넷으로 나갈 수 도 있고, 반대로 인터넷에서 들어오는 정보 역시 경유지를 통해 공격자 서버로 들어올 수 있게 됨.
정리하면, 이번 단계에서는 경유지 서버 탐색을 통해 해당 경유지가 ssh 연결을 통해 공격자 서버에 연결되어있다는 것을 알 수 있음. 위는 HTTP Redirect 설명 예시 그림이고, 현 문제에서는 443(HTTPS) 포트 대신 80(HTTP)가 사용되었음. 정확히 어떤 포트로 연결되었는 지 등의 자세한 사항은 추후 탐색으로 통해 알 수 있을 듯.
경유지 서버에 "spark"이라는 누군가가 id_ed25518이라는 private key를 가지고 접속을 시도한 게 보인다.
expect는 공격자가 자동 입력을 수행하기 위해 넣은 스크립트로, "Enter passphrase"라는 ssh passphrase 입력하라고 뜨면 send 뒤에 보낼 말을 자동으로 보내라, 는 의미이다. 따라서 해당 부분은 공격자가 경유지 서버로 본인 진짜 서버에서 접속한 흔적이며, 편의성을 위해 ssh 연결을 자동화 시키기 위한 명령어의 흔적으로 보인다.
더하여, ssh private key 로그인은 이러한 passphrase 를 추가 요구하는 보안 강화 설정을 적용할 수 있다. 여기도 그런 케이스이며, send 뒷 부분이 여기서 설정된 passphrase임을 알 수 있다. 나아가 보내는 문자 "" 안 끝쪽에 개행 문자 \r을 넣어준 것은 Enter를 눌러 전송하는 행위와 같다. 따라서 실제 passphrase는 "SSH@@RACOONCOIN!@#\r" 중 개행문자 \r을 뺀 "SSH@@RACOONCOIN!@#" 가 된다.
추후 리다이렉트 서버에 ssh 연결해서 접근할 때 Enter passphrase 어쩌구가 뜨면 "SSH@@RACOONCOIN!@#" 를 복붙해 넣으면 된다.
퀴즈를 따라가는 게 힌트인 줄 모르고 쌩 바닥부터 뚫느라 처음엔 중구난방으로 풀었다. 다 풀고 퀴즈를 #1부터 하나하나 풀며 정리하는 글을 쓰니 애매하게 알던 개념들도 글로 정리하며 제대로 이해하게 되는 시간이었다.
퀴즈를 풀고 다시 퀴즈별로 문제 풀이 복귀를 하는 지금에도 느끼지만, 레드 티밍 공격은 이렇게 글쓰듯이 매끄럽게 한 방향으로 한 번에 쭉- 풀리는 게 아니라, 계속해서 저 몇 단계를 다시 오가는 과정인 것 같다. 언젠가 실력이 쌓이면 한 단계에서 필요한 정보를 모두 한 번에 찾을 수 있을 정도로 실력이 쌓일 수 있으면 좋겠다.
간단하지만 많이 배울 수 있던 RCity 실전 Threat Intelligence 추적 챌린지10 였다.
gRPC는 'google Remote Procedure Call'의 약자입니다. 이는 Google에서 개발한 오픈소스 RPC (Remote Procedure Call) 프레임워크입니다. RPC란 분산 컴퓨팅 환경에서 한 프로그램이 네트워크를 통해 다른 컴퓨터에 있는 프로그램의 프로시저(함수)를 실행할 수 있게 해주는 프로토콜입니다.
쉽게 말해, gRPC는 서로 다른 컴퓨터나 서버가 마치 같은 컴퓨터에서 함수를 호출하는 것처럼 통신할 수 있게 해주는 시스템이에요.
gRPC의 주요 특징
1. 높은 성능: HTTP/2 기반으로 동작하여 기존 REST API보다 훨씬 빠른 통신이 가능합니다. 2. 강력한 타입 체크: Protocol Buffers를 사용하여 데이터 구조를 정의하므로, 타입 관련 오류를 줄일 수 있습니다. 3. 다국어 지원: C++, Java, Python, Go, Ruby, C#, Node.js 등 다양한 프로그래밍 언어를 지원합니다. 4. 양방향 스트리밍: 클라이언트와 서버 사이의 실시간, 양방향 통신을 지원합니다. 5. 높은 효율성: 바이너리 형식의 데이터 전송으로 네트워크 사용량을 줄일 수 있습니다.
gRPC는 어떻게 작동하나요?
gRPC의 작동 방식을 좀 더 자세히 살펴보겠습니다.
1. Protocol Buffers
gRPC는 데이터 직렬화를 위해 Protocol Buffers(protobuf)를 사용합니다. Protocol Buffers는 구조화된 데이터를 직렬화하기 위한 언어 중립적, 플랫폼 중립적인 확장 가능한 메커니즘입니다.
예를 들어, 사용자 정보를 나타내는 Protocol Buffers 정의는 다음과 같을 수 있습니다:
message User {
string name = 1;
int32 age = 2;
string email = 3;
}
이 정의는 컴파일되어 다양한 프로그래밍 언어에서 사용할 수 있는 코드로 변환됩니다.
2. 서비스 정의
gRPC에서는 서비스를 .proto 파일에 정의합니다. 이는 서버가 제공할 메서드와 해당 메서드의 요청 및 응답타입을 지정합니다.
이 예제에서 `GetUser`는 단일 응답을, `ListUsers`는 스트림 응답을 반환합니다.
3. 코드 생성
gRPC 도구는 이 서비스 정의를 기반으로 서버와 클라이언트 코드를 자동으로 생성합니다. 이 생성된 코드는 저수준의 통신 세부사항을 처리하므로, 개발자는 비즈니스 로직에 집중할 수 있습니다.
4. 통신 과정
1. 클라이언트가 로컬 객체에서 메서드를 호출합니다. 2. gRPC 프레임워크가 이 호출을 프로토콜 버퍼 메시지로 직렬화합니다. 3. 메시지는 HTTP/2를 통해 서버로 전송됩니다. 4. 서버에서 gRPC 프레임워크가 메시지를 역직렬화하고 해당하는 서버 메서드를 호출합니다. 5. 서버의 응답도 같은 과정을 거쳐 클라이언트로 전송됩니다.
gRPC vs REST API
REST API는 웹 개발에서 널리 사용되는 아키텍처 스타일입니다. gRPC와 REST는 둘 다 서버 간 통신을 위한 방식이지만, 몇 가지 중요한 차이가 있습니다:
1. 프로토콜: - REST: 주로 HTTP/1.1을 사용 - gRPC: HTTP/2를 사용하여 더 빠른 통신과 스트리밍을 지원
2. 데이터 형식: - REST: 주로 JSON이나 XML을 사용 - gRPC: Protocol Buffers를 사용하여 더 작고 빠른 바이너리 형식 사용
3. API 계약: - REST: OpenAPI(Swagger)와 같은 도구로 문서화 - gRPC: .proto 파일로 서비스를 정의하고, 이를 통해 클라이언트/서버 코드 자동 생성
4. 양방향 스트리밍: - REST: 기본적으로 지원하지 않음 - gRPC: 양방향 스트리밍을 기본적으로 지원
5. 언어 지원: - REST: 거의 모든 프로그래밍 언어에서 사용 가능 - gRPC: 주요 언어 대부분 지원하지만, REST보다는 제한적
6. 사용 편의성: - REST: 익숙하고 이해하기 쉬움, 브라우저에서 직접 테스트 가능 - gRPC: 초기 설정이 더 복잡할 수 있으나, 장기적으로 타입 안정성과 성능 이점
gRPC의 사용 사례
gRPC는 다음과 같은 상황에서 특히 유용합니다:
1. 마이크로서비스 아키텍처: 여러 작은 서비스 간의 효율적인 통신에 적합 2. 실시간 통신 시스템: 낮은 지연시간과 높은 처리량이 필요한 경우 3. 다국어 환경: 서로 다른 프로그래밍 언어로 작성된 서비스 간 통신 4. 리소스 제한 환경: 모바일 앱과 서버 간 통신 등 네트워크 대역폭이 제한된 환경 5. 대규모 데이터 처리: 대량의 데이터를 효율적으로 전송해야 하는 경우
결론
gRPC는 현대 백엔드 개발에서 중요한 기술입니다. 높은 성능, 강력한 타입 체크, 다국어 지원 등의 특징으로 인해 특히 마이크로서비스 아키텍처에서 큰 강점을 발휘합니다. 처음에는 개념이 복잡하게 느껴질 수 있지만, 실제로 사용해보면 그 강력함을 체감할 수 있습니다. REST API에 익숙한 개발자라면 gRPC를 배우는 것이 새로운 도전이 될 수 있지만 그만한 가치가 있습니다.
테스트 코드(Test Code)란 소프트웨어 개발 후 기능과 동작을 테스트하는 데 사용되는 코드이다. 개발자가 예상한대로 프로그램이 실행하는 지 확인하는 역할을 한다. 어떤 기능을 테스트할 것인지에 대해 각각 테스트 케이스를 분류하고, 다양한 라이브러리와 프레임워크를 이요해 작설항 수 있다. 테스트 코드를 작성하면 그만큼 자원이 더 낭비된다는 단점이 있지만, 이를 뛰어넘는 장점이 있기 때문에 사용이 권장된다.
장애 방지: 테스트 코드를 통해 출시 이전 소프트웨어의 결함을 찾아내고 미리 수정을 할 수 있다. 이를 통해 회사는 고객 신뢰도를 지키고 낭비되는 장애 복구 비용을 절약할 수 있다.
협업 증진: 중간 작업 결과를 쉬벡 공유할 수 있는 수단이 된다. 불필요한 문서 작업 대신 테스트 코드 결과를 보여주면 되니 협업 과정이 훨씬 빨라진다.
코드 품질 향상: 개발 과정에서 반복적인 테스트와 버그 수정을 통해 전반적인 소프트웨어 품질을 향상시킬 수 있다. 또한 의존성이 높은 코드에 대한 테스트 코드는 짜기 어렵다는 특성 때문에, 테스트 코드를 작성하는 과정에서 의존성이 낮은 좋은 코드를 개발할 수 있게 된다.
리팩토링 지원과 코드 자신감: 테스트 코드가 존재하면 코드 수정, 특히 구조 변경과 같은 대규모 수정에 있어 좀 더 안심하고 진행할 수 있다. 코드 수정 시 기능이 전과 같이 돌아가지 않을 걱정이 생기는 것은 개발자로서 보편적으로 겪는 고민인데, 테스트 코드를 통해 대규모 리팩토링 진행하면서도 정상적으로 동작하는 지 확인 가능하기 때문이다.
2. 테스트 코드의 종류와 예시
테스트 코드는 무엇을, 왜 테스트 하느냐에 따라 종단 테스트(E2E), 통합 테스트(Integration), 단위 테스트(Unit Test), 정적 테스트(Static) 등 다양한 종류가 있다. 아래는 Kent.dot.C가 테스트 코드 분류를 설명한 테스트 코드 트로피이다. (KentDotC가 리액트의 저명사인만큼 프론트엔드에 좀 더 치우쳐져 있는 점은 고려해야 한다.) 그 외에 Snapshot 테스트 등 다양한 테스트가 다양한 이름으로 불리우고 있지만, 크게 아래 4가지 분류 안에 속하는 것 같다. 특히 이 중 Unit Testing과 Integration Testing이 개발 시 가장 많이 사용되는 듯 하다. 그럼 한 번 각자 간단히 알아보자.
소프트웨어를 실행하지 않은 상태에서 오류를 찾아내는 테스트 방법이다. 정적 테스트에는 코드 리뷰, 워크 스루, 인스펙션, 정적 분석 도구 사용 등 다양한 방식이 포함된다. 코드 리뷰(Code Review)는 개발자가 작성한 코드를 동료 개발자들이 검토하는 과정이다. GitHub 등에서 PR 날리고 merge 전에 하는 그 과정 말이다. 워크 스루(Walkthrough)는 좀더 본격적인 팀 간의 코드 검토 과정으로, 작성된 코드나 문서를 작성자가 설명하고 팀이 이를 검토하는 비공식적 회의이다. 자신의 코드를 PPT로 소개하고... 단체 피드백을 받는 그런 과정을 말하는 듯 하다. 인스펙션(Inspection)은 코드나 문서의 결함을 체계적으로 찾기 위해 사전에 준비된 체크리스트와 절차를 따르는 공식적 검토 과정이다. 마지막으로 정적 분석 도구(Static Analysis Tools)는 평소 사용하던 ESLint가 그 대표적인 예이다. 코드 규칙을 검사하고, 잠재적 오류를 탐지해 개발 초기 단계에서 버그를 발견할 수 있다.
2. 단위 테스트(Unit Testing)
더 이상 나눌 수 없는 가장 작은 단위의, 다른 기능과 섞이지 않은 독립적인기능을테스트한다. 라이브러리는언어에따라다양하게존재하며대표적으로는 JavaScript의 Jest, Java의 JUnit이있다. 참고로 단위테스트코드를먼저작성한뒤이에따라기능을작성하는 TDD(Test-Driven Development)를통해개발하면불필요한기능개발에들어가는시간을줄일수있다.
아래는 단위 테스트 코드의 개념을 이해하기 위한 간단한 예시이다. 각각의 독립적인 기능1(sum), 기능2(subtract)을 Jest 라이브러리를 이용해 각각 테스트하는 코드이다.
export function sum(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
import { sum, subtract } from "./utils"
describe('산수 계산 함수 테스트', () => {
test('1+2의 결과는 3이다.', () => {
expect(sum(1, 2)).toBe(3);
})
test('1-2의 결과는 -1이다.', () => {
expect(subtract(1, 2)).toBe(-1);
})
})
3. 통합 테스트(Integration Testing)
각 독립적인 기능들의 상호 작용을테스트한다. 기능들이 각각 잘 동작한다면, 이것들이 모여서 함께 동작할 때도 잘 돌아가는 지 테스트한다. 대표적인통합테스트코드라이브러리로는 JavaScript의 Testing Library과 Storybook, Java의 testcontainers 등이 있다. 각 통합 단위에 따라(화면 단위인지, 기능 단위인지), 대상에 따라(UI만 테스트, 기능만 테스트, 둘 다 테스트) 다양한 테스트가 있는 것 같다. 예를 들어 프론트엔드에서의 화면 단위 UI 테스트인 Snapshot 테스트도 여기에 해당된다(고 이해했다.)
사용자의 입장에서 소프트웨어가 처음부터 끝까지 정상적으로 흐름이 이어지는 지 확인하는 테스트이다. 보통 E2E 테스트라 불린다. 이러한 E2E테스트는 UI뿐만 아니라 기능까지 테스트하기 떄문에 시간과 비용이 많이 든다는 단점이 있다. GUI를 통해 화면에 컴포넌트가 실제로 렌더링 되는 모든 과정까지 테스트하고, 서버에 실제로 API 요청을 보내기 때문에 다른 테스트와는 차원이 다른 시간과 비용이 소모되며, 테스트 실패 가능성도 높다. 따라서 E2E 테스트는 중요한 기능 위주로만 적용해야 한다. 보통 실제 서비스에서는 서비스 장애를 잡을 목적으로 일정 시간(ex. 4시간) 이러한 E2E 테스트가 동작하도록 테스트 자동화를 해둔다고 한다. 사용 라이브러리로는 Cypress, Playwrite 등이 있다.
3. 어떤 테스트 코드를 언제 써야할까?
https://martinfowler.com/bliki/TestPyramid.html
다양한 테스트 코드의 종류와 그 쓰임에 대해 알아보았다. 종류마다 쓰임이 다른 것처럼 그 비용도 다 다르다. 그리고 실세계에서는 우리는 늘 그 비용을 고려할 수 밖에 없다. 그 유명한 "테스트 피라미드" 개념에 따르면 테스트 비용은 앞서 설명된 Static, Unit 단위에서 가장 저렴하고 빠르게 시행할 수 있으며, 로직이 섞이는 Integration 단위부터 비용과 그 무게가 증가한다. Server와 통신까지 필요해지는 E2E 테스트는 그 값이 비싸지고 가장 시행하기 무겁다.
이러한 테스트 특징을 고려했을 때, 쓰임과 비용을 고려해 적절히 사용하는 것이 좋다. Martin Fowler은 무겁고 값이 비싼 E2E 테스트만 시행하고 버그를 통해 고쳐나가기보다는, 작고 가벼운 Unit Testing와 Integration Testing 을 자동화하여 더 자주 실행하는 것을 추천한다. "So the pyramid argues that you should do much more automated testing through unit tests than you should through traditional GUI based testing." 추가적으로, Kent C. Dodds는 그 중 가장 가성비 좋은 Integration 단위 테스트를 가장 많이 사용할 것을 권장한다. "Write tests. Not too many. Mostly integration.”
두 거장에게서 반복적으로 언급된 통합 테스트(Integration Testing)는 앞서도 간략히 설명했지만, 통합 단위에 따라(화면 단위인지, 기능 단위인지), 대상에 따라(UI만 테스트, 기능만 테스트, 둘 다 테스트) 등 다양한 기준에 따라 다양한 테스트가 있는 것으로 보인다. 특히 다양한 컴포넌트들 화면 단위로 테스트를 하는 UI 통합 테스트인 Snapshot test와, API개발이 미뤄지는 현업 상황에서 기능 테스트를 실용적으로 도와줄 msw와 jest를 사용한 통합 기능 테스트, 이 2가지 통합 테스트가 프론트 개발에서는 가장 효율성 좋은 Integration Testing이지 않을까 생각한다. 여기서 한 발짝 더 나아간다면, 정말 '이 기능 오류나면 서비스가 망한다' 싶은 중요한 기능들만 추려 Cypress를 통해 E2E테스트까지 적절한 텀으로 자동화해 시행하면 좋지 않을까 싶다.
4. 통합 테스트(Integration Testing) 직접 적용해 보기: msw, jest, Storybook
1. 서문 2. React에서 상태를 관리하는 방법 - 기본 상태 관리 방법 - 내부 기능 훅 사용하기 - 외부 라이브러리 사용하기 3. 상태 관리를 "잘"하는 방법
1. 서문
최근 공개된 Figma Config 2024에도 나왔고, IT업계 선두 쪽 회사에 다니는 지인들로부터도 Figma, Framer 등을 활용한 디자이너와 프론트엔드의 경계가 모호해진다는 등 여기저기서 소리가 들려온다. 변해가는 프론트엔드 역할을 볼 때 프론트엔드 개발자하면 더 기대되는 부분은 UI적 부분보다는 "데이터"를 다루는 "상태관리"를 얼마나 잘 하는지인 것 같다는 생각을 했다[글].
사실 상태 관리는 어렵다. 왜 어려울까. 무효화, 동기화, 파생 상태, 서버 재요청 등 예기치 못한 리렌더링의 상황이 많아서이다. 개인적으로 이 상태 관리가 너무 어려워서 고생도 많이 했다. 이러한 중요성과 개인 생산성을 고려해서 상태 관리를 제대로 공부해보기로 했다.
상태관리란 무엇이며, 어떻게 해야하는 것일까. 어떻게 하는 것이 상태관리를 "잘"하는 것일까?
2. React 에서 상태를 관리하는 방법
"상태 관리"란 무엇인가요?
리액트에서 상태(state)란 컴포넌트 속 데이터를 의미합니다. 이러한 상태는 시간에 따라, 사용자와의 상호작용에 따라 업데이트 되며, 이렇게 변화하는 상태를 앱의 다양한 부분이 서로 일관되게 공유하여 사용자의 상호작용에 올바르게 반응하게 해주는 관리를 상태 관리라고 합니다. 상태 관리에는 컴포넌트 내부의 데이터의 변화를 관리하는 지역적 상태 관리(local statement management)와 컴포넌트와 외부 컴포넌트끼리의 상태 공유를 관리하는 전역 상태 관리(global statement management)가 있습니다.
2-1. 기본 상태 관리 방법
- state 란... -props란... - state를 업데이트 하는 방법,setState - props를 업데이트 하는 방법,propsDrilling
상태를 관리하는 데에 있어 라이브러리가 반드시 필요할까요? 아니요. 리액트에서 상태 관리를 하는 기본적인 방법은 컴포넌트의 state와 props를 사용하는 것입니다.
props 는 부모 컴포넌트로부터 전달 받은 데이터를 의미합니다. 컴포넌트의 state는 setState 함수를 통해 업데이트할 수 있으며, 이 과정에서 리액트는 컴포넌트를 재렌더링하여 변경된 데이터를 사용자에게 보여줍니다.
그러나 이것은 컴포넌트 내부의 상태 관리일 뿐, 어플리케이션을 효과적으로 동작하게 하기 위해서는 여러 컴포넌트 간에 상태를 공유하고 관리할 수 있어야 합니다. 리액트는 단방향 흐름인 Flux 패턴을 바탕으로 하므로, 데이터 흐름이 단순하지만 단계별로 일일이 props를 넘겨주어야 하는 번거로움이 있습니다. 이는 규모가 큰 애플리케이션에서는 번거롭고, 오히려 데이터 관리가 복잡해지는 결과를 낳기도 합니다.
따라서 트리 단계마다 명시적으로 props를 넘겨주지 않아도 컴포넌트 트리 전체에 데이터를 제공할 수 있게 만들어주는 상태 관리 라이브러리는, 복잡한 상태 관리가 필요한 경우 사용하는 것이 효율적인 면에서 필요하다고 생각합니다.하지만 반드시 외부 라이브러리를 사용할 필요를 의미하진 않습니다. 앱의 규모가 크지 않다면, 기본적인 상태 관리 방법인 state, props만 사용하거나 내부 상태 관리 라이브러리인 useContext와 useReducer 등을 사용하는 것을 고려해 볼 수 도 있습니다.
리액트에서 상태를 관리하기 위해 상태관리 라이브러리가 반드시 필요하지는 않습니다. 하지만 앱의 규모가 커질 수록, 상태를 공유해야 하는 컴포넌트 사이의 거리가 멀수록, 컴포넌트끼리의 상태 공유를 보다 효율적하기 위해서 전역 상태 관리는 반드시 필요합니다. 예전 클래스형 리액트를 사용할 때는 이러한 전역 상태 관리를 위해 Redux 등 외부 라이브러리를 사용해야 했습니다. 그러나 2019년, React 16.8에서 훅(Hook) 기능을 소개하며, 여러 편리한 기능과 함께 상태 관리에 대한 대안을 제시했습니다. 특히 이러한 훅 중 useContext, useReducer 의 훅을 사용하면 반드시 외부 라이브러리를 사용할 필요 없으며, 이를 훅을 이용한 상태관리라고 하기도 합니다. 이러한 훅은 기본적으로 함수이며 use...로 시작하는 것이 관례입니다.
useContext, useReducer와 useState
useContext와 useReducer, 그리고 앞서 배운 useState는 사실 이러한 훅 중 상태 관리 기능에 특화된 훅입니다. useState가 상태 그 자체와 상태를 업데이트하는 함수를 동시에 정의한다면, useContext와 useReducer는 각각 상태와 상태 업데이트 방식을 그 기능을 확장하여 분리한 개념입니다.
useContext에서 컨텍스트(Context)는 모든 컴포넌트에서 직접 접근 가능한 전역 데이터 객체로, 단순 지역 상태를 넘어 전역적으로 어느 컴포넌트에서든 접근하고 사용할 수 있는 상태 정보를 가진 거대한 컨테이너(객체) 같은 개념입니다. 이러한 useContext를 사용하여 언제 어디서든 모든 컴포넌트가 공유하는 상태를 꺼내 사용할 수 있게 됨으로써, 전역 상태 관리가 가능하게 해지고 외부 라이브러리 사용의 필요성이 낮아지게 되었습니다.
한편 useReducer는 상태 업데이트 방법으로, useState에서 제공하는 상태 업데이트 방식보다 더 복잡한 상태 업데이트를 보다 간단한 방식으로 처리해줍니다. useReducer의 동작 원리에 대해 설명하기 전, 미리 말씀 드리고 싶은 부분이 있습니다. 리액트는 이 두 훅에 의해서만 상태 변화를 인지합니다. 주의할 점은 이 두 훅이 아닌 다른 방식으로 상태를 업데이트하면 리액트는 상태 변화를 인지하지 못하기 때문에 리렌더링이 원하는대로 발생하지 않을 수 있습니다. 이는 뒤 3.상태관리를 잘하는법에서 더 자세히 다루겠습니다. 또한 useContext와 useState, useReducer의 구분은 전역/지역 상태의 구분이라기보다는, 상태/상태 업데이트 방식의 구분입니다. 전역/지역 상태는 상태의 범위를 컴포넌트 내부로 제한하느냐, 아니냐에 따라 나눈 구분이며, 상태/상태 업데이트 방법은 지역성과 상관없이 역할에 대한 구분이므로 헷갈리지 않으시면 좋겠습니다.
이제 useReducer의 동작 원리에 대해 살펴보겠습니다. useReducer는 외부 상태 관리 라이브러리인 Redux와 유사합니다. 두 라이브리 모두 Flux 패턴을 사용합니다. Flux 패턴은 단방향으로 데이터 변경이 이루어지는 구조로, 다음 네 가지 개념으로 구성됩니다: Action, Dispatcher, Store(Model), View.
Action: 변경 데이터와 변경 로직 타입을 정의합니다.
Dispatcher: 구체적인 변경 로직을 담당합니다. useReducer의 reducer가 이 역할을 수행합니다.
Store(Model): 상태를 저장합니다.
View: 상태를 기반으로 UI를 렌더링합니다.
useReducer의 reducer는 state(기존 정보)와 action을 받아 기존 데이터를 업데이트하는 역할을 합니다. 결국 useReducer는 state와 state를 변경하는 동작(dispatch)을 하나로 합친 형태입니다. 따라서 state를 여러 번 언급할 필요가 없고, 여러 곳에서 반복되는 업데이트 로직을 reducer에 한 번만 정의한 후 여러 곳에서 사용할 수 있어 코드가 더 간결해집니다. 이는 코드의 직관성을 높여줍니다.
useReducer는 여러 상태를 효율적으로 관리하고, 업데이트 로직을 단순화하여 코드를 간결하게 만들어주는 훅입니다. (*reducer: a function that reduce one or more complex values to a simpler one.) 이는 Redux와 같은 상태 관리 라이브러리의 패턴을 따르며, 복잡한 상태 관리가 필요한 경우 유용합니다. useState는 단 하나의 상태만 관리할 수 있지만, useReducer를 이용하면 동시에 여러 상태들을 한 번에 관리할 수 있게 됩니다. 이러한 useReducer는 2024년 2월 기준 useState를 구현되어 있으며, 따라서 useState로 useReducer를 구현하는 것은 100%로 가능합니다. (향후 더 효율적으로 구현될 수 도 있습니다.) useReducer는 useState와 비교하여 순수함수이며, 외부에서 정의가 가능한 등 마이너한 차이점이 있지만, 특별한 사항이 아니면 중요치 않기 때문에, 기본적으로 useState와 useReducer는 기본적으로 동일며 상호 교환도 가능하다고 봅니다. 다만, useReducer 함수는‘순수함수’(어떤 상황이든 같은 input이면 같은 output을 내뱉는, 외부와 독립적이어 사이드이펙트가 없는 함수)라 동작을 테스트하기 더 쉽다는 이점으로 더 선호되는 부분도 있습니다.
2-3. 외부 라이브러리 사용하기
상태관리외부라이브러리는전역적인상태관리를돕는전역상태관리라이브러리와특정상태의특수성을고려한 특수 목적형 상태관리라이브러리로나뉩니다. 예를들어, 전역 상태 관리 라이브러리에는 Redux, Recoil, 그리고 MobX 등이 있으며, 특정 상태 관리 라이브러리는 서버상태관리를돕는react-query, 폼의상태관리를돕는Formik등이있습니다. 이 중 실제로 사용해 본몇가지를 특징과 함께 사용 후기를 비교하여 설명해보고자 합니다.
왜 OO라이브러리를 사용하셨나요?
이런 질문은 항상 면접에서 빠지지 않고 듣는 것 같습니다. 그만큼 라이브러리를 무작위로 사용하지 않고 특징을 파악해 사용해 불필요한 리소스 사용을 줄이는 것이 엔지니어로서의 덕목이기 때문이겠죠. 우선 직접 사용해본 전역 상태 관리 라이브러리 두 가지를 공부하고 사용하며 느낀 그 특징을 설명해보겠습니다. 이를 바탕으로 질문에 답할 수 있을 것입니다.
1. Redux
Redux는가장오래된상태관리라이브러리입니다. React Hooks(2019년 2월)보다이전에출시(2015년 6월)되어, 클래스형컴포넌트로상태를관리하던시절부터 전역 상태 관리를 위해 사용되던 상태관리의조상격라이브러리입니다. 특징은 아래와 같습니다.
Redux의 기본 동작 원리와 특징: Flux 패턴
단방향 데이터 흐름: 상태 추적이 일관적이고 쉬워 팀원들 간에 공유하기 쉽습니다. Action, Dispatcher, Store(Model), View로 이루어진 Flux 패턴의 단방향 흐름은 앞서 useReducer를 설명하며 간단히 언급하였습니다. 더 자세한 동작 방식은 다음 글을 참조할 수 있습니다.
순수 함수: 역시 앞서 설명되었지만, 순수함수는 어떤 상황이든 같은 input이면 같은 output을 내뱉는, 외부와 독립적이어 사이드이펙트가 없는 함수를 의미합니다. 이러한 특성 덕분에 무한 되돌림, 무한 재생이 가능하며, Redux의 특징인 시간 여행도 가능합니다.
보일러플레이트 코드: 특정 패턴을 바탕으로 하기 때문에 설정 과정에서 많은 보일러플레이트 코드가 필요하여 진입 장벽이 높습니다.
그 외 특징: 커뮤니티 지원
DevTools: 강력한 개발 도구를 제공합니다.
방대한자료: 가장오래된상태관리라이브러리로관련자료가많습니다.
2. Recoil
Recoil은 2020년 5월에 Facebook의 일부 React 개발자들이출시하였으며, 현재많은개발자들에게인정을받고있습니다.
Recoil의 기본 동작 원리
분산 상태: Recoil은 상태를 여러 작은 Atom(state)으로 나누어 관리할 수 있게 해줍니다. 이는 상태 관리의 복잡성을 줄이고, 특정 상태 변경이 애플리케이션 전체에 영향을 미치지 않도록 합니다.
증분 상태: Recoil의 Selectors는 파생된 상태(derived state)를 관리하기 위해 사용되며, 다른 Atom이나 Selector의 값을 기반으로 계산됩니다. 이는 상태의 재사용성을 높이고, 필요에 따라 상태를 동적으로 계산할 수 있게 해줍니다.
useRecoilState: Recoil에서의 상태 업데이트 방법입니다.
그 외 Recoil의 특징
지엽적인 상태 관리: Atom식 상태 관리 특징에 따라 지엽적인 상태 관리가 더 많이 필요한 서비스의 경우 사용되면 좋을 것이라 판단됩니다. 전체적인 팀 공유가 어려워 질 수 있다는 단점이 있지만, 특정 상태 관리가 더 필요한 경우 유용합니다.
낮은러닝커브와진입장벽: React의 Context API와 거의 동일한 방식으로 상태를 사용하나, 1) Provider로 감싸줄 필요가 없고, 사용법이 더 직관적이고 쉽습니다. 3) React에 익숙한 사람이라면 이미 익숙한 개념이라 배우기 쉽습니다.
불완전한 개발 도구: Redux처럼 시간 여행 등의 기능이 있지만, 아직 완전하지는 않습니다. 문서 보기.
- 애초에 불필요한 상태를 만들지 않기 - 상태 변경시 불변성을 고려하기 - 리렌더링 성능을 최적화하기: memo(), useCallback() - 컴포넌트 생명주기와 상태의 주기를 같이 하기: useEffect()
리액트의 "불변 철학"이란 무엇인가요? 리액트의 "상태 감지"에 대해 아는대로 말해주세요.
리액트는상태변경시기존상태를직접수정하지않고새로운상태객체를반환하는불변성을중요시합니다. 이는상태관리의예측가능성을높이고, 상태변경의추적을용이하게합니다. 이는 리액트의 상태 감지 방식에서 유래합니다. 리액트는 상태 변화를 객체의 참조(주소)가 변경될 떄만 상태 변화로 인식하는 "얕은 참조"를 통해 변화를 감지합니다. 따라서 원시 값의 변경이나 같은 객체의 반환은 리렌더링을 일으키지 않습니다. 또한 앞서 언급되었듯 "useState와 useReducer"를 통해 관리되는 상태 변화만 감지합니다. 일반 변수 값의 변경은 감지하지 못해 리렌더링이 일어나지 않습니다. 따라서 같은 객체를 반환하거나 원시 값의 변경, useState 혹은 useReducer를 사용하지 않고 상태를 변경하는 경우 등은 베일 아웃을 야기할 수 있습니다. 이러한 리액트의 불변성을 고려하여 상태 변경을 진행해야 합니다.
React의 리렌더링 최적화
React는 렌더링은 두 번 일어납니다. 최초 앱을 실행할 때 한 번의 렌더링, 그리고 상태 변화가 감지되었을 때(리렌더링). 리렌더링이 발생하는 경우는 두 가지입니다. 첫째, 부모 컴포넌트의 리렌더링. 이 경우 하위 컴포넌트는 상태 변화와 상관 없이 전부 리렌더링됩니다. 둘째, 컨텍스트의 변경. 컨텍스트의 상태 변경 시, 해당 컨텍스트를 사용하는 모든 컴포넌트는 리렌더링 됩니다. 상태가 감지가 되면 리액트는 모든 부분이 아닌, 변화된 부분에 한해서 리렌더링합니다. 정확히는 상태가 변화하는 컴포넌트와 그의 모든 하위 컴포넌트를 리렌더링합니다. 변화한 부분만 리렌더링하는 자세한 내부 동작 원리는 아래와 같습니다.
가상 DOM 업데이트: 상태가 변경되면, React는 새로운 가상 DOM을 생성합니다. 가상 DOM은 실제 DOM의 가벼운 복사본입니다. 이 단계에서는 메모리 내에서만 작업이 이루어집니다.
비교 (Reconciliation): 새로운 가상 DOM과 이전 가상 DOM을 비교합니다. React는 이 비교 과정을 통해 변경된 부분을 찾아냅니다. 이를 "diffing algorithm"이라고 합니다.
실제 DOM 업데이트: 변경된 부분만 실제 DOM에 반영합니다. 이렇게 함으로써 성능을 최적화하고 불필요한 DOM 업데이트를 피할 수 있습니다.
리엑트에서의 리렌더링을 이해했다면, 상태가 업데이트되지 않은 컴포넌트의 불필요한 리렌더링 방지가 필요합니다.
이러한 불필요한 리렌더링을 방지하는 방법을 알고 있는대로 정리하면 아래와 같습니다.
애초에 잘 배치하기(Clever Structuring) 여러 컴포넌트에서 해당 상태 사용시, 하나의 컨테이너 안에서 상태 변경을 이루게 하기 위해 반드시 해당 컴포넌트들의 공통 상위 컴포넌트에 위치시켜야 합니다. 이를 상태 끌어올리기(lift state up)이라고 합니다. 만약 각각의 컴포넌트 안에서 useState를 사용해 상태를 다루게 된다면, 이는 사실상 각각 다른 컨테이너, 즉, 다른 문맥(ex. count container1, count container 2 등)을 사용하는 것이기 때문에, 추측과 다르게 렌더링이 일어나지 않는 리렌더링 오류가 발생할 수 있으니, 반드시 상태 끌어올리기를 사용해야 합니다. 공통된 상태를 공유하는 가장 낮은 컴포넌트에 적절히 상태를 잘 위치시키며, 컴포넌트 트리 구성과 리렌더링 상태를 염두에 두고 컴포넌트를 구성하는 것이 필요합니다.
memo: 부모 컴포넌트의 리렌더링으로 인해 발생하는 불필요한 하위 컴포넌트의 리렌더링을 막기 위해 memo를 사용합니다. 컨텍스트를 사용하지 않는 하위 컴포넌트도 부모의 리렌더링으로 불필요하게 리렌더링 되는 경우, 이 때 memo()를 활용한다. 즉, memo는 컨텍스트 변경이 없다면(부모 렌더링으로 인한 렌더링은 못막지만) 리렌더링을 막아줍니다. 그러나 성능 향상을 위해 memo를 무작위로 사용하는 것은 좋지 않습니다. memo의 동작 원리는, 상태 변경 시 memo로 감싼 컴포넌트의 prop의 변화를 확인하는 것입니다. prop의 변화가 있을 경우만 컴포넌트를 리렌더링합니다. 이러한 동작 원리를 이해했을 때, 불필요한 props-checking이 발생하여 성능이 저하되는 것을 막기 위해서는 꼭 필요한 상위 컴포넌트를 잘 선택해 memo를 감싸는 것이 중요합니다. 상위 컴포넌트가 리렌더링 되지 않는다면 하위 컴포넌트 역시 리렌더링 되지 않을 테니까요.
useRef와 useEffect: useRef과 useEffect는 모두 렌더링 사이클과 관계없이 값을 유지해야 할 때 사용하는, 상태 관리에 도움을 주는 훅입니다. 먼저 useRef는 렌더링 사이클과 관계없이 값을 유지하는 것 + DOM과의 연결이 필요할 때 사용합니다. useEffect는 컴포넌트의 생명 주기(마운트, 업데이트, 언마운트)를 보다 간결하고 효과적으로 관리하기 위해 탄생한 훅으로, 컴포넌트의 생명 주기를 따라 동작합니다. 부수 효과(데이터 페칭, 구독 설정, 타이머 설정, DOM 조작 등)를 렌더링 로직과 분리하는 데 사용하면 효과적입니다. 모든 함수가 그러하지만 특히 useEffect 의 경우 함수를 잘 사용하는 것이 중요합니다. 아니면 상태 관리 시 꼬인 상태 때문에 곤욕을 치룰 수 있기 때문입니다. 그 방법은 다음과 같습니다. 첫째, useEffect 함수 안에는 렌더링 로직과 상관 없는 동작만 넣어야 합니다. 즉, 상태 변화를 일으키는 setState 함수 등이 들어가면 안됩니다. 리액트는컴포넌트가리렌더링될때마다useEffect를호출하므로,불필요한부수효과를방지하기위해상태변경로직은useEffect외부에서처리해야합니다. 둘째, cleanup 함수를 작성합니다. 개발 모드에서 컴포넌트가 리렌더링될 때 useEffect가 두 번 호출되는 경우를 대비해 cleanup 함수를 작성해야 합니다. useEffect 내부에서 상태 변경 훅(useState, useReducer)을 사용하지 않도록 주의합니다.
최근 공개된 Figma Config 2024에서 새로 공개한 Figma의 기능을 보면 점점 디자이너와 프론트엔드의 경계가 모호해지는 것 같다. IT업계 선두 그룹에서 인턴을 경험한 지인도, Figma, Framer 등을 활용해 디자이너의 디자인을 코드로 변환시킨 것을 프론트엔드 개발자가 조금 다듬고 서버와 연결 지어 업데이트 한다고 했다. AI가 디자인까지 해버리고 그걸 코드로까지 내놓는 세상이 왔다. 디자이너도, 프론트엔드 개발자의 역할도 달라지고 있다. 디자이너분들의 의견도 궁금하긴 하지만, 난 개발자니 개발자의 역할은 어떻게 달라질지를 생각해본다.
직업은 사라지고 생겨난다. 그 역할이 조금씩 변하기도 한다. AI의 등장으로 결국 가까운 다음 대세는 AI를 잘 활용하는 인재와 AI가 할 수 없는 부분을 할 줄 인재가 대우 받겠지. 비기술적으로는 고유성과 창의성을 지닌 경영, 영업, 기획, 디자인 부분이나, 기술쪽으로는 AI가 (아직까지는) 파악하기 어려운, 데이터를 위한 데이터 구조를 짜는 백엔드 직군이 더 강력해질 거란 생각이 든다. 즉, 결국 감각적이고 창의적인 기획으로 인간의 고유 기술을 갈고 닦거나, 아니면 결국은 "데이터"를 다루는 것이 중요해질 거란 생각이 들었다.
프론트엔드직군의 경우, PC의 대중화로 혜성처럼 등장했고, 모바일앱의 유행으로 CSR이 유행하는가 하더니 Next.js의 등장으로 SSR으로 다시 돌아와 서버쪽도 결국은 다뤄야 하는 방향으로 가고 있다. AI의 등장으로 디자인을 반영하고 프론트측 데이터를 다루던 역할에서 디자인의 영역은 점점 그 중요성이 사라지고 있는 것 같다. 이번 Figma Config를 보면 이제 정말 CSS쪽 지식의 입지는 점점 작아지는 게 보인다. 유지보수 관리가 쉽도록 회사 관리 방식에 맞게 수정해주는 정도는 필요하겠지만, 이제 웬만한 베이스는 AI가 다 깔아주니 말이다. 점점 프론트엔드 개발자의 역할은 프론트 측에서의 "데이터"의 관리쪽에 더 집중되는 것 같다. 아직까지도 AI에게 코드를 부탁하면 '던져주는' 정도이다. 어떻게 하면 더 효율적으로 돌아가며 유지보수가 쉬워지는 코드를 짜는 지는 프론트엔드 개발자 역량에 달린 것 같다. 서비스가 커질 수록 그 역량은 빛이 날 것이고.
또 결국 서비스를 만드는 건 회사에서 사람들이 하는 일 아닌가. AI가 돌아다니면서 협업하고, 부서 돌아다니면서 언제까지 되냐고 쪼고(?), 의견을 조율하고 하지는 않는다. AI는 컴퓨터 속에 있고 제품 생산을 돕지만, 이 각 분야의 생산물을 합쳐 시장에 내놓는 것은 인간들이다. 그리고 그 과정에서 협업이 정말 중요하겠고. 움직이는 하드웨어를 가진 인간으로서 이런 컴퓨터속 AI가 못하는 사람과의 상호작용이라는 걸 잘하는 것도 (지금도 중요하지만 앞으로는 더욱더 빛날 역량이 아닌가 하는 생각이 든다.
프론트엔드의 역할이 달라져가는 이 시대, 결국은 단기적인, "데이터"를 다루는 "상태관리"를 얼마나 잘 하는지, 깊게 다뤄봤는지가 좁혀져가는 입지에서 그나마 중요한 포인트인 듯하다. 능동적인 부분을 찾자면 그렇다.