'GRAY HAT PYTHON'

 

Chapter 2. Debugger

   2.1. CPU registers

   2.2. dis-assemble

 

* 본 문서는 'Gray Hat Python' 책의 내용을 살펴보며 개인적으로 정리하고 싶은 내용들을 기록한 페이지입니다. 

  Phtyon3 기준으로 예제는 변경되었습니다. 잘못된 내용이 있거나 추가가 필요한 사항이 있다면 언제든지 알려주시기 바랍니다.

 

2.1 CPU registers

 

간단히 살펴볼겸 Register들에 대해 확인해 보겠습니다.

 

* Intel core

http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf

EAX ( Accumulator register )

EDX ( Data register )

ECX ( Counter register )

ESI ( Source Index )

EDI ( Destination Index )

ESP ( Stack Pointer )

EBP ( Base Pointer )

Segment Registers

Program Status and Control Register

Instruction Pointer

 

* ARM core

http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/CHDBIBGJ.html

R0-R12 ( General Registers )

SP ( Stack Pointer )

LR ( Link Register )

PC ( Program Counter )

PSR ( Program Status Register ) 

ASPR ( Application Program Status Register )

IPSR ( Interrupt Program Status Register )

EPSR ( Execution Program Status Register )

 

 

2.2 dis-assemble

 

2장 내용중 ECX register (count register)는 레지스터 값을 감소시킨다는 문구가 있어서 예제를 직접 de-assemble해보았습니다.

dis.py library에서 bytecode로 disassembling해주는 기능이 있습니다. 

 

https://docs.python.org/3.5/library/dis.html

 

 

chapter2-dis.py

 

import dis

 

def f(x):

    counter = 3

    while counter < 10:

        print ("Loop number: %d" % counter)

        counter +=1

    print ("hello")

 

dis.dis(f)

 

  4           0 LOAD_CONST               1 (3)

              3 STORE_FAST               1 (counter)

 

  5           6 SETUP_LOOP              40 (to 49)

             // while counter < 10

        >>    9 LOAD_FAST                1 (counter)

             12 LOAD_CONST               2 (10)

             15 COMPARE_OP               0 (<)

 // TOS (Top of stack)을 확인

             18 POP_JUMP_IF_FALSE       48

 

  6          21 LOAD_GLOBAL              0 (print)

             24 LOAD_CONST               3 ('Loop number: %d')

             27 LOAD_FAST                1 (counter)

             30 BINARY_MODULO

             31 CALL_FUNCTION            1 (1 positional, 0 keyword pair)

             34 POP_TOP

 

             // counter+1

  7          35 LOAD_FAST                1 (counter)

             38 LOAD_CONST               4 (1)

             41 INPLACE_ADD

             42 STORE_FAST               1 (counter)

 

             // while loop 다시 돌기

             45 JUMP_ABSOLUTE            9

        >>   48 POP_BLOCK

  8     >>   49 LOAD_GLOBAL              0 (print)

 

             52 LOAD_CONST               5 ('hello')

 

             55 CALL_FUNCTION            1 (1 positional, 0 keyword pair)

             58 POP_TOP

             59 LOAD_CONST               0 (None)

             62 RETURN_VALUE

 
dis 만으로는 CPU register들에 대한 동작을 확인할 순 없었습니다.

 

 

반응형

'Security&Encryption > Black Hat' 카테고리의 다른 글

Windows Debugger with PyDev  (0) 2016.06.29
Pydev on Eclipse  (0) 2016.06.28
Trojan using Git hub  (0) 2016.03.30
ICMP Decoding with Python  (0) 2016.03.16

'GRAY HAT PYTHON'

 

Chapter 1

   1.1. 환경설정

   1.2. ctypes


* 본 문서는 'Gray Hat Python' 책의 내용을 살펴보며 개인적으로 정리하고 싶은 내용들을 기록한 페이지입니다. 

  Phtyon3 기준으로 예제는 변경되었습니다. 잘못된 내용이 있거나 추가가 필요한 사항이 있다면 언제든지 알려주시기 바랍니다.


1.1 환경 설정


Eclipse에 Pydev환경을 설치해 보았습니다. (Python은 이미 설치 되어 있다는 가정)


Eclipse는 아무 생각 없이 Mars.2 Relase(4.5.2)에 깔아 버렸습니다.


http://www.pydev.org/ 사이트에 방문해보니 친절하게 pydev update url이 있습니다.

   Latest version: http://pydev.org/updates
   Nightly build: http://pydev.org/nightly


Eclipse의 help > Install new software 창을 띄워서 [Work with]에 위 latest version을 입력해 줍니다.

그리고 나서 필요한 software를 선택한 이후 설치를 진행하면 끝~ 입니다.





License를 확인하고 accept 클릭 합니다.

설치 중간에 certification관련 warning 팝업도 나오는데 일단 accept하였습니다.



Eclipse를 재시작하고 Window > Preferences 에 가보면

PyDev가 추가된 것을 확인할 수 있습니다.


인제 Python interpreter만 연결해주면 준비 끝



예제로 프로젝트를 하나 생성해 보도록 하겠습니다.


제 PC에는 Python3가 깔려 있기에

아래 Grammar version과 interpreter를 변경하였습니다.



src 폴더를 하나 추가하고, 그 안에 PyDev Module로 python script를 추가 합니다.



간단히 play버튼을 누르면 정상적으로 동작하는 것을 확인할 수 있습니다.




1.2. ctypes


Linux, windows, Max OS와 같은 외부 library를 호출하기 위해 Python에서는 ctypes library를 지원합니다.

아래 공식 documenet를 확인해 봅니다.


https://docs.python.org/3.5/library/ctypes.html


아래는 ctypes 라이브러리를 이용하여 window의 c runtime 함수인 printf를 이용하여 텍스트 메세지를 출력하는 예제입니다.


chapter1-test.py


from ctypes import *


msvcrt = cdll.msvcrt

message_string = "Hello World!\n"

msvcrt.printf("Testing: %s".encode('ascii'), message_string.encode('ascii'))



Testing: Hello World!


Python3의 경우 모든 string을 unicode로 처리하기 때문에 위와 같이 ascii로 변환이 필요합니다.


Python에서 indent를 가지고 class나 함수의 범위를 구분합니다. 

아래 예제에서 Union선언한 다음 제가 실수로 tap을 value 선언하는 곳 이후에 넣어 두었더니 실행이 안되네요. 주의! 


chapter1-unions.py


from ctypes import *


class barley_amount(Union):

    _fields_ = [

        ("barley_long", c_long),

        ("barley_int", c_int),

        ("barley_char", c_char*8)

    ]

    

value = input("Enter the amount of barley to pu into the beer vat:")

my_barley = barley_amount(int(value))

print ("Barley amount as a long: %ld" % my_barley.barley_long)

print ("Barley amount as a long: %d" % my_barley.barley_int)

print ("Barley amount as a long: %s" % my_barley.barley_char)


Enter the amount of barley to pu into the beer vat:66

Barley amount as a long: 66

Barley amount as a long: 66

Barley amount as a long: b'B'


Python3부터는 raw_input이 input으로 rename되었습니다.


반응형

'Security&Encryption > Black Hat' 카테고리의 다른 글

Windows Debugger with PyDev  (0) 2016.06.29
CPU registers and dis-assemble of Python  (0) 2016.06.29
Trojan using Git hub  (0) 2016.03.30
ICMP Decoding with Python  (0) 2016.03.16


from Black Hat Python
Git Hub Command and Control



Following code can be changed to EXE file format with py2exe tool for window.

http://www.py2exe.org/


[+] start code  [-] end code



Example of running the trojan code from client

python git_trojan.py
[*] get_trojan_config
[*] get_file_contents
[*] connect_to_github
[*] Found file abc.json
[*] Attempting to retrieve dirlister
[*] get_file_contents
[*] connect_to_github
[*] Found file modules/dirlister
[*] Attempting to retrieve environment
[*] get_file_contents
[*] connect_to_github
[*] Found file modules/environment
[*] module_runner
[*] In dirlister module.
[*] store_module_result
[*] connect_to_github
[*] module_runner
[*] In environment module.
[*] store_module_result
[*] connect_to_github



The client script will upload the result to git server. And it can be checked with following git commands. 

kjpark@kjpark-F9SG:~/code/PracticeAlgorithm/chapter7$ cd data
kjpark@kjpark-F9SG:~/code/PracticeAlgorithm/chapter7/data$ git pull origin master
remote: Counting objects: 10, done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 10 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (10/10), done.
From https://github.com/sedew810225/chapter7
 * branch            master     -> FETCH_HEAD
   c432f2c..d29f1cf  master     -> origin/master
Updating c432f2c..d29f1cf
Fast-forward
 data/abc/60121.data | 1 +
 data/abc/85593.data | 1 +
 2 files changed, 2 insertions(+)
 create mode 100644 data/abc/60121.data
 create mode 100644 data/abc/85593.data



Because the data has been encoded for base64 format, you can simply decode it as following.

kjpark@kjpark-F9SG:~/code/PracticeAlgorithm/chapter7/data$ base64 abc/60121.data
ZXlkTVExOU9WVTFGVWtsREp6b2dKMnR2WDB0U0xsVlVSaTA0Snl3Z0oxZEpUa1JQVjBsRUp6b2dK
ek01T0RRMU9EazRKeXdnSjAxQlRrUkJWRTlTV1Y5UVFWUklKem9nSnk5MWMzSXZjMmhoY21Vdloy
TnZibVl2WjI1dmJXVXViV0Z1WkdGMGIzSjVMbkJoZEdnbkxDQW5XRVJIWDBkU1JVVlVSVkpmUkVG
VVFWOUVTVkluT2lBbkwzWmhjaTlzYVdJdmJHbG5hSFJrYlMxa1lYUmhMMnRxY0dGeWF5Y3NJQ2RI
VGs5TlJWOUVSVk5MVkU5UVgxTkZVMU5KVDA1ZlNVUW5PaUFuZEdocGN5MXBjeTFrWlhCeVpXTmhk
R1ZrSnl3Z0owZEtVMTlFUlVKVlIxOVBWVlJRVlZRbk9pQW5jM1JrWlhKeUp5d2dKMHhGVTFOUFVF
Vk9Kem9nSjN3Z0wzVnpjaTlpYVc0dmJHVnpjM0JwY0dVZ0pYTW5MQ0FuV0VSSFgxWlVUbEluT2lB
bk55Y3NJQ2RSVkY5SlRWOU5UMFJWVEVVbk9pQW5hV0oxY3ljc0lDZE1UMGRPUVUxRkp6b2dKMnRx
Y0dGeWF5Y3NJQ2RWVTBWU0p6b2dK ....

alBUQXdPek0yT2lvdWIyZG5QVEF3T3pNMk9pb3VjbUU5TURBN016WTZLaTUzWVhZOU1EQTdNelk2
S2k1aGVHRTlNREE3TXpZNktpNXZaMkU5TURBN016WTZLaTV6Y0hnOU1EQTdNelk2S2k1NGMzQm1Q
VEF3T3pNMk9pY3NJQ2RIU2xOZlJFVkNWVWRmVkU5UVNVTlRKem9nSjBwVElFVlNVazlTTzBwVElF
eFBSeWNzSUNkWVJFZGZVMFZCVkNjNklDZHpaV0YwTUNkOQ==


kjpark@kjpark-F9SG:~/code/PracticeAlgorithm/chapter7/data$ base64 -d abc/60121.data
{'LC_NUMERIC': 'ko_KR.UTF-8', 'WINDOWID': '39845898', 'MANDATORY_PATH': '/usr/share/gconf/gnome.mandatory.path', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/kjpark', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'GJS_DEBUG_OUTPUT': 'stderr', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'XDG_VTNR': '7', 'QT_IM_MODULE': 'ibus', 'LOGNAME': 'kjpark', 'USER': 'kjpark', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games', 'LC_PAPER': 'ko_KR.UTF-8', 'GNOME_KEYRING_CONTROL': '', 'GTK_IM_MODULE': 'ibus', 'DISPLAY': ':0', 'LANG': 'ko_KR.UTF-8', 'TERM': 'xterm-256color', 'SHELL': '/bin/bash', 'XDG_SESSION_PATH': '/org/freedesktop/DisplayManager/Session0', 'XAUTHORITY': '/home/kjpark/.Xauthority', 'LANGUAGE': 'ko:en_US:en', 'SESSION_MANAGER': 'local/kjpark-F9SG:@/tmp

...

ob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:', 'GJS_DEBUG_TOPICS': 'JS ERROR;JS LOG', 'XDG_SEAT': 'seat0'}kjpark@kjpar


반응형

'Security&Encryption > Black Hat' 카테고리의 다른 글

Windows Debugger with PyDev  (0) 2016.06.29
CPU registers and dis-assemble of Python  (0) 2016.06.29
Pydev on Eclipse  (0) 2016.06.28
ICMP Decoding with Python  (0) 2016.03.16

Socket Class from Python

https://docs.python.org/2/library/socket.html

  • Address Family
    • AF_UNIX address family : a single string
    • AF_INET address family : (host, port)
    • AF_INET6 address family : (host, port, flowinfo, scopeid)
    • AF_NETLINK socket       : (pid, groups)
    • AF_TIPC address family : (addr_type, v1, v2, v3 [, scope])
      • non-IP based networked protocol designed for use in clustered computer environments


  • Socket Type
    • socket.SOCK_STREAM :
    • socket.SOCK_DGRAM :
    • socket.SOCK_RAW :
    • socket.SOCK_RDM :
    • socket.SOCK_SEQPACKET :


  • IP header & ICMP message


Scanning Example from 'Black Hat Python'


1. Create socket

2. Bind

3. ioctl


 


pip install netaddr

python scanner.py
Traceback (most recent call last):
  File "scanner.py", line 7, in <module>
    from netaddr import IPNetwork, IPAddress
ImportError: No module named netaddr


 

 

References :

http://www.kalitutorials.net/2014/04/denial-of-service-methods-icmp-syn.html

반응형

'Security&Encryption > Black Hat' 카테고리의 다른 글

Windows Debugger with PyDev  (0) 2016.06.29
CPU registers and dis-assemble of Python  (0) 2016.06.29
Pydev on Eclipse  (0) 2016.06.28
Trojan using Git hub  (0) 2016.03.30

TCP Flow Control

From this article, let's see some basic stuff for TCP related. In RFC 793, there are comment for 'flow control' as following :

RFC 793

https://tools.ietf.org/html/rfc793#page-15


flow Control: TCP provides a means for the receiver to govern the amount of data sent by the sender. This is achieved by returning a "window" with every ACK indicating a range of acceptable sequence numbers beyond the last segment successfully received. The window indicates an allowed number of octets that the sender may transmit before receiving further permission.


In TCP header, there are Window and Control field which can be used for flow control.


    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |          Source Port          |       Destination Port        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                        Sequence Number                        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Acknowledgment Number                      |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |  Data |           |U|A|P|R|S|F|                               |
   | Offset| Reserved  |R|C|S|S|Y|I|            Window             |
   |       |           |G|K|H|T|N|N|                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |           Checksum            |         Urgent Pointer        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Options                    |    Padding    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                             data                              |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                            TCP Header Format


Window: 16 bits The number of data octets beginning with the one indicated in the acknowledgment field which the sender of this segment is willing to accept.


Sliding window


WINDOW AND ACKNOWLEDGEMENT STRATEGY IN TCP : http://www.ietf.org/rfc/rfc813.txt

The window mechanism is a flow control tool. Whenever appropriate, the recipient of data returns to the sender a number, which is (more or less) the size of the buffer which the receiver currently has available for additional data. This number of bytes, called the window, is the maximum which the sender is permitted to transmit until the receiver returns some additional window.

http://www.omnisecu.com/tcpip/tcp-sliding-window.php

  • The sending device can send all packets within the TCP window size without receiving an ACK, and should start a timeout timer for each of them.

  • The receiving device should acknowledge each packet it received, indicating the sequence number of the last well-received packet. After receiving the ACK from the receiving device, the sending device slides the window to right side.



Slow Read DoS attack

Slow Read DoS attach is one of slow HTTP attack. When the Web server keeps too many resources busy, this situation becomes like DoS attacks. To realize this malicious condition, the attacker can take following two types of techniques. 
1) The technique of sending request slowly 
2) The technique of reading response slowly




Example


{{ TBD }}



References :

https://en.wikipedia.org/wiki/Transmission_Control_Protocol

http://www.rhyshaden.com/tcp.htm

http://www.tcpipguide.com/free/t_TCPMessageSegmentFormat-3.htm

https://www.youtube.com/watch?v=ADiuHeoT2GA

http://www.freesoft.org/CIE/Course/Section4/8.htm


반응형

'Security&Encryption > Network Packet Forensic' 카테고리의 다른 글

Wireless Packet Analysis - 2  (0) 2016.03.08
Wireless Packet Analysis - 1  (0) 2016.03.08
Shell code packet analysis - 1  (0) 2016.03.07
UDP Port Scan  (0) 2016.03.07
TCP Port Scan  (0) 2016.03.06

+ Recent posts