본문 바로가기
프로그램 (PHP,Python)

iptables 규칙의 구조화: XML/JSON 변환 및 분석 자동화 실전 가이드

by 날으는물고기 2025. 4. 20.

iptables 규칙의 구조화: XML/JSON 변환 및 분석 자동화 실전 가이드

728x90

iptables-save를 XML로 변환한 뒤, JSON으로 변환하는 과정과 사용 예시입니다.

기본 개념

  1. iptables-save: 현재 시스템의 iptables 규칙을 텍스트 형식으로 저장합니다.
  2. XML 변환: iptables-xml 도구를 사용해 iptables 규칙을 XML 형식으로 변환합니다.
  3. JSON 변환: XML 데이터를 JSON으로 변환합니다. JSON은 현대적 애플리케이션에서 널리 사용되는 데이터 형식입니다.

1단계: iptables-save 출력에서 XML로 변환

iptables-xml은 iptables 규칙을 XML 형식으로 변환하기 위한 유틸리티입니다. 대부분의 리눅스 배포판에서는 iptables-utils 패키지에 포함되어 있습니다.

sudo iptables-save | iptables-xml > iptables-config.xml
  • -c: 규칙과 매치 조건을 병합합니다.
  • -v: 규칙에 대한 추가 정보(예: 주석)를 포함합니다.

실제 예제

sudo iptables-save | iptables-xml -c -v > /etc/firewall/iptables-config.xml

이 명령은 iptables-save 결과를 XML 형식으로 변환한 뒤 /etc/firewall/iptables-config.xml 파일에 저장합니다.

2단계: XML을 JSON으로 변환

방법 1: Python 스크립트를 사용한 변환

Python의 xmltodictjson 라이브러리를 사용하면 XML 데이터를 손쉽게 JSON으로 변환할 수 있습니다.

pip install xmltodict

다음은 XML 파일을 JSON으로 변환하는 Python 코드입니다.

import xmltodict
import json

# XML 파일 읽기
with open('iptables-config.xml', 'r') as xml_file:
    xml_content = xml_file.read()

# XML -> Python 딕셔너리 변환
dict_data = xmltodict.parse(xml_content)

# 딕셔너리 -> JSON 변환
json_data = json.dumps(dict_data, indent=4)

# JSON 파일로 저장
with open('iptables-config.json', 'w') as json_file:
    json_file.write(json_data)

print("Conversion complete! JSON saved as 'iptables-config.json'.")

iptables-config.json 파일이 생성되며, XML 데이터가 JSON 형식으로 저장됩니다.

방법 2: 명령줄 도구를 사용한 변환

xml2json이라는 명령줄 도구를 사용하면 빠르게 XML을 JSON으로 변환할 수 있습니다.

sudo apt install xml2json
xml2json < iptables-config.xml > iptables-config.json

iptables-config.json 파일에 JSON 형식의 데이터가 저장됩니다.

방법 3: 온라인 도구를 이용한 변환

  1. Code Beautify (https://codebeautify.org/xml-to-json-converter)
  2. FreeFormatter (https://www.freeformatter.com/xml-to-json-converter.html)

사용법

  1. XML 파일 내용을 복사하여 입력.
  2. "Convert" 버튼 클릭.
  3. 결과 JSON을 다운로드.

실전 응용 예시

1. JSON 포맷 데이터 검증 및 필터링

JSON 데이터가 올바른 형식인지 확인하려면 Python에서 jsonschema를 활용할 수 있습니다.

from jsonschema import validate, ValidationError

# JSON 스키마 정의
schema = {
    "type": "object",
    "properties": {
        "iptables": {"type": "array"}
    },
    "required": ["iptables"]
}

# JSON 파일 읽기
with open('iptables-config.json', 'r') as json_file:
    data = json.load(json_file)

# 검증
try:
    validate(instance=data, schema=schema)
    print("JSON is valid.")
except ValidationError as e:
    print(f"JSON validation error: {e}")

2. JSON 데이터를 분석하여 특정 규칙 추출

특정 source IP를 차단하는 규칙만 필터링

import json

# JSON 파일 읽기
with open('iptables-config.json', 'r') as json_file:
    data = json.load(json_file)

# 특정 규칙 필터링
blocked_ips = []
for rule in data.get('iptables', {}).get('rules', []):
    if rule.get('target') == "DROP" and rule.get('source'):
        blocked_ips.append(rule['source'])

print("Blocked IPs:", blocked_ips)

3. JSON 데이터를 Elasticsearch에 인덱싱

iptables 규칙을 중앙화된 Elasticsearch 클러스터에 저장하려면 curl이나 Python의 elasticsearch 라이브러리를 사용할 수 있습니다.

from elasticsearch import Elasticsearch
import json

# Elasticsearch 클라이언트 연결
es = Elasticsearch(["http://localhost:9200"])

# JSON 파일 읽기
with open('iptables-config.json', 'r') as json_file:
    data = json.load(json_file)

# Elasticsearch 인덱스에 데이터 추가
for rule in data.get('iptables', {}).get('rules', []):
    es.index(index='iptables-rules', document=rule)

print("Rules indexed successfully!")

4. JSON 데이터를 SIEM 시스템으로 전송

JSON 데이터를 SIEM (예: Splunk, Wazuh)으로 전송하여 규칙 관리 및 모니터링을 자동화할 수 있습니다.

 

Splunk에 HTTP Event Collector 사용

curl -k "https://splunk-url:8088/services/collector" \
     -H "Authorization: Splunk <TOKEN>" \
     -d @iptables-config.json

이러한 절차를 따라 iptables-save 데이터를 구조화된 JSON 형식으로 변환하고, 다양한 시스템과 응용 프로그램에서 활용할 수 있습니다. 위에서 설명한 iptables의 룰셋 정보 및 패킷 데이터 수집 방식은 네트워크 분석 및 보안 모니터링에 매우 유용합니다. jc(JSON Convert)와 같은 도구를 활용하면 iptables 출력 데이터를 JSON 형태로 변환하여 데이터 처리 및 분석에 적합하게 만들 수 있습니다.

  • iptables --line-numbers -v -L -t nat: 현재 nat 테이블의 규칙 목록을 라인 번호, 패킷 수(pkts), 바이트 수(bytes) 등과 함께 출력합니다.
  • jc는 명령어 출력 결과를 JSON 형태로 변환하는 CLI 도구입니다.
  • 설치: pip install jc

명령어 예시

sudo iptables --line-numbers -v -L -t nat | jc --iptables -p

위 명령은 iptables 규칙을 JSON으로 변환하여 아래와 같은 구조로 출력합니다.

[
  {
    "chain": "PREROUTING",
    "rules": [
      {
        "num": 1,
        "pkts": 2183,
        "bytes": 186000,
        "target": "PREROUTING_direct",
        "prot": "all",
        "opt": null,
        "in": "any",
        "out": "any",
        "source": "anywhere",
        "destination": "anywhere"
      }
    ]
  }
]

JSON 데이터를 Elasticsearch에 저장

iptables 패킷 정보를 중앙화된 Elasticsearch에 저장하여 규칙 트래픽 분석 및 모니터링.

from elasticsearch import Elasticsearch
import subprocess
import json

# Elasticsearch 클라이언트 설정
es = Elasticsearch(["http://localhost:9200"])

# iptables 출력 JSON으로 변환
command = "sudo iptables --line-numbers -v -L -t nat | jc --iptables -p"
result = subprocess.check_output(command, shell=True)
data = json.loads(result)

# 데이터 Elasticsearch에 저장
for chain in data:
    for rule in chain.get("rules", []):
        es.index(index="iptables-rules", document=rule)

print("iptables data successfully indexed into Elasticsearch.")

특정 규칙의 패킷 및 바이트 변화 모니터링

특정 규칙(예: PREROUTING의 첫 번째 규칙)의 패킷 수 및 바이트 수를 주기적으로 확인하여 비정상적인 트래픽 감지.

import subprocess
import json
import time

# 규칙 모니터링 함수
def monitor_rule(chain_name, rule_num):
    while True:
        # iptables 출력
        command = "sudo iptables --line-numbers -v -L -t nat | jc --iptables -p"
        result = subprocess.check_output(command, shell=True)
        data = json.loads(result)

        # 특정 체인과 규칙 확인
        for chain in data:
            if chain.get("chain") == chain_name:
                for rule in chain.get("rules", []):
                    if rule.get("num") == rule_num:
                        print(f"Rule {rule_num} in {chain_name}:")
                        print(f"  Packets: {rule['pkts']}")
                        print(f"  Bytes: {rule['bytes']}")

        time.sleep(5)  # 5초 대기

# PREROUTING 체인의 1번 규칙 모니터링
monitor_rule("PREROUTING", 1)

Slack으로 알림 전송

규칙에 의해 차단된 패킷 수가 일정 임계치를 초과할 경우 Slack 알림 전송.

import subprocess
import json
import requests

# Slack Webhook URL 설정
slack_webhook_url = "https://hooks.slack.com/services/your/webhook/url"

# iptables 데이터 수집 및 Slack 알림
def check_and_notify(chain_name, rule_num, packet_threshold):
    command = "sudo iptables --line-numbers -v -L -t nat | jc --iptables -p"
    result = subprocess.check_output(command, shell=True)
    data = json.loads(result)

    for chain in data:
        if chain.get("chain") == chain_name:
            for rule in chain.get("rules", []):
                if rule.get("num") == rule_num:
                    if rule['pkts'] > packet_threshold:
                        message = f"Alert! Rule {rule_num} in {chain_name} exceeded {packet_threshold} packets.\n"
                        message += f"Packets: {rule['pkts']}, Bytes: {rule['bytes']}"
                        requests.post(slack_webhook_url, json={"text": message})
                        print("Notification sent to Slack.")

# PREROUTING 체인의 1번 규칙에서 1000 패킷 이상 발생 시 알림
check_and_notify("PREROUTING", 1, 1000)

시각화를 위한 데이터 저장

수집한 데이터를 CSV 또는 데이터베이스로 저장하고, Grafana 등의 도구를 이용해 시각화.

import subprocess
import json
import csv

# iptables 데이터를 CSV로 저장
command = "sudo iptables --line-numbers -v -L -t nat | jc --iptables -p"
result = subprocess.check_output(command, shell=True)
data = json.loads(result)

# CSV 파일 작성
with open('iptables_data.csv', 'w', newline='') as csvfile:
    fieldnames = ['chain', 'num', 'pkts', 'bytes', 'target', 'prot', 'source', 'destination']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    for chain in data:
        for rule in chain.get("rules", []):
            writer.writerow({
                "chain": chain["chain"],
                "num": rule["num"],
                "pkts": rule["pkts"],
                "bytes": rule["bytes"],
                "target": rule["target"],
                "prot": rule["prot"],
                "source": rule["source"],
                "destination": rule["destination"]
            })

print("iptables data saved to iptables_data.csv.")
  • jc를 활용하면 iptables 규칙 및 패킷 데이터를 손쉽게 JSON으로 변환하여 다양한 분석 및 응용에 활용할 수 있습니다.
  • 주기적 모니터링, 이상 탐지, Slack 알림, 중앙 로그 관리(Elasticsearch) 등 여러 시나리오에 응용 가능합니다.
  • 또한 Grafana와 같은 시각화 도구를 통해 데이터의 가시성을 높이고 네트워크 보안 관리를 효율화할 수 있습니다.
728x90
그리드형

댓글