2024년 7월 14일 일요일

Reentrancy Attack: 블록체인 스마트 컨트랙트의 치명적인 취약점

블록체인 기술이 전 세계적으로 주목받으면서 스마트 컨트랙트(Smart Contract)의 사용이 급격히 증가하고 있습니다. 하지만 그만큼 보안 취약점도 함께 늘어나고 있는데, 그 중에서도 Reentrancy Attack(재진입 공격)은 매우 치명적이고 널리 알려진 공격 기법 중 하나입니다. 이 공격 방법의 원리와 방어 방법을 자세히 살펴보겠습니다.


Reentrancy Attack


Reentrancy Attack이란?

Reentrancy Attack은 스마트 컨트랙트의 취약점을 이용하여, 외부 호출이 끝나기 전에 같은 함수를 반복 호출함으로써 자금을 탈취하는 공격입니다. 특히 이더리움 같은 플랫폼에서 많이 발생합니다. 공격자는 스마트 컨트랙트가 특정 상태 업데이트를 완료하기 전에 재진입하여 여러 번 호출함으로써 계약의 상태를 왜곡시키고 자금을 반복적으로 인출할 수 있습니다.


공격 원리

  1. 스마트 컨트랙트의 취약점 탐색: 공격자는 특정 스마트 컨트랙트 코드에서 외부 호출을 포함하는 함수를 찾아냅니다.
  2. 악의적인 컨트랙트 생성: 공격자는 자신이 통제할 수 있는 악의적인 스마트 컨트랙트를 생성합니다.
  3. 재진입 호출: 악의적인 컨트랙트를 이용하여 원래 스마트 컨트랙트의 함수를 재진입합니다. 이 과정에서 원래 컨트랙트가 상태를 업데이트하기 전에 동일한 함수가 반복적으로 호출됩니다.
  4. 자금 탈취: 재진입이 성공할 경우, 공격자는 스마트 컨트랙트에서 자금을 반복적으로 인출할 수 있습니다.


사례 분석

2016년에 발생한 The DAO 해킹 사건은 Reentrancy Attack의 대표적인 사례입니다. 공격자는 The DAO의 스마트 컨트랙트에서 재진입 취약점을 발견하고 이를 통해 약 360만 이더(당시 약 5000만 달러)를 탈취했습니다. 이 사건은 이더리움 커뮤니티에 큰 충격을 주었고, 결국 이더리움의 하드포크를 초래했습니다.


방어 방법

Reentrancy Attack을 방어하기 위해 다음과 같은 전략을 사용할 수 있습니다.

1. Checks-Effects-Interactions 패턴: 외부 호출 전 상태를 업데이트하고, 그 후에 외부 호출을 수행합니다. 이렇게 하면 재진입 시 상태가 이미 업데이트되어 공격이 무효화됩니다.


function withdraw(uint _amount) public {

    require(balances[msg.sender] >= _amount);

    balances[msg.sender] -= _amount;

    (bool success, ) = msg.sender.call{value: _amount}("");

    require(success);

}


Checks-Effects-Interactions(CEI) 패턴은 스마트 컨트랙트에서 외부 호출로 인한 보안 문제를 방지하기 위해 설계된 중요한 기법입니다. 이 패턴은 상태 변화를 먼저 수행하고 그 후에 외부 호출을 하는 구조로, 재진입 공격을 방지하는 데 유용합니다. 아래는 CEI 패턴을 구체적으로 적용한 예제를 더 살펴보겠습니다.

예제 1: 단순 인출 함수

이 예제에서는 사용자가 자신의 잔액을 인출할 수 있는 스마트 계약을 보여줍니다. CEI 패턴을 사용하여 재진입 공격을 방지합니다.

pragma solidity ^0.8.0;

contract SafeWithdraw {
    mapping(address => uint) public balances;

    // 예치 기능
    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    // 인출 기능
    function withdraw(uint _amount) public {
        // Checks: 인출 금액이 잔액보다 크지 않은지 확인
        require(balances[msg.sender] >= _amount, "Insufficient balance");

        // Effects: 상태를 먼저 업데이트
        balances[msg.sender] -= _amount;

        // Interactions: 외부 호출 수행
        (bool success, ) = msg.sender.call{value: _amount}("");
        require(success, "Transfer failed");
    }
}


이 예제에서 withdraw 함수는 먼저 사용자의 잔액을 확인하고(Checks), 잔액에서 인출할 금액을 차감한 후(Effects), 마지막으로 인출을 수행합니다(Interactions). 이러한 순서를 통해 외부 호출이 이루어지기 전에 상태가 안전하게 업데이트됩니다.

예제 2: 경매 계약

이 예제는 경매 계약에서 최고 입찰자가 인출할 수 있는 기능을 구현한 것입니다. CEI 패턴을 사용하여 입찰자가 인출할 때 재진입 공격을 방지합니다.

pragma solidity ^0.8.0;

contract Auction {
    address public highestBidder;
    uint public highestBid;
    mapping(address => uint) public pendingReturns;

    // 입찰 기능
    function bid() public payable {
        require(msg.value > highestBid, "There already is a higher bid");

        if (highestBidder != address(0)) {
            // 이전 최고 입찰자에게 환불
            pendingReturns[highestBidder] += highestBid;
        }

        highestBidder = msg.sender;
        highestBid = msg.value;
    }

    // 환불 기능
    function withdraw() public {
        uint amount = pendingReturns[msg.sender];
        require(amount > 0, "No funds to withdraw");

        // Checks: 환불 금액 확인
        pendingReturns[msg.sender] = 0; // Effects: 상태를 먼저 업데이트

        // Interactions: 외부 호출 수행
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
    }
}


이 경매 컨트랙트에서 bid 함수는 새로운 입찰자가 기존 최고 입찰자보다 높은 입찰을 할 때, 기존 최고 입찰자의 입찰금을 pendingReturns에 추가합니다. withdraw 함수는 pendingReturns에서 환불할 금액을 먼저 확인한 후, 상태를 업데이트하고 외부 호출을 수행합니다.

위 예제들은 CEI 패턴을 활용하여 재진입 공격을 방지하는 방법을 구체적으로 보여줍니다. 스마트 컨트랙트 개발자는 항상 CEI 패턴을 적용하여 안전한 코드를 작성해야 합니다.

2. Reentrancy Guard 사용: 재진입 방지를 위해 상태 변수를 사용하여 함수가 재진입되었는지를 체크합니다.


bool private locked;


modifier noReentrancy() {

    require(!locked, "No reentrancy");

    locked = true;

    _;

    locked = false;

}


function withdraw(uint _amount) public noReentrancy {

    require(balances[msg.sender] >= _amount);

    balances[msg.sender] -= _amount;

    (bool success, ) = msg.sender.call{value: _amount}("");

    require(success);

}


3. 외부 호출 최소화: 외부 계약 호출을 최소화하여 재진입 가능성을 줄입니다. 필요한 경우, 가능한 한 간단한 형태로 유지합니다.


결론

Reentrancy Attack은 스마트 컨트랙트의 보안에 있어서 매우 중요한 문제입니다. 이 공격을 방어하기 위해서는 코드 작성 시 각별한 주의가 필요하며, 위에서 언급한 방어 전략을 적극적으로 적용해야 합니다. 스마트 컨트랙트 개발자는 항상 코드의 취약점을 사전에 파악하고, 최신 보안 기법을 적용하여 안전한 블록체인 환경을 구축해야 합니다.



2024년 3월 6일 수요일

홈페이지 jQuery 라이브러리에서 CVE-2019-11358 취약점 패치 여부 확인 방법

현재 홈페이지에서 사용 중인 jQuery 라이브러리가 CVE-2019-11358 취약점 패치를 적용했는지 확인하는 방법은 다음과 같습니다.


1. jQuery 버전 확인

홈페이지 소스 코드를 확인하여 jQuery 라이브러리 버전을 직접 확인합니다.

웹 개발자 도구를 사용하여 jQuery 버전을 확인합니다.


2. jQuery CDN 사용 여부 확인

만약 홈페이지에서 jQuery CDN을 사용한다면, CDN URL을 통해 버전 정보를 확인할 수 있습니다.

예를 들어 jQuery 1.12.4 버전은 //code.jquery.com/jquery-1.12.4.min.js URL을 사용합니다. 만약 URL에 1.12.4 이후 버전 정보가 포함되어 있다면, 취약점 패치가 적용된 버전입니다.


3. 취약점 검사 도구 사용

다양한 취약점 검사 도구를 사용하여 홈페이지의 jQuery 버전 및 취약점 존재 여부를 확인할 수 있습니다. npm audit, yarn audit, Snyk, 또는 OWASP Dependency Check와 같은 도구를 사용하여 프로젝트의 의존성을 스캔하고 CVE-2019-11358 취약점에 대한 경고가 사라졌는지 확인합니다. 이러한 도구들은 프로젝트 내에 사용된 라이브러리의 취약점 정보를 제공합니다.

NVD CVE-2019-11358: https://nvd.nist.gov/vuln/detail/CVE-2019-11358

Snyk: https://snyk.io/

OWASP Dependency-Check: https://owasp.org/www-project-dependency-check/


4. 추가 정보

CVE-2019-11358 취약점은 jQuery 1.x 버전에 존재하는 XSS 취약점입니다. 공격자가 악성 스크립트를 실행하여 사용자 정보를 절취하거나 시스템을 손상시킬 수 있습니다. jQuery 3.4.0 이상 버전은 이 취약점에 대한 패치가 적용되었습니다. 취약점 패치를 적용하는 것이 가장 안전한 방법입니다.

jQuery 공식 문서에서 취약점 관련 정보 및 패치 적용 방법을 확인할 수 있습니다.

jQuery Security Advisories: https://github.com/jquery/jquery/security/advisories


이 수정사항은 jQuery 3.4.0에 포함되어 있으나, 이전 jQuery 버전을 패치하기 위한 patch diffs도 있습니다. https://github.com/DanielRuf/snyk-js-jquery-174006


5. 주의 사항

취약점 검사 도구는 100% 정확하지 않을 수 있습니다.

취약점 패치를 적용하기 전에 홈페이지 호환성을 확인해야 합니다.

2024년 3월 4일 월요일

The Complete Guide to Network Equipment Vulnerability Assessment Criteria: An Essential Checklist from a Security Expert

In today's rapidly evolving digital landscape, the security of network infrastructure and the robustness of network devices against vulnerabilities have become paramount for organizations worldwide. 

With cyber threats becoming more sophisticated and pervasive, it's essential to understand the standards for assessing vulnerabilities in network equipment. 

This guide aims to provide a comprehensive overview of the criteria for evaluating network infrastructure security and the vulnerabilities of network equipment. 

By equipping yourself with this knowledge, you can ensure that your network remains impervious to the ever-changing threats, safeguarding your organization's data and assets.



1. Criteria for assessing network infrastructure security vulnerabilities


Configure network line (ISP) redundancy

  • If your network (ISP) line is configured as single, ensure that your network line (ISP) is configured as redundant because a line failure can cause service failure.


Configure network equipment redundancy

  • Ensure that network equipment is configured for redundancy as there is a risk of service failure in case of equipment failure while operating in a single equipment configuration.


Configure information security system redundancy

  • Check whether the information protection system is redundantly configured as there is a risk of service failure in case of equipment failure while the information protection system is operating in a single equipment configuration.

Configure critical server redundancy

  • Check whether the critical server is redundantly configured as there is a risk of service failure in case of equipment failure during operation with a single equipment configuration of the server.

Existence of aging equipment with software and hardware end of support (EOS)

  • Check for end-of-service (EOS) aging equipment, as vendor support for software and hardware can lead to unwanted degradation and failure of equipment, patching of new vulnerabilities, etc.

Having separate zones for recovery in the event of a disaster or failure

  • Whether network sections such as disaster recovery centers or backup centers are in place in case of emergencies such as disasters or failures.

Configure network segregation by business characteristics

  • Check that network segments are appropriately segregated by business characteristics, as a lack of segregation could potentially expose the entire network to risk in the event of a breach.

Configure network segregation between dev/test and production networks

  • In the case of development and test (verification system) servers, there is a possibility that the strength of security settings is set lower than that of production servers, and it may be outside the scope of protection of the information protection system, so check whether the sections are separated and operated separately.

Control user access to critical server sections

  • If access control is not performed from the user's device to the main server section, there is a risk of exposure to unauthorized access and malware, so check whether the user's device is performing control so that only access that meets the user's authorization is allowed when accessing the main server.

Control access between separate network segments

  • Ensure that appropriate access controls are in place with least privilege policies to prevent unauthorized access between segregated network segments based on the nature of the business.

Presence or absence of security policy-unenforced bypass routes

  • Checks for bypass routes to uncontrolled network contacts within segregated network segments.

Lack of access control to unnecessary sections of the external communications network

  • Check whether there are sections or systems that are directly accessible from the outside due to inadequate access control other than DMZ sections that are allowed to be accessed from the external communication network.

Internal Communications Network Public IP Usage Controls

  • Check whether unnecessary public IPs are assigned to the internal communication network because public IPs are directly accessible from the outside and may allow inappropriate access.

Whether to block external communication network for information system (server, DB) located in the internal section

  • If the internal server can access the external communication network, there is a risk of information leakage or virus infection, so check whether the internal section information system is allowed to access the outside.

Adequacy of access control to external and internal communication networks (groupware, etc.) from critical devices

  • There is a risk of malware infection due to access to the external communication network from critical devices, and there is a possibility of leakage or destruction of important information.

Whether you recognize the failure and have a plan in place to respond

  • Check whether a monitoring system is in place to immediately recognize and respond to failures, as it is difficult to immediately identify and respond to failures if the person in charge is not aware of them.

Appropriateness of intrusion detection system configuration for each network segment

  • Check if there are any exempted sections as intrusion attempts and abnormal traffic cannot be detected if the network sectional intrusion detection system is missing or installed in an inappropriate location.

Appropriateness of DMZ configuration for servers (such as web servers) that communicate with the external network.

  • Check whether public servers that should be located in the DMZ section are located in the internal section, as this may cause a breach of that section and the entire section.

Appropriateness of security settings for network management system activity history, log management, and user rights settings

  • There is a risk that important information may be exposed to unauthorized persons due to improper permission settings of the network management system, and it may be difficult to identify the cause in the event of a failure due to improper work history and log management.


2. Criteria for assessing network equipment security vulnerabilities


Whether to back up network equipment settings

  • To ensure that the system can be quickly restored to normal in the event of an emergency, such as a failure or downtime of network equipment.

Set SNMP Community Name Complexity

  • When setting the SNMP Community String, set it to comply with complexity to ensure that it is not easily inferred by unauthorized parties.

Set SNMP community permissions

  • Set the SNMP Community String permission to Read Only (RO) to ensure that unauthorized parties cannot change network configuration information even if they capture the Community String.

Set up SNMP access control (ACL)

  • Set up SNMP access lists (ACLs) to limit the exposure of network information, such as blocking SNMP access from unauthorized parties.

Block external interface SNMP access

  • Apply access list (ACL) blocking settings for SNMP service ports on the external interface of network equipment to restrict access by unauthorized users.

Whether to create local users and manage permissions

  • Create a local user when accessing the device to block access by unauthorized people

Whether to use enhanced authentication (AAA)

  • Enable Authentication Authorization Accounting (AAA) authentication for device access to prevent unauthorized access.

Using duplicate weak passwords

  • Check for duplicate passwords used by users, administrators, etc. as duplicate passwords can lead to account information leakage by unauthorized persons.

Whether to set enable secret

  • To encrypt the Enable password, which was exposed in plain text, so that it cannot be easily identified by unauthorized parties if the network equipment configuration is exposed.

Whether to set a secure encryption algorithm

  • Encrypt user and administrator passwords to make it difficult for unauthorized parties to identify passwords on the device if the network device configuration file is exposed to the outside world.

Set password complexity

  • To ensure that password complexity policies are followed to prevent attackers from gaining access to network equipment when they attempt to gain access.

Remote management access control

  • To prevent unauthorized users from accessing network equipment remotely.

Whether to set a session timeout

  • Check whether an automatic timeout is set for sessions that are inactive for a certain period of time to prevent unauthorized use of the system in the user's absence, and if so, check whether the session timeout is excessive.

Using insecure protocols (such as TELNET) for VTY connections

  • Use encryption protocols when accessing network equipment via a remote terminal (VTY) to prevent plain text data from being exposed to attackers by network sniffing attacks.

Whether to block unnecessary auxiliary input/output ports (AUX)

  • To disable unused I/O ports to prevent access by unauthorized parties

Whether to block unnecessary Source routing

  • Source routing is a feature that allows packets to be sent to a path of the packet sender's choosing, rather than through a routing path, to prevent unauthorized parties from exploiting it for attacks.
  • Check the settings on your router or switch to ensure that the IP source routing option is disabled.
  • For Cisco equipment, check that the no ip source-route command is included in the configuration file (config).

Whether Proxy ARP blocking is enabled

  • To block unauthorized parties because they can forge packet addresses to request Proxy ARPs and use the responses to obtain information about the router and network.
  • If Proxy ARP is enabled, you must disable the feature. For Cisco equipment, you can disable Proxy ARP using the no ip proxy-arp command in interface configuration mode.

IP Directed Broadcast blocking check - IOS 11

  • Disable IP Directed Broadcast to block DoS attacks (such as Smurf attacks)
  • Connect to the router, and verify that IP Directed Broadcast is disabled. On routers running Cisco IOS 12.0 or later, IP Directed Broadcast is disabled by default; however, on routers running IOS 11.x or earlier, you might need to manually disable it.
  • On Cisco routers, you can disable IP Directed Broadcast by using the no ip directed-broadcast command in interface configuration mode.

Whether to run unnecessary services

  • To eliminate potential risks, as unnecessary services that are not required for operations can make you a target for unintentional attacks.

NTP settings and whether to synchronize time

  • For system time accuracy and accurate log analysis when events occur

Enable logging

  • To enable monitoring for network equipment operation and security

Whether to set a time for logging messages

  • To include the exact time in log messages to enable analysis of the attack.

Whether to set the logging buffer size

  • Cisco routers store log messages in a memory buffer, and you can set the size of the buffer to a certain level for debugging or monitoring purposes.

Set up remote log server integration

  • To manage separate log files by installing a log server remotely because there are limitations to storing logs on network devices, and logs may be deleted.

Setting console logging levels

  • To prevent unnecessary log message output, as sometimes log messages are only output to the console and are not operationally necessary.

Setting up ingress filters on external interfaces

  • Setting up an ingress filter on an external interface to filter packets entering the internal network

Set up an egress filter on an external interface

  • Set an egress filter on an external interface to filter packets sent from the inside to the outside

Setting up anti-spoofing filters

  • To block spoofing attacks by filtering incoming packets on the external interface using the internal network IP band as the source IP.

Setting up IP multicast blocking

  • If IP multicast is not enabled, filter multicast packets to prevent them from being exploited in attacks.
  • To verify that multicast is enabled, use commands that look up the relevant settings. For example, on Cisco devices, you can use the show ip multicast routing command.

Setting up ICMP blocking

  • Block ICMP packets from outside to inside to prevent internal information from being leaked and to prevent denial-of-service attacks, etc.

Setting up ICMP redirect blocking

  • To prevent routing table changes by blocking ICMP redirect packets on external interfaces

Setting up ICMP unreachable blocking

  • To prevent ICMP unreachable messages from being used to expose whether certain ports on network equipment are enabled or disabled when scanning and exploited for DoS attacks.

Setting up ICMP mask-reply blocking

  • To block the ICMP mask-reply service to prevent network configuration information from being exposed to unauthorized parties.

Set ICMP Timestamp, Information Requests blocking settings

  • Block ICMP Timestamp, Information Requests to prevent network information from being exposed to unauthorized parties.

Set up filtering to block denial-of-service (DDoS) attacks

  • To block ports where denial-of-service attacks can occur

Availability of the latest/urgent security patches and updates

  • To ensure that the latest version of the network equipment operating system and the last released security patches have been reviewed (including testing against stable versions of the operating system and the latest security patches) and implemented

Whether to restrict command execution permissions

  • Set the user's per-command privilege level to Level 15 to prevent access by unauthorized parties.

Disable warning messages at logon

  • To display an appropriate warning message via banner to users accessing the router

Whether to enable tcp keepalives

  • Use TCP KEEPALIVES to block the session when the remote user is terminated to prevent attacks via hijacking and to ensure that the session is terminated normally.

Disable unused interfaces

  • To prevent unauthorized persons from obtaining network information and causing disruptions to communication equipment through unused interfaces.

Hardening switch hub security

  • Security settings to prevent network traffic from being exposed to or tampered with by unauthorized parties

Whether passwords are periodically changed and managed

  • Check whether the passwords of network equipment accessors are changed/managed periodically as there is a threat of password theft due to password dictionary attacks if the password is not changed for a long period of time.

Whether vulnerable services are running

  • Check whether vulnerable services* are running as there are threats such as equipment information exposure and transmission information exposure if vulnerable services are running.
    * CDP, LLDP, TFTP, Finger, identd, Smart Install, etc.


#NetworkSecurity #CyberSecurityTips #VulnerabilityAssessment #TechSafety #DigitalDefense #InfoSec #CyberThreats #SecureNetworking #ITSecurity #NetworkInfrastructure

Reentrancy Attack: 블록체인 스마트 컨트랙트의 치명적인 취약점

블록체인 기술이 전 세계적으로 주목받으면서 스마트 컨트랙트(Smart Contract)의 사용이 급격히 증가하고 있습니다. 하지만 그만큼 보안 취약점도 함께 늘어나고 있는데, 그 중에서도 Reentrancy Attack(재진입 공격)은 매우 치명적이고...