'GRAY HAT PYTHON'

 

Chapter 3. Windows Debugger

   3.1. Debugger (ERROR_FILE_NOT_FOUND)

   3.2. Debugger (ERROR_ACCESS_DENIED)

   3.3. Get CPU register status

   3.4. Debug event handler

   3.5. Break Points


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

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


3.1 Debugger (ERROR_FILE_NOT_FOUND)


Python3에서 p56의 예제 화일을 수행하였더니 kernel32.GetLastError() 부분에서 0x2 에러가 발생합니다.

Windll에서 발생한 에러이므로 아래 MS 홈페이지를 참조해보니 ERROR_FILE_NOT_FOUND입니다.

혹시 path_to_exe에 잘못된 스트링이 전달되었는지 출력을 해보았으나 특히 점은 코드상에서 보이지 않습니다.


https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx


my_test.py (page 56)

import my_debugger

debugger.load("c:\\Windows\\System32\\calc.exe")
debugger = my_debugger.debugger()

[*] Error : 0x00000002 c:\Windows\System32\calc.exe.

ERROR_FILE_NOT_FOUND
2 (0x2)

The system cannot find the file specified.


우선은 아래처럼 string을 unicode로 변환을 곧바로 하는 방법이 있습니다.


my_test_modify.py


import my_debugger

debugger.load(b"c:\\Windows\\System32\\calc.exe")
debugger = my_debugger.debugger()



혹은 debugger.load부분이 아닌 my_debugger.py를 수정할 수 있습니다.

ascii-strings만 받는 CreateProcessA 가 아닌 CreateProcessW를 사용하는 방법입니다.


my_debugger.py


...

    if kernel32.CreateProcessW(path_to_exe,
                                   None,
                                   None,
                                   None,
                                   None,
                                   creation_flags,
                                   None,
                                   None,
                                   byref(startupinfo),
                                   byref(process_information)):
            print ("[*] We have successfully launched the process!")
            print ("[*] PID: %d " % process_information.dwProcessId)

...


Then if you use Python 3.x you should use not CreateProcessA but CreateProcessW function because all string in Python 3.x is in unicode (in WinAPI all functions ends with 'A' accept asci-strings, ends with 'W' accept unicode-strings)



3.2 Debugger (ERROR_ACCESS_DENIED)


위 에러를 수정하고 나서 p60의 예제를 수행해보니 이번에는 debugger.attach() 함수내의 DebugActiveProcess(pid)에서 0x5번 에러가 발생합니다.


my_test.py (p60)


import my_debugger


debugger = my_debugger.debugger()

debugger.attach(int(pid))pid = input("Enter the PID of the process to attach to: ")


debugger.run()

debugger.detach()


Enter the PID of the process to attach to: 9476
[*] Unable to attach to the process.
[*] Error : 0x00000005
There was an error


ERROR_ACCESS_DENIED
5 (0x5)
Access is denied.



구글링으로 찾아보니 64비트용 프로그램은 수행할 수 없다는 정보가 있습니다.


http://stackoverflow.com/questions/20807108/pythondebugger-from-gray-hat-python

그래서 windows 10의 Task Manager에서 (32bit) 표시가 있는 process를 시도 해보니 정상적으로 attach가 진행됩니다.



3.3 Get CPU register status


C에서는 { } 를 이용하여 scope를 정하지만 Python에서는 indent를 가지고 code code와 structure를 구분합니다.

P66에 잘못 프린트된 indent로 인해 무한 루프에 빠지는 부분이 있어 수정이 필요합니다.


    def enumerate_threads(self):
        thread_entry = THREADENTRY32()
        thread_list = []
        snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, self.pid)
       
        if snapshot is not None :
            thread_entry.dwSize = sizeof(thread_entry)
            success = kernel32.Thread32First(snapshot, byref(thread_entry))
            print ("[*] Snapshot check %d" % success)
           
            while success:
                if thread_entry.th32OwnerProcessID == self.pid :
                    thread_list.append(thread_entry.th32ThreadID)
                success = kernel32.Thread32Next(snapshot, byref(thread_entry))   
                print ("[*] Snapshot check %d" % success)


            kernel32.CloseHandle(snapshot)

            print ("[*] Snapshot handle closed")

            return thread_list

        else: 

            return False


[*] Getting Thread Context success
[*] Dumping registers for thread ID: 0x000029e8
[*] EIP : 0x772e8f00
[*] ESP : 0x0077fff0
[*] EBP : 0x00000000
[*] EAX : 0x77319d20
[*] EBX : 0x00000000
[*] ECX : 0x00000000
[*] EDX : 0x00000000
[*] End DUMP
[*] Finished debugging. Exiting...


앞서 범용 CPU register에서 살펴 보았지만 다시 한번 복습하는 의미에서

EIP : Instruction Pointer

ESP : Stack Pointer

EBP : Base Pointer

EAX : Accumulator register

EBX : 추가적인 register

ECX : Count register

EDX : Data register





반응형

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

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
ICMP Decoding with Python  (0) 2016.03.16

'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
ZXlkTVExOU9WVTFGVW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', '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

+ Recent posts