2018년 9월 19일 수요일

[word] 1

hardware abstraction 추상화

ART and its predecessor Dalvik were originally created specifically for the Android project
predecessor :  전신의

ART as the runtime executes the Dalvik Executable format and Dex bytecode specification
bytecode specification : 바이트코드 지정(설명서, 사양)

ART and Dalvik are compatible runtimes running Dex bytecode
compatible : 호환되는

ART introduces ahead-of-time (AOT) compilation, which can improve app performance
improve: 향상시키다.
performance : 성능

ART also has tighter install-time verification than Dalvik.
tight : 엄격한

This utility accepts DEX files as input and generates a compiled app executable for the target device
accepts : 받아들이다.
generates : 생성하다.

The utility should be able to compile all valid DEX files without difficulty
valid : 유효한
difficulty : 문제

However, some post-processing tools produce invalid files that may be tolerated by Dalvik but cannot be compiled by ART.
post-processing: 일부 처리된
invalid : 잘못된, 무효의
tolerate: 용납하다, 참다




2018년 1월 8일 월요일

[OS] 내용 정리

세그먼테이션

[ PHP] 게시판

mysql

DB생성
create database comdoctor;

회원 테이블 생성
create table user(email varchar(50), pass varchar(100), nick varchar(20), primary key(email) )Engine='InnoDB' default charset='utf8';

create table membership(email varchar(50) not null, grade int unsigned, rank int unsigned, point int unsigned, primary key(email) )Engine='InnoDB' default charset='utf8';

insert into user values('sangoochoi@gmail.com','111111','Comdoctor');
insert into membership values('sangoochoi@gmail.com',1,0,9999);


================================================
php source

[C] 버블정렬

/*버블정렬*/
void smp_ahl_bubblesort()
{
int n_arr[ARR_MAX]={10,50,1,3,100,90,78,12,22,34,56,11,51,2,8,101,91,79,13,23,35,57};
int n_count = sizeof(n_arr)/4;
int n_mid = n_count/2;
int i, j, tmp;

for(i=0; i<n_mid; i++)
{
for(j=1; j<n_count-i; j++)
{
if(n_arr[j-1] > n_arr[j])
{
tmp = n_arr[j];
n_arr[j] = n_arr[j-1];
n_arr[j-1] = tmp;
}
}
}

for(i=0; i<ARR_MAX; i++)
{
printf("%d\n",n_arr[i]);
}
}

2018년 1월 3일 수요일

[C] 이중연결리스트

test.c

#include "comdr.h"
#include "list.h"
#include <stdio.h>

#define ARR_MAX 22

int main(int argc, char **argv)
{
LinkedList* list = list_createList();

list_insertBack(list, 1);
list_insertBack(list, 2);
list_insertBack(list, 3);
list_insertBack(list, 4);
list_insertBack(list, 5);
list_insertBack(list, 6);
list_insertBack(list, 7);

list_printAll(list);


return 0;
}


list.h

#pragma once
#include "comdr.h"

//===== struct =====
typedef struct _Node Node;
struct _Node
{
Node *next;
Node *prev;
#ifdef TEST
int data;
#else
void* data;
#endif
};

typedef struct
{
Node *head;
Node *tail;
int count;
}LinkedList, *LPLinkedList;

//===== function =====
LPLinkedList
list_createList();

BOOL
list_deleteList(LPLinkedList plist);



#ifdef TEST
Node*
list_newNode(int data);

void
list_insertBack(LPLinkedList plist, int data);

void
list_insertPront(LPLinkedList plist, int data);
#else
Node*
list_newNode(void* data);

void
list_insertBack(LPLinkedList plist, void* data);

void
list_insertPront(LPLinkedList plist, void* data);
#endif

void list_printAll(LPLinkedList plist);


list.c

#include "list.h"
#include <stdio.h>
#include <stdlib.h>

#ifdef TEST
void list_insertBack(LPLinkedList plist, int data)
{
Node* newNode = list_newNode(data);
if(plist->count == 0)
{
plist->head = newNode;
plist->tail = plist->head;
}
else
{
newNode->prev = plist->tail;
plist->tail->next = newNode;
plist->tail = newNode;
}
plist->count++;
}

void list_printAll(LPLinkedList plist)
{
Node* cur = plist->head;
while(cur)
{
printf("%d ",cur->data);
cur = cur->next;
}
}

Node* list_newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->next = null;
node->prev = null;
node->data = data;
return node;
}
#endif


LPLinkedList list_createList()
{
LPLinkedList list = (LPLinkedList)malloc(sizeof(LPLinkedList));
list->head = null;
list->tail = null;
list->count = 0;
return list;
}

BOOL list_deleteList(LPLinkedList plist)
{
if(!plist)
return FALSE;
else
{
if(plist->tail == plist->head)
free(plist);
else
{
Node* cur = plist->tail;
Node* tmp = null;
while(!cur->prev)
{
tmp = cur;
cur = cur->prev;
free(tmp);
}
}
}
}


comdr.h

#pragma once

#define TEST
#define NOT_INCLUDE_WINDOWS_H

#ifdef NOT_INCLUDE_WINDOWS_H
#define FALSE 0
#define TRUE 1
typedef int BOOL;
#endif

typedef unsigned int uint;
typedef unsigned char byte;

#define null 0

2017년 12월 6일 수요일

[Pin tool] 메뉴얼 해석

=======================================================
  • Pin 3.5 User Guide
Pin is a tool for the instrumentation of programs. It supports the Linux*, OS X* and Windows* operating systems and executables for the IA-32, Intel(R) 64 and Intel(R) Many Integrated Core architectures.
-> Pin은 프로그램의 측정을위한 도구이다.  IA-32, Intel(R)64, Intel(R), 통합 코어 아키텍쳐에 실행 가능한 파일들 그리고 Linux, OS X * 및 Windows * 운영 체제들을 지원한다.

Pin allows a tool to insert arbitrary code (written in C or C++) in arbitrary places in the executable. The code is added dynamically while the executable is running. This also makes it possible to attach Pin to an already running process.
-> Pin은 실행 가능한 파일에 임임의 공간에 임의의 코드(C 또는 C++로 작성된)를 삽입하기 위한 도구로 사용된다. 삽입된 코드는 실행 가능한 파일이 실행중에 동적으로 추가된다. 또한 이미 실행중인 프로세스에 Pin에 붙이는 것도 가능하다.

Pin provides a rich API that abstracts away the underlying instruction set idiosyncracies and allows context information such as register contents to be passed to the injected code as parameters. Pin automatically saves and restores the registers that are overwritten by the injected code so the application continues to work. Limited access to symbol and debug information is available as well.
-> Pin은 기본 명령어 세트의 특이성을 추상화하고 레지스터 내용 등의 컨텍스트 정보를 주입 된 코드에 매개 변수로 전달할 수있는 풍부한 API를 제공한다. Pin은 응용프로그램이 계속 작동하도록 삽입된 코드에 의해 무시된 레지스터를 자동으로 저장되고 복구된다. 심볼과 디버그 정보의 접근도 제한되있다.

Pin includes the source code for a large number of example instrumentation tools like basic block profilers, cache simulators, instruction trace generators, etc. It is easy to derive new tools using the examples as a template
-> Pin은 basic block profilers, cache simulators, instruction trace generators, 그외 수 많은 양의 측정 도구 예제 소스 코드를 포함한다. 이 샘플들은 예제 탬플릿으로 사용하여 새로운 도구를 이끌어 내기 쉽다.

Tutorial Sections
  • How to Instrument With Pin
  • Examples
  • Callbacks
  • Modifying Application Instructions
  • The Pin Advanced Debugging Extensions
  • Applying a Pintool to an Application
  • Debugging Tips for Debugging a Pintool
  • Recording Messages from a Pintool
  • Performance Considerations
  • Memory management
  • PinTools Information and Restrictions
  • Building Tools on windows
  • Libraries for Windows
  • Libraries for Linux
  • Installation
  • Building Your Own Tool
  • Pin's makefile Infrastructure
  • Feedback
  • Disclaimer and Legal Information


How to Instrument With Pin(핀을 사용하여 측정하는 방법)
  • Pin
  • Pintools
  • Observations
  • Instrumentation Granularity
  • Managed platforms support
  • Symbols
  • Floating Point Support in Analysis Routines
  • Instrumenting Multi-threaded Applications
  • Avoiding Deadlocks in Multi-threaded Applications
The best way to think about Pin is as a "just in time" (JIT) compiler. The input to this compiler is not bytecode, however, but a regular executable
-> Pin에 대한 최선의 방법은 "just in time"(JIT) 컴파일러 이다. 하지만 이 컴파일러의 입력은 바이트코드가 아니다. 그러나 일반 실행 파일이다.

Pin intercepts the execution of the first instruction of the executable and generates ("compiles") new code for the straight line code sequence starting at this instruction.
-> Pin은 실행 파일의 첫번째  명령의 실행을 차단하고 이 명령에서 시작하는 straight line code sequence를 위한 새로운 코드를 발생(컴파일)시킨다.

It then transfers control to the generated sequence. The generated code sequence is almost identical to the original one, but Pin ensures that it regains control when a branch exits the sequence.
-> 그 후 생성된 sequence 제어로 이동한다. 발생된 code sequence는 원래 코드 순서와 거의 동일하다. 그러나 Pin은 분기 sequence를 종료할 때 제어를 회복하는 것을 보장한다.

After regaining control, Pin generates more code for the branch target and continues execution. Pin makes this efficient by keeping all of the generated code in memory so it can be reused and directly branching from one sequence to another.
-> 제어가 복구된 후에 Pin은 분기된 코드를 더 생성하고 실행을 계속한다. Pin은
하나의 시퀀스에서 다른 시퀀스로부터 직접 분기하고 재사용 하기 할 수 있게 메모리에 생성된 코드 전부를 보관하는 것이 효율적이다.

In JIT mode, the only code ever executed is the generated code. The original code is only used for reference. When generating code, Pin gives the user an opportunity to inject their own code (instrumentation).
-> JIT 모드에서 실행된 코드는 생성된 코드이다. 원래 코드는 참조를 위해 사용되어진다.
코드가 생성될 때 Pin은 사용자 자신의 코드(instrumentation)를 주입 할 수 있는 기회를 제공한다.

Pin instruments all instructions that are actually excuted. It does not matter in what section they reside. Although there are some exceptions for conditional branches, generally speaking, if an instruction is never executed then it will not be instrumented.
-> 실제로 실행된 모든 명령들은 Pin으로 측정한다. 어느 섹션에 그들이 존재하는지 중요하지 않다. 비록 그들은 조건 분기에는 몇가지 예외가 있지만 일반적으로 명령이 실행되지 않으면 명령은 인스트루먼트되지 않는다.

  • Pintools
Conceptually, instrumentation consists of two components:
-> 개념적으로 Instrumentation은 두가지의 Component로 구성되어 있다

    • A mechanism that decides where and what code is inserted
-> 어디에 어떤 코드가 삽입되는지를 결정하는 메커니즘
    • The code to execute at insertion points
-> 삽입 지점에서 실행되는 코드

These two components are instrumentation and analysis code. Both components live in a single executable, a Pintool. Pintools can be thought of as plugins that can modify the code generation process inside Pin.
-> 이러한 두 Components는 계측 과 분석 코드이다. 두 Component 는 단일 실행파일, Pintool에 존재한다. Pintool은 Pin 내 코드 생성 프로세스를 변경할 수 있는 플러그인이라고 생각 할 수 있다.

The Pintool registers instrumentation callback routines with Pin that are called from Pin whenever new code needs to be generated. This instrumentation callback routine represents the instrumentation component. It inspects the code to be generated, investigates its static properties, and decides if and where to inject calls to analysis functions.
-> Pintool은 언제든 새로운 코드가 생성되기 위해 필요한 Pin으로 부터 호출된 Pin과 함께 계측(instrumentation)  콜백 루틴을 등록한다. 이 계측(instrumentation)  콜백 루틴은 계측 component를 나타낸다. 생성된 코드를 검사하고, 정적 속성을 검사하여 분석 함수에 호출을 어디에 삽입할지 결정한다.

The analysis function gathers data about the application. Pin makes sure that the integer and floating point register state is saved and restored as necessary and allow arguments to be passed to the functions.
-> 분석 함수는 응용프로그램에 대한 데이터를 수집한다. Pin은 정수, 소수점 레지스터의 상태가 필요에 따라 저장 및 복원되고 함수에 전달되는 것을 허용한다.

The Pintool can also register notification callback routines for events such as thread creation or forking. These callbacks are generally used to gather data or tool initialization or clean up.
-> 또한 Pintool은 스레드 생성 또는 포크와 같은 이벤트를 위한 알림 콜백 루틴을 등록할 수 있다. 이 콜백은 일반적으로 데이터 수집 또는 도구 초기화 및 정리를 위해 사용된다.

  • Observations
Since a Pintool works like a plugin, it must run in the same address space as Pin and the executable to be instrumented. Hence the Pintool has access to all of the executable's data. It also shares file descriptors and other process information with the executable.
-> Pintool은 플러그인 처럼 동작하기 때문에 Pin과 계측 가능한 실행파일이 같은 주소 공간에서 실행한다. 따라서 Pintool은 모든 실행 파일의 데이터를 엑세스 할 수 있다. 또한 파일 디스크립터 및 실행파일과 기타 프로세스 정보를 공유한다.

Pin and the Pintool control a program starting with the very first instruction. For executables compiled with shared libraries this implies that the execution of the dynamic loader and all shared libraries will be visible to the Pintool.
-> Pin과 Pintool은 첫 번째 명령에서 프로그램 시작을 제어한다. 공유 라이브러리로 컴파일된 실행파일인 경우 이것은 동적 로더 및 모든 공유라이브러리의 실행이 Pintool에 표시되는 것을 의미한다.

When writing tools, it is more important to tune the analysis code than the instrumentation code. This is because the instrumentation is executed once, but analysis code is called many times.
-> 도구를 쓸 때 측정 코드보다 분석 코드를 조정하는 것이 중요하다. 이것은 측정이 1 회 실행되지만, 분석 코드가 여러 번 호출되기 때문이다.



  • Instrumentation Granularity

As described above, Pin's instrumentation is "just in time" (JIT). Instrumentation occurs immediately before a code sequence is executed for the first time. We call this mode of operation trace instrumentation .
-> 전술 한 바와 같이, Pin의 측정은 "just in time" 이다. 계측은 코드 시퀀스가 처음  실행되기 전에 즉시 발생한다. 우리는 작업 모드를 Trace instrumentation이라고 부른다.

Trace instrumentation lets the Pintool inspect and instrument an executable one trace at a time. Traces usually begin at the target of a taken branch and end with an unconditional branch, including calls and returns. Pin guarantees that a trace is only entered at the top, but it may contain multiple exits.
-> Trace instrumentation는 Pintool 점검과 도구


If a branch joins the middle of a trace, Pin constructs a new trace that begins with the branch target. Pin breaks the trace into basic blocks, BBLs. A BBL is a single entrance, single exit sequence of instructions. Branches to the middle of a bbl begin a new trace and hence a new BBL. It is often possible to insert a single analysis call for a BBL, instead of one analysis call for every instruction. Reducing the number of analysis calls makes instrumentation more efficient. Trace instrumentation utilizes the


https://software.intel.com/sites/landingpage/pintool/docs/97503/Pin/html/index.html#INSTRUMENTING

2017년 11월 23일 목요일

참고 사이트

SSL
https://opentutorials.org/course/228/4894

Frida IOS
http://bachs.tistory.com/entry/iOS-Hooking2Frida?category=892887

CVE-2017-8759
https://www.fireeye.com/blog/threat-research/2017/09/zero-day-used-to-distribute-finspy.html

윈도우서버 2012 보안설정
http://archmond.net/?p=6780

IOS 센드박스 관련
http://www.jiniya.net/wp/archives/13532

2017년 7월 3일 월요일

[LOB] 0xff


  • 0xff 인식문제 

Redhat 6.2에서 Bash의 버전이 1.14버전
- 0xff를 인식하지 못하는 버그를 가지고 있기 때문에 문자열의 끝을 알리는 0xff가 0x00과 같은 역할을 함
- bash2: 위의 버그를 픽스한 2.3버전이기 때문에 0xff를 삽입할 수 있다.

1. root/hackerschoolbof
2. :%s/bash/bash2/
vi 데이터로 /etc/passwd을 열어서
: = 커맨드 입력 시작
% = 파일 전체
s/ = 문자열 치환 시작
bash = bash를
/ = 구분선
bash2 = bash로 치환
/ = 끝
3. 재시작



출처: http://ssaemo.tistory.com/2 [뾰족뾰족]

2017년 6월 26일 월요일

사용자 영역, 커널 영역

- 리눅스 i386 32bit 환경에서 사용자 영역을 3G 커널영역을 1G로 나누어 사용함
- include/asm-i386/page.h에 __PAGE_OFFSET이나 PAGE_OFFSET에서 커널공간과 사용자 공간의 경계 값(0xC000 0000)
- 메모리 공간에 접근할 수 았는 권한 부여(일반 사용자의 메모리 접근 제어)
- 메모르 접근 검사는 CPU 자체에서 제공
- 특권 링(privilege ring, privilege level): CPU에서 제공하는 권한
- level 0 : 커널 공간(Core) -> 메모리 영역
- level 1, 2 : 커널 공간(Subsystem) -> 메모리 영역 지정(디바이스, GUI 등)
- level 3 : 사용자 공간
※ 보통은 0, 3만을 사용한다.

GDT(Global Descriptor Table)
- 세그먼트 디스크립터: 운영체제가 부팅하는 과정 동안에 해당 레벨에 사용할 메모리 영역을 지정하는 특별한 자료구조
- DPL 필드(2bit) : 특권 레벨 지정
- Type 필드: 코드영역, 데이터영역, 일기/쓰기, 실행권한 지정
- System Call: 사용자 영역에서 커널 영역에 있는 함수를 호출
- CALL 명령어로 상위레벨에 접근할 수 있게 함
- RET 명령어로 권한을 돌려줌
- JMP 명령어로 다른 레벨 사이로 이동 불가능
DPL 3 --------------CALL------------> DPL 0
        <-------------RET---------------
        <--X--------- JMP---------X-->
- CPL: 현재 실행중인 특권 레벨 저장 레지스터
인터럽트 발생 전(CPL3) ---> 인터럽트 서비스 루틴(CPL0) ---> 인터럽트 처리 후(CPL3)
- RPL: CPL을 조작하여 운영체제를 조작하려 하기 때문에 요청하는 쪽의 권한을 기록하고 추적하기 위한 용도
* 64bit IA64 CALL -> SYSCALL, RET -> SYSRET

[출처] IT EXPERT 리눅스 커널 프로그래밍(도서)


2017년 6월 25일 일요일

[C] 파일 입출력 - 특정 문자 발견 시 처리 루틴

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    FILE *pFile = NULL;
    FILE *pNewFile = NULL;

    pFile = fopen(argv[1], "rb" );
    if( pFile != NULL )
    {
        char szNewFile[255]="new_";
        char szTmp=0;
        strcat(szNewFile,argv[1]);
        pNewFile = fopen("new_web5prob.txt","wb");

        if(pNewFile == NULL){
                printf("2. is not file..!");
        }
        else
       {
             while( !feof( pFile ) )
            {
                szTmp = fgetc(pFile);
                putc((char)szTmp, pNewFile);
                if(szTmp == ';')    //특정 문자
                    fputs("\n", pNewFile);
             }
             fclose( pFile );
        }
    }
    else{
        printf("1. is not file..!");
    }

    return 0;
}


GDB

  • C언어 디버깅
- 컴파일: gcc -g test.c -o test
             -fno-stack-protector: carnary
- 명령어
    next (n) 라인 : 지정해 준 라인만큼 실행하고 라인 지정 하지 않을 시 한 줄 실행
    step (s) 라인 : 지정해 준 라인만큼 실행하고 함수가 있을 시 함수 안으로 진입
    p 변수명 : 지정해준 변수의 현재 값 확인
    set 변수명 = 값 : 지정해 준 값을 변수에 대입
    display 변수명 : 지정해 준 변수명의 상태를 항상 출력
                         display 해준 순서대로 번호를 자동으로 지정 해줌
    undisplay displayNumber : 자동으로 지정된 display 넘버를 지정해주면 명령실행 다음                                          부터 출력해주지 않음
    until (u) : 현재 루프를 빠져나감
    d : 모든 breakpoint 삭제 
    cl 번호 : 번호에 해당하는 breakpoint 삭제
    list (l) : 소스 출력

- perl 인자값 주기
(gdb) run $(perl -e 'print "A"x9, "\x08\x04\x83\xf4"')


2017년 6월 24일 토요일

[VMWare] - Ubuntu 로그인 후 검정화면 해결방법

1) 로그인 화면에서 ctrl + alt + f1 키

2) 로그인 후 xserver-xorg 제거
- sudo apt-get remove --purge xserver-xorg

3) 제거가 완료되면 재부팅
- sudo reboot

4) ctrl + alt + f1 키

5) 로그인 후 xserver-xorg를 다시 설치
- sudo apt-get install xserver-xorg

6) xorg 설정을 다시한다.
- sudo dpkg-reconfigure xserver-xorg

7) 재부팅
- sudo reboot

2017년 6월 21일 수요일

[Ubuntu] FTP ROOT계정 사용


  • vsftpd

- /etc/vsftpd/vsftpd.conf
write_enable=YES
local_enable=YES

- /etc/ftpusers
#root

2017년 6월 20일 화요일

[VirtualBox] 네트워크 설정

  • 네트워크 설정
1. NAT
- 가상머신 내부 네트워크 -> host PC 외부 네트워크 단방향 통신 가능
- Host PC 내의 가상 머신 간의 통신 불가능
- 실제 외부로 나갈때는 host PC가 가진 주소를 갖고 송신한다.
- host PC외부 네트워크에서는 내부 가상머신에 접근 불가능하다.

2.NAT Network
- 가상머신 내부 네트워크 -> Host PC 외부 네트워크 단방향 통신 가능
- Host PC 내의 가상 머신 간의 통신 가능

3. 브릿지 어댑터
- host PC와 동등한 수준의 네트워크 구성
- 추가의 IP할당이 필요함
- Host PC가 192.168.0.10이면 가산머신도 192.168.0.x
- host PC의 이더넷 카드로 virtualbox의 net filter로 host와 guest를 구분한다.

4. 내부 네트워크 
- host PC와 독립적인 내부 네트워크
- 같은 host PC 내의 가상 머신 간 연결이 가능
- host PC와 분리되어 있고 가상머신 간에만 통신이 가능

5. 호스트 전용 어뎁터
- host PC를 포함한 내부 네트워크(외부 네트워크와는 단절)
- 같은 host PC 내의 가상 머신 간 연결이 가능

[참고] http://solatech.tistory.com/263



  •  에러

1. The VM session was closed before any attempt to power it on.
- 저장된 파일 가서 name.vbox-prev 파일을 prev 삭제
- VirtualBox 실행 > 새로만들기 > 기존 생성된 이미지 내 .vdi 선택

[참고] https://www.youtube.com/watch?v=wvI_zWJ7eY0





webhacking.kr


  • 18

no=1%0aor%0a1%3d1%0alimit%0a1%2c1


  • 38

180.70.97.12:admin


  • 42 - zip crack

- url?dawn=test.txt(base64) -> test.zip
- fcrackzip를 사용하여 zip파일 크랙
   * apt-get install fcrackzip
   * fcrackzip -u -c 1 -l 1-8 test.zip


  • 47 - mail header injection
- 문제
------------------------------------------------------------------------------<?if($_POST[email])
{
$pass="????";$header="From: $_POST[email]\r\n";mail("admin@webhacking.kr","readme","password is $pass",$header);
echo(
"<script>alert('Done');</script><meta http-equiv=refresh content=1>");
}
?>-----------------------------------------------------------------------------
- bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )  //이메일을 보내는 함수
   - to: 메일 수신자
   - subject: 보내는 이메일 제목
   - message: 보낼 메시지
   - additional_parameters: 이메일 헤더 마지막에 추가될 문자열
      * From, Cc, Bcc (CRLF[\r\n]로 구분된다.)
- 정답: sangoochoi@gmail.com%0d%0acc: sangoochoi@gmail.com
==========================================================