Search results for 'Code'

SendMessage by winappdbg

2013. 6. 12. 15:27

특정 Control에 특정 메세지를 전송.

target window 아래 child window을 뒤져 원하는 핸들값을 찾아내고 메시지를 전송.


from winappdbg import System, version, HexDump, win32
import sys, time

def send_input(hwnd, msg):
    for c in msg:
            win32.SendMessage(hwnd, user32.WM_CHAR, ord(c), 0)
            time.sleep(0.5)

user32 = win32.user32

txt = 'I am Legend.\n'

system = System()

for window in system.get_windows():
    if window.classname == 'Notepad':
        tmp =  user32.EnumChildWindows(window)
        for x in tmp:
            if user32.GetClassNameA(x) == 'Edit':
                send_input(x, txt)


'Code > Python' 카테고리의 다른 글

decode captcha by python  (0) 2012.11.12
handling HTTP by python module  (0) 2011.07.04
ISEC 2009 level3 solution by winappdbg  (0) 2010.09.16
hust 8th level D - python  (0) 2009.10.17

badcob Code/Python

decode captcha by python

2012. 11. 12. 01:10
보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

ASLR&DEP viewer

2012. 8. 25. 11:41


Windows에서 특정 프로그램을 실행할 때 로딩되는 라이브러리 목록과 

각 라이브러리들의 ASLR과 DEP flag 설정 여부를 보여준다.


원래는 누군가가 만든 툴처럼 여기에 gadget finder를 추가해서 windows 환경에서 exploit 만들 때 쓸려고 했었다.


mfc는 분석만 해보고 만져본적이 없어서 api로 만들었는데,

기능을 더 추가하면 ui 배치를 어떻게 할지가 고민도 되고 해서 걍 팽개침.


마저 해볼까 라는 생각에 또 버려둘까 두려워 이렇게 올려둠.



#include <Windows.h>
#include <stdio.h>
#include <TlHelp32.h>
#include <Psapi.h>
#include <time.h>
#include "resource.h"
#include <commctrl.h>
#include <time.h>

#pragma comment(lib, "psapi.lib")

#define ID_LISTBOX 100

LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
DWORD checkTarget(char *modName, int iNumber);

HINSTANCE g_hInst;                                     
HWND hList;
OPENFILENAME OFN;

const char* lpszClass="ASLR&DEP Viewer";

DWORD i;
LVCOLUMN COL;
LVITEM LI;

HMODULE hMod;
HMODULE hModules[1024] = {0};
HANDLE hProcess;
DWORD ProcArray[1024] = {0};
DWORD nBytes, NumProc, nPid, cbNeeded;

char szModName[MAX_PATH];

STARTUPINFO si;
PROCESS_INFORMATION pi;

char str[300];
char lpstrFile[MAX_PATH] = "";

int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszCmdParam,int nCmdShow)
{
	HWND hWnd;
	MSG Message;
	WNDCLASS WndClass;
	g_hInst=hInstance;
 
	WndClass.cbClsExtra=0;
	WndClass.cbWndExtra=0;
	WndClass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
	WndClass.hCursor=LoadCursor(NULL,IDC_ARROW);
	WndClass.hIcon=LoadIcon(NULL,IDI_APPLICATION);
	WndClass.hInstance=hInstance;
	WndClass.lpfnWndProc=WndProc;
	WndClass.lpszClassName=lpszClass;
	WndClass.lpszMenuName=MAKEINTRESOURCE(IDR_MENU1);
	WndClass.style=CS_HREDRAW | CS_VREDRAW;

	RegisterClass(&WndClass);
	hWnd=CreateWindow(lpszClass,lpszClass,WS_OVERLAPPEDWINDOW|WS_VSCROLL,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,(HMENU)NULL,hInstance,NULL);
	ShowWindow(hWnd,nCmdShow);
 
	while (GetMessage(&Message,NULL,0,0)) {
		TranslateMessage(&Message);
		DispatchMessage(&Message);
	}

	return (int)Message.wParam;
}

void SetListViewStyle(HWND hList, DWORD dwView)
{
	DWORD dwStyle;

	dwStyle=GetWindowLong(hList, GWL_STYLE);
	if ((dwStyle & LVS_TYPEMASK) != dwView) {
		SetWindowLong(hList, GWL_STYLE, (dwStyle & ~LVS_TYPEMASK) | dwView);
	}
}

LRESULT CALLBACK WndProc(HWND hWnd,UINT iMessage,WPARAM wParam,LPARAM lParam)
{

	switch (iMessage) {
		case WM_CREATE:
			hList=CreateWindow(WC_LISTVIEW,NULL,WS_VISIBLE|WS_CHILD|WS_BORDER|LVS_REPORT,10,10,600,300,hWnd,NULL,g_hInst,NULL);

			COL.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
			COL.fmt = LVCFMT_LEFT;
			COL.cx=150;
			COL.pszText="Name";
			COL.iSubItem=0;
			ListView_InsertColumn(hList,0,&COL);

			COL.pszText="ASLR";
			COL.iSubItem=1;
			ListView_InsertColumn(hList,1,&COL);

			COL.pszText="DEP";
			COL.iSubItem=2;
			ListView_InsertColumn(hList,2,&COL);
			return 0;

		case WM_COMMAND:
			switch(LOWORD(wParam))
			{			
				case ID_FILE_OPEN1:
					memset(&OFN, 0, sizeof(OPENFILENAME));
					OFN.lStructSize = sizeof(OPENFILENAME);
					OFN.hwndOwner=hWnd;
					OFN.lpstrFilter="Exe file\0*.exe\0Dll file\0*.dll\0";
					OFN.lpstrFile=lpstrFile;
					OFN.nMaxFile=255;
					OFN.lpstrInitialDir="c:\\";
#if 1
					if (GetOpenFileName(&OFN)!=0) {
						//wsprintf(str,"You select %s .",OFN.lpstrFile);
						//MessageBox(hWnd,str,"Yeah",MB_OK);
					}
					else {
						MessageBox(hWnd, "You should select file.", "Error", MB_OK);
						return 0;
					}
#endif

					if( !CreateProcess( NULL,  
						lpstrFile,        
						NULL,           
						NULL,           
						FALSE,          
						//CREATE_NO_WINDOW|CREATE_SUSPENDED,              
						CREATE_NO_WINDOW,
						NULL,           
						NULL,           
						&si,            
						&pi )           
					) 
					{
						MessageBox(hWnd, "CreateProcess failed.", "Error", MB_OK);
					}

					hProcess = pi.hProcess;
					nPid = pi.dwProcessId;					
					
					Sleep(1000);

					if(EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeeded))
					{
						

						for (i=0; i < (signed)(cbNeeded / sizeof(HMODULE)); i++)
						{
							if (GetModuleFileNameEx(hProcess, hModules[i], szModName, sizeof(szModName)/sizeof(char))&&i!=0)
							{
								checkTarget(szModName, i);
							}
						}
					}
					else
					{
						MessageBox(hWnd, "EnumProcessModule failed.", "Error", MB_OK);
					}
					break;
				case ID_FILE_EXIT1:
					break;
			}
			return 0;
		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;
	}

	return(DefWindowProc(hWnd,iMessage,wParam,lParam));
}

DWORD error(const char* message){
	MessageBox(NULL,message,"ERROR",MB_OK);
	return 1;
}

DWORD checkTarget(char *modName, int iNumber){
	HANDLE h = CreateFileA(modName,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	if(h==INVALID_HANDLE_VALUE)
		return error("Cannot open file.");
	BYTE headers[1000];
	DWORD read;
	ReadFile(h,headers,1000,&read,NULL);

	IMAGE_DOS_HEADER* idh = (IMAGE_DOS_HEADER*)headers;
	if(read<sizeof(IMAGE_DOS_HEADER))
		return error("Invalid DOS header");
	IMAGE_NT_HEADERS* inh =(IMAGE_NT_HEADERS*)(headers+idh->e_lfanew);
	if(read < idh->e_lfanew + sizeof(IMAGE_NT_HEADERS))
		return error("Invalid NT header");
	if(inh->Signature!=0x00004550)
		return error("Invalid NT header");

	BOOL aslr = inh->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
	
	BOOL dep = inh->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT;

	DWORD listNum = ListView_GetItemCount(hList);

	LI.mask = LVIF_TEXT;
	LI.state = 0;
	LI.stateMask = 0;

	LI.iSubItem=0;
	LI.iItem=iNumber;	
	LI.pszText = modName;
	ListView_InsertItem(hList, &LI);

	if (aslr) {
		ListView_SetItemText(hList,listNum,1,"ASLR");
	}
	else {
		ListView_SetItemText(hList, listNum, 1, "No ASLR");
	}
	if (dep) {
		ListView_SetItemText(hList, listNum, 2, "DEP");
	}
	else {
		ListView_SetItemText(hList, listNum, 2, "No DEP");
	}

	return 0;
}


badcob Code/C

handling HTTP by python module

2011. 7. 4. 01:03

파이썬으로 네크워크 프로그래밍을 할때 일반적으로 아래의 모듈들을 사용한다.

socket, httplib,urllib, urllib2, etc..

상황에 따라 다르겠지만 urllib, urllib2, httplib 애들은 이름부터 비슷해서 기능들도 비슷비슷하다

각각 사용해야 될 상황이 있을 법한데 그때 그때 구현해서 쓰다보니 뭐가 뭔지 헷갈림.. 
그래서 구글링을 해보니 생각보다 간단하다.

1) urllib2는 Request class를 통해서 헤더를 조작할수 있다는 것과
2) urlencode는 urllib에만 있다는 것

그러니깐 urllib2는 보다 디테일한 제어가 가능하지만 몇몇 기능 떄문에 urllib를 써야 한다는 정도.
httplib는 아래 코멘트로 설명이 될듯.

If you're dealing solely with http/https and need access to HTTP specific stuff, use httplib. For all other cases, use urllib2.
urllib/urllib2 is built on top of httplib. It offers more features than writing to httplib directly.


example. socket 

from socket import *

host = "blabla"
port = 80
payload = "GET / HTTP/1.1\r\n"

s = socket(AF_INET, SOCK_STREAM)
s.connect((host, port))
s.send(payload)
r = s.recv(1024)
print "[+] Receive - %s" % r


example urllib2,urllib
wechall.net에 있는 문제 중에 하나.
urllib2에서 Request 클래스를 생성할 때, data 값이 있으면 POST 로 전송한다. 
따라서 GET으로 전송하고 싶으면 add_header 메소드로 추가.


import urllib,urllib2,re

url = 'http://www.wechall.net/challenge/training/programming1/index.php?action=request'
callback_url = 'http://www.wechall.net/challenge/training/programming1/index.php?answer='

#param = {'action':'request'}
#data = urllib.urlencode(param)

sid = "WC4_SID=921244-6205-R8w9DSKbppv6P4pE"

req = urllib2.Request(url)
req.add_header('cookie',sid)
f = urllib2.urlopen(req)

text = f.read()
#answer = re.findall('page_wrap\">\n[a-zA-Z0-0]{9}',text)
t = re.findall('[a-zA-Z0-9]+',text)
t.reverse()
answer = t[0]

req = urllib2.Request(callback_url+answer)
req.add_header('cookie',sid)
f = urllib2.urlopen(req)
print f.read()

'Code > Python' 카테고리의 다른 글

SendMessage by winappdbg  (0) 2013.06.12
decode captcha by python  (0) 2012.11.12
ISEC 2009 level3 solution by winappdbg  (0) 2010.09.16
hust 8th level D - python  (0) 2009.10.17

badcob Code/Python

ISEC 2009 level3 solution by winappdbg

2010. 9. 16. 22:14

Level : 3


This program is Encoder.
I encoded the plaintext And memo the encoded string.
But I fotget the plaintext!!!
SHIT, What the...!!!
I don't have decoder!
I hope you decode this string!

Encoded string : A1 FD 7E F6 F0 70 98 D6 E5 F8 FF F8 78 B8 DE ED 0D

p.s) You should input the key which are removed the space in plaintext!
ex.) a b cd(x) => abcd(o)

풀이



Python code


WinAppDbg Tutorial & Reference



불량식품이랑 문제 풀이는 철이 지나야 제맛.

'Code > Python' 카테고리의 다른 글

SendMessage by winappdbg  (0) 2013.06.12
decode captcha by python  (0) 2012.11.12
handling HTTP by python module  (0) 2011.07.04
hust 8th level D - python  (0) 2009.10.17

badcob Code/Python

move 명령어

2010. 9. 7. 02:29

http://faydoc.tripod.com/cpu/movsd.htm 에 본문이 있슴.

Code Mnemonic Description
A4 MOVS m8, m8 Move byte at address DS:(E)SI to address ES:(E)DI
A5 MOVS m16, m16 Move word at address DS:(E)SI to address ES:(E)DI
A5 MOVS m32, m32 Move doubleword at address DS:(E)SI to address ES:(E)DI
A4 MOVSB Move byte at address DS:(E)SI to address ES:(E)DI
A5 MOVSW Move word at address DS:(E)SI to address ES:(E)DI
A5 MOVSD Move doubleword at address DS:(E)SI to address ES:(E)DI

Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified with the first operand (destination operand). Both the source and destination operands are located in memory. The address of the source operand is read from the DS:ESI or the DS:SI registers (depending on the address-size attribute of the instruction, 32 or 16, respectively). The address of the destination operand is read from the ES:EDI or the ES:DI registers (again depending on the address-size attribute of the instruction). The DS segment may be over-ridden with a segment override prefix, but the ES segment cannot be overridden.

대충 메모리에 있는 데이터를  바이트,워드, 더블 워드 만큼 ESI(src address)에서 EDI(dst address)로 옮긴단 얘기. 계속 설명을 보면..

After the move operation, the (E)SI and (E)DI registers are incremented or decremented automatically according to the setting of the DF flag in the EFLAGS register. (If the DF flag is 0, the (E)SI and (E)DI register are incremented; if the DF flag is 1, the (E)SI and (E)DI registers are decremented.) The registers are incremented or decremented by 1 for byte operations, by 2 for word operations, or by 4 for doubleword operations.

Move 연산 이후에 ESI와 EDI 레지스터는 EFLAGS 레지스터의 DF 플래그에 따라서 값이 증가하거나 감소되거나 한다. DF 가 0 이면 증가, 1이면 감소, 사이즈에 따라서 연산되는 크기도 달라지고.. 마지막엔 이렇게 나와있다.

The MOVS, MOVSB, MOVSW, and MOVSD instructions can be preceded by the REP prefix

MOVS 류 명령어 앞에는 REP 가 올 수 있단다.
같은 사이트에서 REP를 찾아보면..


Code Mnemonic Description
F3 6C REP INS r/m8, DX Input (E)CX bytes from port DX into ES:[(E)DI]
F3 6D REP INS r/m16, DX Input (E)CX words from port DX into ES:[(E)DI]
F3 6D REP INS r/m32, DX Input (E)CX doublewords from port DX into ES:[(E)DI]
F3 A4 REP MOVS m8, m8 Move (E)CX bytes from DS:[(E)SI] to ES:[(E)DI]
F3 A5 REP MOVS m16, m16 Move (E)CX words from DS:[(E)SI] to ES:[(E)DI]
F3 A5 REP MOVS m32, m32 Move (E)CX doublewords from DS:[(E)SI] to ES:[(E)DI]
F3 6E REP OUTS DX, r/m8 Output (E)CX bytes from DS:[(E)SI] to port DX
F3 6F REP OUTS DX, r/m16 Output (E)CX words from DS:[(E)SI] to port DX
F3 6F REP OUTS DX, r/m32 Output (E)CX doublewords from DS:[(E)SI] to port DX
F3 AC REP LODS AL Load (E)CX bytes from DS:[(E)SI] to AL
F3 AD REP LODS AX Load (E)CX words from DS:[(E)SI] to AX
F3 AD REP LODS EAX Load (E)CX doublewords from DS:[(E)SI] to EAX
F3 AA REP STOS m8 Fill (E)CX bytes at ES:[(E)DI] with AL
F3 AB REP STOS m16 Fill (E)CX words at ES:[(E)DI] with AX
F3 AB REP STOS m32 Fill (E)CX doublewords at ES:[(E)DI] with EAX
F3 A6 REPE CMPS m8, m8 Find nonmatching bytes in ES:[(E)DI] and DS:[(E)SI]
F3 A7 REPE CMPS m16, m16 Find nonmatching words in ES:[(E)DI] and DS:[(E)SI]
F3 A7 REPE CMPS m32, m32 Find nonmatching doublewords in ES:[(E)DI] and DS:[(E)SI]
F3 AE REPE SCAS m8 Find non-AL byte starting at ES:[(E)DI]
F3 AF REPE SCAS m16 Find non-AX word starting at ES:[(E)DI]
F3 AF REPE SCAS m32 Find non-EAX doubleword starting at ES:[(E)DI]
F2 A6 REPNE CMPS m8, m8 Find matching bytes in ES:[(E)DI] and DS:[(E)SI]
F2 A7 REPNE CMPS m16, m16 Find matching words in ES:[(E)DI] and DS:[(E)SI]
F2 A7 REPNE CMPS m32, m32 Find matching doublewords in ES:[(E)DI] and DS:[(E)SI]
F2 AE REPNE SCAS m8 Find AL, starting at ES:[(E)DI]
F2 AF REPNE SCAS m16 Find AX, starting at ES:[(E)DI]
F2 AF REPNE SCAS m32 Find EAX, starting at ES:[(E)DI]

Repeats a string instruction the number of times specified in the count register ((E)CX) or until the indicated condition of the ZF flag is no longer met. The REP (repeat), REPE (repeat while equal), REPNE (repeat while not equal), REPZ (repeat while zero), and REPNZ (repeat while not zero) mnemonics are prefixes that can be added to one of the string instructions. The REP prefix can be added to the INS, OUTS, MOVS, LODS, and STOS instructions, and the REPE, REPNE, REPZ, and REPNZ prefixes can be added to the CMPS and SCAS instructions. (The REPZ and REPNZ prefixes are synonymous forms of the REPE and REPNE prefixes, respectively.) The behavior of the REP prefix is undefined when used with non-string instructions

ECX  또는 ZF 플래그 조건이 충족되는 만큼 문자열 명령을 반복한다.

따라서 REP  MOVSD 일때 ECX가 10 이면, ESI 레지스터의 값을 EDI로 10 번 옮기게 된다.

매번 까먹고 구글링에 지쳐서.. 적어놓으면 좀 나을려나.


'Code > assembly' 카테고리의 다른 글

기본 색인 주소 지정 모드  (4) 2009.08.09

badcob Code/assembly

hust 8th level D - python

2009. 10. 17. 19:07

받아온 키를 한줄 씩 전송 해 봤지만 첫 줄만 보내도 패스워드를 얻을 수 있었다.


import struct,base64,httplib, urllib
from socket import *
svrsocket = socket(AF_INET, SOCK_STREAM)
svrsocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
svrsocket.bind(('', 7777))
svrsocket.listen(1)
conn, addr = svrsocket.accept()
i = 0 
sum = ''
buf =conn.recv(1024)
#print buf
j = 0 
result = []
try:
    while 1:
        if buf[j]:
            if buf[j] == '\x0a':
                j+=1
                result.append(sum)
                sum = ''
                pass
            sum += buf[j]
            j+=1
        else:
            break
except:
    pass
#print result
conn.close()

try:
    for x in result:
        auth = base64.b64encode("admin:21d0ac6b17066785986d4ea3dcaf2c72")
        params = urllib.urlencode({'passwd':x,'submit':'SEND+PASSWORD+KEY'})
        headers = {'Content-Type':'application/x-www-form-urlencoded','Authorization': 'Basic %s'%auth}
        conn = httplib.HTTPConnection("220.95.152.132:80")
        conn.request("POST", "/login_ok.php", params, headers)
        response = conn.getresponse()
        data = response.read()
        print data
        conn.close()
except:
    pass

'Code > Python' 카테고리의 다른 글

SendMessage by winappdbg  (0) 2013.06.12
decode captcha by python  (0) 2012.11.12
handling HTTP by python module  (0) 2011.07.04
ISEC 2009 level3 solution by winappdbg  (0) 2010.09.16

badcob Code/Python

기본 색인 주소 지정 모드

2009. 8. 9. 04:31


아래의 코드는 어느 바이너리의 특정 함수를 objdump 로 디스어셈블한 것이다.

사용자 삽입 이미지


 0x8048508에 있는 구문을 보자

     lea    (%edx, %eax, 1), %eax
   
  주소를 eax 에 넣긴 하는거 같은데 어떻게 계산이 이루어지는 지 모르겠다. 도와줘요 IDA~~
  
사용자 삽입 이미지
 

AT&T 문법에 맞춰서 디스어셈블되면  

lea   eax, [edx+eax]  로 바뀐 것을 볼 수 있다.

구글링을 해보니 리눅스 어셈블러: GAS와 NASM 비교 라는 글에서 다음과 같은 설명을 찾을 수 있었다.



NASM: mov al, byte [ebx + esi]

GAS: movb (%ebx, %esi, 1), %al

이런 방식은 기본 색인 주소 지정 모드다. 여기서 구성요소가 세 개 등장한다. 첫째는 기본 주소, 둘째는 색인 레지스터, 셋째는 승수(乘數)다. 메모리 위치에서 접근하는 바이트 숫자를 결정하기란 불가능하므로 주소를 지정한 메모리 총량을 찾아내기 위한 방법이 필요하다. NASM은 byte 연산자를 사용해 자료에서 한 바이트가 이동했음을 어셈블러에 알려준다. GAS에서는 니모닉에 b, w, l 접미사를 붙이는(예를 들어, movb) 동시에 승수를 사용해 이런 문제를 해결한다. 처음 보면 GAS 구문이 좀더 복잡해보일 수도 있다.

GAS에서 일반적인 기본 색인 주소 지정 형식은 다음과 같다.

%segment:ADDRESS (, index, multiplier)

또는

%segment:(offset, index, multiplier)

또는

%segment:ADDRESS(base, index, multiplier)

이 공식을 사용해 최종 주소를 계산한다.

ADDRESS or offset + base + index * multiplier.

따라서 바이트에 접근하려면 승수는 1이 되며, 워드에 접근하려면 승수는 2가 되며, 더블 워드에 접근하려면 승수가 4가 되어야 한다. 물론 NASM은 좀더 단순한 구문을 사용한다. 따라서 NASM으로 상기 공식을 풀어쓰면 다음과 같다.

Segment:[ADDRESS or offset + index * multiplier]

각각 메모리 1, 2, 4 바이트에 접근하도록 byte, word, dword 접두사를 메모리 주소 앞에 표시한다.



즉, movb (%ebx, %esi, 1), %al 구문으로 설명한다면  

ebx(address or offset) 의 값에 esi(index)를 더해서 al 레지스터로 옮긴다.
3번째 인자로 인덱스를 byte, word, dword 단위로 조정할 수 있으며 위의 코드에서는  
바이트(1) 단위로 접근하는 것을 알 수 있다.
 


'Code > assembly' 카테고리의 다른 글

move 명령어  (0) 2010.09.07

badcob Code/assembly