Parse-GnmapFile with PowerShell


PowerShell for Nmap

파워쉘?

파워쉘1은 마이크로소프트에서 개발한 명령줄 셸과 관련 스크립팅 언어로 구성된 크로스 플랫폼 작업 자동화 및 구성 관리 프레임워크 입니다. 일괄 처리와 같은 시스템 작업을 자동화하고, 일반적으로 사용되는 프로세스를 위한 시스템 관리 도구를 만들 수 있도록 설계되었습니다. 스크립팅 언어는 .NET 프레임워크를 기반으로 구축되어 .NET 클래스 및 메서드의 모든 기능을 활용할 수 있습니다.

What is Nmap?

Nmap2(Network Mapper의 약자)은 오픈 소스 네트워크 스캐닝 및 취약점 탐지 도구이다. 일명 Fyodor라 불리는 원작자 Gordon Lyon 이 개발했으며, 네트워크 스캐닝 및 호스트 식별, 보안 취약점 감사 목적으로 사용된다. 특정 대상 네트워크에 존재하는 호스트를 식별하고, 확인된 호스트의 네트워크 서비스 및 서비스의 메타 정보를 수집한다.

PowerShell
Nmap
Nmap

스캐닝 절차를 단순화 해 보면, 지정된 단일 혹은 다수의 대상에게 패킷을 보내고 전송한 패킷에 대한 대상의 응답(혹은 무응답) 패킷을 분석해 결과를 도출한다. 이러한 요청, 응답(또는 무시/거부), 분석 과정을 반복하며. 그 결과로 수집 된 네트워크 응답(혹은 무응답) 데이터를 기반으로, 네트워크에 존재하며 활성화된 호스트를 식별하고, 호스트에서 실행 중인 서비스 종류, 서비스 버젼, 호스트 운영 체제 등 다양한 정보를 식별 및 유추 할 수 있다.

What is gnmap file

gnmap(grepable nmap) 파일은 네트워크 스캔 결과를 파일 스트림으로 저장할 때 선택할 수 있는 파일 형식 옵션 중 하나인 grepable output3 (-oG)의 출력이다. 공식 도움말에서는 deprecated 된 상태이며 Xml 출력 옵션4(-oX) 사용을 권장한다.

This output format is covered last because it is deprecated. The XML output format is far more powerful, and is nearly as convenient for experienced users. XML is a standard for which dozens of excellent parsers are available, while grepable output is my own simple hack. XML is extensible to support new Nmap features as they are released, while I often must omit those features from grepable output for lack of a place to put them.

https://nmap.org/book/output-formats-grepable-output.html

It’s deprecated but

공식 도움말에서도 언급했든, 공식적으론 deprecated 상태다. 그럼에도 불구하고, 모든 출력(-oA) 옵션 선택 시 함께 생성된다. grepable 이름에 걸맞게, 배쉬나 파워쉘과 같은 명령줄 인터페이스(CLI)에서 grep등의 텍스트 처리 도구들과 함께 사용하기에 편리하기 때문에, 텍스트 기반 환경에서 간단한 작업 수행시 grepable output 파일을 선호한다.

Nevertheless, grepable output is still quite popular. It is a simple format that lists each host on one line and can be trivially searched and parsed with standard Unix tools such as grep, awk, cut, sed, diff, and Perl.

https://nmap.org/book/output-formats-grepable-output.html

Parse-GnmapFile

다음은 입력받은 gnmap 형식 파일을 처리하는 파워쉘 스크립트다. 입력받은 파일을 처리하기 위한 함수 Parse-GnmapFile 정의와 실 사용 예를 볼 수 있다. Parse-Gnmapfile 함수는 입력 받은 파일 내용을 읽고, 줄 단위로 반복해 처리한다. 파일 본문의 각 행에서 호스트 정보 및 포트 정보가 존재하는지 찾고, 해당 정보의 패턴이 확인 될 경우 그 문자열을 나눠 파싱한다. 함수가 정상적으로 실행 되었다면, 확인된 전체 호스트 정보 및 열린(Open) 상태의 포트 번호 목록을 만들어 반환한다. 함수 정의 시작(줄 번호 2)과, 함수 호출(줄 번호 49) 을 각각의 행 번호 2, 49 에서 확인 할 수 있다.

# Function to read and parse .gnmap file and list open ports
function Parse-GnmapFile {
    param (
        [string]$filePath
    )

    # Initialize counters and open ports list
    $onlineHosts = 0
    $totalOpenPorts = 0
    $hosts = @{}

    # Read the file line by line
    Get-Content $filePath | ForEach-Object {
        # Check if the line contains host information
        if ($_ -match '^Host: (\d+\.\d+\.\d+\.\d+) .*Status: Up') {
            $matchhost = $matches[1]
            if (-not $hosts.ContainsKey($matchhost)) {
                $hosts[$matchhost] = @()
                $onlineHosts++
            }
        }

        # Check if the line contains open port information
        if ($_ -match 'Ports: (.*)') {
            $portsString = $matches[1]
            $ports = $portsString -split ', '
            foreach ($portInfo in $ports) {
                if ($portInfo -match '(\d+)/open') {
                    $port = $matches[1]
                    $hosts[$matchhost] += $port
                    $totalOpenPorts++
                }
            }
        }
    }

    # Return the statistics and hosts
    return @{
        OnlineHosts = $onlineHosts
        TotalOpenPorts = $totalOpenPorts
        Hosts = $hosts
    }
}

# Path to the .gnmap file
$filePath = "scan\1_2_3_4_24_local.gnmap"

# Parse the .gnmap file and get the statistics
$statistics = Parse-GnmapFile -filePath $filePath

# Display the statistics
Write-Output "Statistics from .gnmap file:"
Write-Output "Online Hosts: $($statistics.OnlineHosts)"
Write-Output "Total Open Ports: $($statistics.TotalOpenPorts)"

# Iterate through each host
foreach ($hostname in $statistics.Hosts.Keys) {
    Write-Output "Host $hostname ports list:"
    foreach ($port in $statistics.Hosts[$hostname]) {
        Write-Output "$port"
    }
}

Parse-GnmapFile 함수로 -oG 옵션 출력 파일을 파싱하면, 아주 간단한 통계(호스트 수 및 포트 수)와 함께 호스트 및 열린 포트목록을 가진 오브젝트가 반환된다.


참고자료

  1. 파워쉘 GitHub 리포지토리 : https://github.com/PowerShell/PowerShell ↩︎
  2. Nmap.org ↩︎
  3. Output formats grepable output ↩︎
  4. Output formats xml output ↩︎

+ There are no comments

Add yours

이 사이트는 Akismet을 사용하여 스팸을 줄입니다. 댓글 데이터가 어떻게 처리되는지 알아보세요.