Be myself :: Be myself

달력

42024  이전 다음

  • 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
#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
|