티스토리 툴바


posted by ppiazi 2011/09/05 16:17
Creative Commons License
Creative Commons License
http://marketplace.eclipse.org/content/eclipse-color-theme

Preferences >> General >> Appearance >> Color Theme 에서 변경가능하다.
저작자 표시 비영리 동일 조건 변경 허락
posted by ppiazi 2011/08/24 11:05
Creative Commons License
Creative Commons License
특정 UDP 포트로 들어오는 데이터를 캡처하여 sequential하게 증가하는 특정값을 모니터링하는 소프트웨어이다.

import socket
import struct
import time
from threading import Thread
from scapy.all import *

DATA_FMT = "!IHHH%ds"
UDP_PORT = 8080
captured_list = []
start_msginx = -1
expected_msginx = -1
missing_cnt = 0
captured_cnt = 0

def pkg_callback(pkg):
    global start_msginx
    global missing_cnt
    global expected_msginx
    global captured_cnt
   
    udp_layer = pkg.getlayer("UDP")
    if udp_layer.dport != UDP_PORT:
        return
    captured_cnt = captured_cnt + 1
    udp_size = udp_layer.len
    dl_payload_size = udp_size - 8 - 10
    dl_timestamp, dl_bport, dl_msginx, dl_crc, dl_payload = struct.unpack(DATA_FMT%dl_payload_size, str(udp_layer.payload))
    if start_msginx == -1:
        start_msginx = dl_msginx
        print "DL MsgInx Start from %d" % ( start_msginx )
        expected_msginx = start_msginx + 1
        expected_msginx = expected_msginx % 0x10000
        return
    if expected_msginx != dl_msginx:
        print "Expected MsgInx ( %d ), Received MsgInx ( %d )" % (expected_msginx, dl_msginx)
        temp_missing_cnt = 0
        if dl_msginx < expected_msginx:
            temp_missing_cnt = 0xffff + dl_msginx - expected_msginx
        else:
            temp_missing_cnt = dl_msginx - expected_msginx
        missing_cnt = missing_cnt + temp_missing_cnt
    expected_msginx = dl_msginx + 1
    expected_msginx = expected_msginx % 0x10000

class UDP_SNIFFER(Thread):
    def __init__(self):
        Thread.__init__(self)
                                     
    def run(self):
      
        while 1:
            choice = raw_input("menu> ")
            if choice.strip() == "":
                continue
            if choice.strip() == "exit":
                break
            if choice.strip() == "start":
                print "Start to capture packets..."
                self.startCapture()
                continue
        print "Exiting..." 
   def startCapture(self):
        global captured_list
        global start_msginx
        global missing_cnt
        global expected_msginx
        global captured_cnt

        # initialize all variables.
        captured_list = []
        start_msginx = -1
        expected_msginx = -1
        missing_cnt = 0
        captured_cnt = 0

        # try to capture N packets.
        start_time = time.time()
        sniff(prn=pkg_callback, filter="udp and port %d" % (UDP_PORT), count=10000)
        end_time = time.time()
        gap = end_time - start_time

        # print result
        print "Sniffing is done. Result ( %d / %d ) during %f" % ( missing_cnt, captured_cnt, gap )

if __name__ == "__main__":
    upr = UDP_SNIFFER()
    upr.start()
    upr.join()
    exit(0)

저작자 표시 비영리 동일 조건 변경 허락
posted by ppiazi 2011/07/21 11:22
Creative Commons License
Creative Commons License
http://www.secdev.org/projects/scapy/doc/build_dissect.html#adding-new-protocols

IP / UDP / CUSTOM_DL_HDR / CUSTOM_HDR 과 같은 네트워크 스택이 있다고 가정한다. CUSTOM_DL_HDR의 Destination UDP Port는 50481이며, 바로 뒤에 CUSTOM_HDR이 따라 오도록 한다.

CUSTOM_DL_HDR는 [4 bytes] [2 bytes] [2 bytes] [2 bytes]로 구성되어 있다.
CUSTOM_HDR는 [1 byte] [1 byte] [2 bytes]로 구성되어 있다.

CUSTOM_DL_HDR과 CUSTOM_HDR Protocol 을  등록하기 위한 코드는 아래와 같다.

from scapy.all import *

class CUSTOM_HDR(Packet):
    name = "Custom Header"
    fields_desc = [ XByteField("Custom1", 0),
                    XByteField("Custom2", 0),
                    ShortField("Custom3", 0) ]

class CUSTOM_DL_HDR(Packet):
    name = "Custom Datalink Header"
    fields_desc = [ XIntField("CustomDl1", 0),
                    ShortField("CustomDl2", 0),
                    ShortField("CustomDl3", 0),
                    ShortField("CustomDl4", 0) ]

    def guess_payload_class(self, payload):
        return CUSTOM_HDR

bind_layers(UDP, CUSTOM_DL_HDR, dport=50481)



CUSTOM_Packet을 임포트하기 전의 pcap의 내용




CUSTOM_Packet을 임포트한 후의 pcap의 내용 : 851번 패킷의 경우, CUSTOM_Packet을 임포트한 이후에는 해당 프로토콜이 해석되어 전시되는 것을 볼수가 있다.



851번 패킷의 내용을 자세히 분석한 결과이다.



저작자 표시 비영리 동일 조건 변경 허락
posted by ppiazi 2011/07/13 16:16
Creative Commons License
Creative Commons License
scapy 모듈을 활용하여 pcap 파일을 읽는 예제이다.
간단히 모든 패킷을 읽어들여 ARP 패킷 개수를 세는 프로그램이다.



from scapy.all import *

arps = []
pcap_data = rdpcap("test_arp.pcap")

n_total = 0

for pkg in pcap_data:
    ip_layer = pkg.getlayer("ARP")

    n_total = n_total + 1

    if ip_layer == None:
#        print "No ARP"
        continue

    arps.append(pkg)

print "%02d / %02d ARP packets found. " % (len(arps), n_total)










저작자 표시 비영리 동일 조건 변경 허락
TAG
posted by ppiazi 2011/04/04 17:12
Creative Commons License
Creative Commons License
http://www.secdev.org/projects/scapy/doc/installation.html#windows

저작자 표시 비영리 동일 조건 변경 허락
TAG
posted by ppiazi 2011/03/27 13:09
Creative Commons License
Creative Commons License
프로젝트 진행간에 테스트 용도로 급하게 만들어 보았다. 역시 이럴때는 Python 만한게 없다. :)

import socket

if __name__ == '__main__':
    rcv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
        rcv_sock.bind(("10.100.10.90", 8889))
    except:
        print "Error at Binding"

    while 1:
        print "Listening..."
        data, addr = rcv_sock.recvfrom(65535)
        print "Got %s" % data

Python을 이용한 Socket 프로그래밍에 관련된 자료는 아래의 문서를 참고한다.

저작자 표시 비영리 동일 조건 변경 허락
posted by ppiazi 2010/11/21 21:28
Creative Commons License
Creative Commons License

저작자 표시 비영리 동일 조건 변경 허락
posted by ppiazi 2010/10/04 11:57
Creative Commons License
Creative Commons License
http://www.pyside.org/

Python용 QT 바인딩 프로젝트. 라이센스가 LGPL이다. 참고로 PyQt는 GPL.
저작자 표시 비영리 동일 조건 변경 허락
posted by ppiazi 2010/07/16 17:28
Creative Commons License
Creative Commons License
http://docs.python.org/library/struct.html

오,, 네트워크 프로그램에서 매우 유용하게 사용할 수 있는 모듈. @_@

>>> struct.pack('>IB6s', len("Hello"), 0, "Hello")
'\x00\x00\x00\x05\x00Hello\x00'
>>>

저작자 표시 비영리 동일 조건 변경 허락
posted by ppiazi 2010/05/09 17:56
Creative Commons License
Creative Commons License
ascii에만 젖어있던던 나에게 unicode는 재앙과 같았다. 파일에서 읽어서 머 좀 하려고 하면 UnicodeEncodingError 예외 발생!! ㅠ.ㅜ

그래서 바로 구글링으로 몇가지 주옥같은 링크 발견한 후 속독!! 아래의 링크다.

속독한 후 알게된 사실.
1. Byte String(문자열)과 유니코드는 다르다.
2. Byte String(문자열)을 읽어 유니코드로 변환하는 과정을 decoding 이라고 한다.
3. 유니코드를 Byte String(문자열)로 변환하는 과정을 encoding 이라고 한다.
4. 파일/소켓/stdin에서 데이터를 읽거나 수신하였다면 decoding 과정을 거쳐 유니코드로 변환하자.
5. 파일/소켓/화면(stdout)으로 데이터를 쓰거나 전송하고싶다면 encoding 과정을 거쳐 Byte String으로 변환하자.

머 이 정도~!
나머진 차근차근히.. ㅎ
저작자 표시 비영리 동일 조건 변경 허락