UML
Posted by gavinkwoe
1.建模
1.1 为什么要建模
建立大厦和建立狗窝的区别是建设狗窝不需要设计。要生产合格的软件就要有一套关于体系结构、过程和工具的规范。
建模的定义:建模是对现实的简化。
建模的目标:
1)模型帮助我们按照实际情况或按照我们所需要的样式对系统进行可视化。
2)模型允许我们详细说明系统的结构和行为。
3)模型给出一个知道我们构造系统的模板。
4)模型对我们的决策进行文档化。
建模就是把复杂的系统变成小的系统,采用“各个击破”的原则逐一解决。
1.2 建模原理
1)选择创建什么模型很重要,模型要反映你难于处理的开发问题。
2)模型要在不同的精度级别上来表示。你可以根据观察的角色和观察的原因来选择精度。
3)建造模型要和现实相连。
4)重要的系统需要用一组独立的模型去处理。在面向对象的软件体系中,为了理解系统的体系结构,你需要几个互补和连锁的视图:用例图、设计视图、进程视图、实现视图和实施视图。
1.3 面向对象的建模
面向算法的建模在需求发生变化或者系统增长后就变得难以维护。
面向对象的建模把对象和类作为其主要构造块。例如,在三层结构中,我们可以在用户接口层、中间层和数据库层中找到你想要的对象。
2 UML介绍
2.1 概述
UML可以对软件密集型系统的制品进行可视化、详述、构造和文档化。最好把它用于以用况(用例)为驱动、以体系结构为中心、跌代及增量的过程中。
UML是一种语言,它是一种可视化的语言,它是一组图形符号。它可用于详细描述。它又是一种构造语言,可以直接生成代码。用Rational XDE就可以实现从UML到C#,或者从C#到UML的双向工程。
2.2 UML的概念模型
学习建模的三个要素:UML的基本构造块、这些构造块放在一起的规则、一些运用于整个UML的公共机制。
UML中由一些四种事物
1)结构事物 --- 类、接口、协作(它是一个交互,它是由一组共同工作以提供某协作行为的角色和其它元素构成的一个群体。)、用例、主动类(至少拥有一个进程或者线程,其元素的行为可以和其它元素的行为并发)、构件(如COM+和Java Bean)、节点。
2)行为事物 --- 交互、状态机(描述了一个对象或者一个交互在生命期内响应事件所经历的状态序列)。
3)分组事物 --- 包
4)注释事物 --- 注解
UML中的四种关系
1)依赖 --- 两个事物间的语义关系
2)关联 --- 是一种结构关系,如聚合
3)泛化 --- 一般/特殊关系
4)实现 --- 用在两种地方:接口和实现他们之间的类和构件之间;用例和实现他们的协作之间。
UML中的图
1)类图 --- 系统的静态状态图,包含主动类的类图给除系统的静态进程视图。
2)对象图
3)用例图
4)顺序图
5)协作图
6)状态图
7)活动图 --- 强调对象间的控制流程
8)构件图
9)实施图
2.3 体系结构
我们用5个互联的视图来描述软件密集型系统的体系结构:
1)系统的用例图
2)系统的设计视图 --- 静态方面由类图和对象图描述,动态方面由交互图、状态图和活动图描述。
3)系统的进程视图 --- 包含了形成系统并发和同步机制的线程和进程。
4)系统的实现视图 --- 主要针对系统发布的配置管理。
5)系统的实施视图
2.4 软件开发生命周期
用况驱动
以体系结构为中心
跌代过程 --- 涉及到一连串可执行发布的管理。
软件开发生命周期的四个阶段:
初始
细化
构造
移交
3 Hello World
4 类
4.3.1 对系统的词汇建模
需要做如下工作:
1)识别用户用于描述问题或解决问题的事物。
2)对于每个抽象,识别一个职责集。
3)提供为实现每个类的职责所需的属性和操作。
4.3.2 对系统中职责的分布建模
抽象出来的类要适中,不要过大过小。
需要如下工作:
1) 识别一组为了完成某些行为而紧密协同工作的类。
2) 对上面的每一个类识别出一组职责。
3) 从整体上观察这些类,过大的分解,过小的合并。
4) 考虑相映的协作方式,重新分配职责。
5 关系
面向对象建模中三种最重要的关系:
依赖 --- 使用关系
泛化 --- 一般/特殊关系
关联 --- 结构关系
当你开始建模是,特别是解决这些对象的动态协作时,你还会遇到两种其它的关系:链(可能发送消息的对象间的实例)和转换(状态机中不同状态的连接)
对简单依赖建模 ---(如一个类作为另一个类的参数) 依赖从操作的类指向当作参数的类。
对单继承建模
对结构关系建模
6 公共机制
四个公共机制可以使UML简化:详述、修饰、公共划分和扩展
构造型、标记值和约束使UML提供的用以增加新的构造块、创建新的特性以及描述新的语义的机制。
7 图
有5种最重要的互补视图:用例视图、设计视图、进程视图、实现视图和实施视图
每一种视图包含结构建模(静态)和行为建模(动态)
建图的两种方法:正向工程和逆向工程
一些术语:
系统:由子系统组成; 子系统:由元素组成; 模型:对现实的简化; 视图:对系统模型的组织和结构的投影,注重于系统的一个方面。
结构图:类图、对象图、构件图、实施图。
行为图: 用况图、顺序图、协作图、状态图、活动图。
顺序图和协作图统称交互图。顺序图强调消息的时间次序,协作图强调收发消息的对象的结构组织。
活动图强调对象之间的控制流。
如何选择视图来建模?
1)视图能够表达系统的体系结构,能够暴露项目的技术风险。
2)决定用哪些制品来捕获视图的基本细节。
3)作为你的过程策略的一部分,决定把那种视图至于某种形式或者半形式的控制之下。
4)保留废弃的视图。
两种系统建模的方法:
1)针对同一模型,用不同层次上的细节描述图。
2)在不同的抽象层次上,从一个模型跟踪到另一个模型的方法建模。
8 类图
类图包括如下内容:
类
接口
协作
依赖、泛化和关联关系。
对系统的静态设计视图建模时使用类图的3种方式:
1)对系统的词汇建模
2)对简单协作建模 --- 协作提供的一些合作行为强于其所有元素行为之和。
3)对逻辑数据库模式建模
9 高级类
在UML中更一般的构造块是类元,类元包括:类、接口、数据类型、信号、构件、节点、用况和子系统。他是描述结构特性和行为特性的机制。
转自:http://blog.csdn.net/binjuny/archive/2007/07/05/1679193.aspx
PHP6 features
Posted by gavinkwoe
去年在巴黎举行的PHP开发者大会中,PHP6开发的消息开始流传开来,于PHP大会讨论的PHP6,将有很大幅度的变化,但这只是草案阶段,并不代表所有会议的机率都会随着PHP6的发布而包含记录中所有的变更也就是说,在发布PHP6之前,还是会有异动的情形,但是可以确定的是下面所列的数项变化,将会随着PHP6一同面世(当然不是百分百乐,)赶快来看看这些新特性吧
1.支持Unicode
支持Unicode是有其必然,虽然Unicode占用较多的空间,但Unicode带来的便利性,远超过占用空间的缺点,尤其在国际化的今天,硬件设备越来越强大,网速也大幅度的提升,这么一点小小的缺点是可以忽略的。另外一点,PHP也可以在.ini文件中设定是否开启支持Unicode,决定权在你自己,这是一个不错的点子,关掉Unicode的支持,PHP的性能并不会有大幅度的提升,主要的影响在于需要引用字符串的函数。
2.Register Globals 将被移除
这是一个重要的决定,说多新进的PHP开发者会觉得Register Globals满方便的,但是却忽略了Register Globals会带来程序上安全性的隐患,大多数的主机上此项功能是关闭的,印象中从PHP4.3.x版开始时,此项默认设置值即是关闭状态,PHP6正式移除Register Globals也代表着如果程序是由PHP3时代的产物,将完全无法使用,除了改写一途外,别无他法。相信现在的PHP世界里,仍使用PHP3时代所产生的程序应该是少之又少。
3.Magic Quotes 将消失
Magic Quotes主要是自动转义需要转义的字符,此项功能移除叶符合大多数PHP开发者的心声。
4.Safe Mode 取消
老实说,这个模式不知道哪里不好,取消就取消吧,反正也用不到
5.’var’ 别名为 ‘public’
在类中的var声明变成public的别名,相信是为了兼容PHP5而作的决定,PHP6现在也可以称作为OO语言了。
6.通过引用返回将出错
现在透过引用返回编译器将会报错 例如$a =& new b()、function &c(),OO语言默认就是引用,所以不需要再使用&了。
7.zend.ze1 compatbility mode 将被移去
Zend.ze1相容模式将被移去,PHP5是为兼容旧有PHP4,所以在.ini中可选择是否开启相容模式,原因在于PHP5使用的是第二代解析引擎,但是相容模式并不是百分之百能解析PHP4语法,所以旧时代的产物,移除。
8.Freetype 1 and GD 1 support 将不见
这两个是很久的Libs,所以不再支持,GD1早已被现在的GD2取代了。
9.dl() 被移到 SAPI 中
dl()主要是让设计师加载extension Libs,现在被移到 SAPI 中
10.Register Long Array 去除
从PHP5起默认是关闭,再PHP6中正式移除。
11.一些Extension的变更
例如 XMLReader 和 XMLWriter 将不再是以Extension的方式出现,他们将被移入到PHP的核心之中,并且默认是开启,ereg extension将被放入PECL,代表着它将被移出PHP核心,这也是为了让路给新的正则表达式extension,此外,Fileinfo extension 也将被导入PHP的核心之中。
12.APC将被导入核心
这是一个提高PHP性能的功能,现在它将被放入PHP核心中,并且可以选择是否启用APC
13.告别ASP风格的起始标签
原来是为了取悦ASP开发者转向使用PHP,现今已经不再需要这种做法了,
最后,别期望PHP6的性能可以全面超过PHP5,有可能的是PHP6的执行效率会比PHP5还要来的慢的,但是可以预期的是,PHP开发小组将会努力的完善PHP5,超越PHP5。
那么,对PHP6有兴趣的朋友现在可以到PHP官方网站上下载,试试这些功能是否真的已经
在PHP6中体现出来了,下载地址http://snaps.php.net/
[收藏] Asian NTP Server pool
Posted by dengwei
Philippines — ph.pool.ntp.org (1)
Malaysia — my.pool.ntp.org (4)
Turkey — tr.pool.ntp.org (1)
Singapore — sg.pool.ntp.org (2)
India — in.pool.ntp.org (1)
Hong Kong — hk.pool.ntp.org (1)
United Arab Emirates — ae.pool.ntp.org (0)
Japan — jp.pool.ntp.org (6)
Bangladesh — bd.pool.ntp.org (0)
Israel — il.pool.ntp.org (3)
Korea — kr.pool.ntp.org (4)
Thailand — th.pool.ntp.org (1)
Iran — ir.pool.ntp.org (0)
Taiwan — tw.pool.ntp.org (15)
China — cn.pool.ntp.org (6)
Indonesia — id.pool.ntp.org (3)
[超长篇] Inject Your Code to a Portable Executable File
Posted by dengwei
转至: http://www.codeguru.com/cpp/w-p/system/misc/article.php/c11393
Downloads
Windows NT 3.51 (I mean, Win3.1, Win95, Win98 were not perfect OSs). The MS-DOS data causes that your executable file to have the performance inside MS-DOS and the MS-DOS Stub program lets it display: "This program can not be run in MS-DOS mode" or "This program can be run only in Windows mode", or some things like these comments when you try to run a Windows EXE file inside MS-DOS 6.0, where there is no footstep of Windows. Thus, this data is reserved for the code to indicate these comments in the MS-DOS operating system. The most interesting part of the MS-DOS data is "MZ"! Can you believe, it refers to the name of "Mark Zbikowski", one of the first Microsoft programmers?
0 Preface
You might demand to comprehend the ways a virus program injects its procedure into the interior of a portable executable file and corrupts it, or you are interested in implementing a packer or a protector to encrypt the data of your portable executable (PE) file. This article is committed to represent a brief discussion to realize the performance that is accomplished by EXE tools or some kinds of mal-ware.
You can employ this article’s source code to create your custom EXE builder. It could be used to make an EXE protector in the right way, or with the wrong intention, to spread a virus. However, my purpose of writing this article has been the first application, so I will not be responsible for the immoral usage of these methods.
1 Prerequisites
There are no specific mandatory prerequisites to follow the topics in this article. If you are familiar with a debugger and also the portable file format, I suggest you to drop to Sections 2 and 3; the whole of these sections has been made for people who don’t have any knowledge regarding the EXE file format or debuggers.
2 Portable Executable File Format
The Portable Executable file format was defined to provide the best way for the Windows Operating System to execute code and also to store the essential data that is needed to run a program—for example constant data, variable data, import library links, and resource data. It consists of MS-DOS file information, Windows NT file information, Section Headers, and Section images, as shown in Table 1.
2.1 The MS-DOS data
These data let you remember the first days of developing the Windows Operating System. You were at the beginning of a way to achieve a complete Operating System such as
To me, only the offset of the PE signature in the MS-DOS data is important, so I can use it to find the position of the Windows NT data. I just recommend that you take a look at Table 1, and then observe the structure of IMAGE_DOS_HEADER in the <winnt.h> header in the <Microsoft Visual Studio .net path>\VC7\PlatformSDK\include\ folder or the <Microsoft Visual Studio 6.0 path>\VC98\include\ folder. I do not know why the Microsoft team has forgotten to provide some comment about this structure in the MSDN library!
typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header "MZ" WORD e_magic; // Magic number WORD e_cblp; // Bytes on last page of file WORD e_cp; // Pages in file WORD e_crlc; // Relocations WORD e_cparhdr; // Size of header in // paragraphs WORD e_minalloc; // Minimum extra paragraphs // needed WORD e_maxalloc; // Maximum extra paragraphs // needed WORD e_ss; // Initial (relative) SS // value WORD e_sp; // Initial SP value WORD e_csum; // Checksum WORD e_ip; // Initial IP value WORD e_cs; // Initial (relative) CS // value WORD e_lfarlc; // File address of relocation // table WORD e_ovno; // Overlay number WORD e_res[4]; // Reserved words WORD e_oemid; // OEM identifier // (for e_oeminfo) WORD e_oeminfo; // OEM information; // e_oemid specific WORD e_res2[10]; // Reserved words LONG e_lfanew; // File address of the new // exe header } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
e_lfanew is the offset that refers to the position of the Windows NT data. I have provided a program to obtain the header information from an EXE file and to display it to you. To use the program, just try:
PE Viewer
This sample is useful for the whole of this article.
Table 1: Portable Executable file format structure
| MS-DOS information |
IMAGE_DOS_ HEADER |
DOS EXE Signature |
00000000 ASCII "MZ"00000002 DW 009000000004 DW 000300000006 DW 000000000008 DW 00040000000A DW 00000000000C DW FFFF0000000E DW 000000000010 DW 00B800000012 DW 000000000014 DW 000000000016 DW 000000000018 DW 00400000001A DW 00000000001C DB 00b&b&0000003B DB 000000003C DD 000000F0
|
| DOS_PartPag | |||
| DOS_PageCnt | |||
| DOS_ReloCnt | |||
| DOS_HdrSize | |||
| DOS_MinMem | |||
| DOS_MaxMem | |||
| DOS_ReloSS | |||
| DOS_ExeSP | |||
| DOS_ChkSum | |||
| DOS_ExeIPP | |||
| DOS_ReloCS | |||
| DOS_TablOff | |||
| DOS_Overlay | |||
| b& Reserved words b& |
|||
| Offset to PE signature | |||
| MS-DOS Stub Program |
00000040 ..B:..B4.C!B8\LC!This program canno00000060 t be run in DOS mode....$.......
|
||
| Windows NT information IMAGE_ |
Signature | PE signature (PE) |
000000F0 ASCII "PE"
|
| IMAGE_ FILE_HEADER |
Machine |
000000F4 DW 014C000000F6 DW 0003000000F8 DD 3B7D8410000000FC DD 0000000000000100 DD 0000000000000104 DW 00E000000106 DW 010F
|
|
| NumberOfSections | |||
| TimeDateStamp | |||
| PointerToSymbolTable | |||
| NumberOfSymbols | |||
| SizeOfOptionalHeader | |||
| Characteristics | |||
| IMAGE_ OPTIONAL_ HEADER32 |
MagicNumber |
00000108 DW 010B0000010A DB 070000010B DB 000000010C DD 0001280000000110 DD 00009C0000000114 DD 0000000000000118 DD 000124750000011C DD 0000100000000120 DD 0001400000000124 DD 0100000000000128 DD 000010000000012C DD 0000020000000130 DW 000500000132 DW 000100000134 DW 000500000136 DW 000100000138 DW 00040000013A DW 00000000013C DD 0000000000000140 DD 0001F00000000144 DD 0000040000000148 DD 0001D7FC0000014C DW 00020000014E DW 800000000150 DD 0004000000000154 DD 0000100000000158 DD 001000000000015C DD 0000100000000160 DD 0000000000000164 DD 00000010
|
|
| MajorLinkerVersion | |||
| MinorLinkerVersion | |||
| SizeOfCode | |||
| SizeOfInitializedData | |||
| SizeOfUninitializedData | |||
| AddressOfEntryPoint | |||
| BaseOfCode | |||
| BaseOfData | |||
| ImageBase | |||
| SectionAlignment | |||
| FileAlignment | |||
| MajorOSVersion | |||
| MinorOSVersion | |||
| MajorImageVersion | |||
| MinorImageVersion | |||
| MajorSubsystemVersion | |||
| MinorSubsystemVersion | |||
| Reserved | |||
| SizeOfImage | |||
| SizeOfHeaders | |||
| CheckSum | |||
| Subsystem | |||
| DLLCharacteristics | |||
| SizeOfStackReserve | |||
| SizeOfStackCommit | |||
| SizeOfHeapReserve | |||
| SizeOfHeapCommit | |||
| LoaderFlags | |||
| NumberOfRvaAndSizes | |||
| IMAGE_ DATA_DIRECTORY[16] |
Export Table | ||
| Import Table | |||
| Resource Table | |||
| Exception Table | |||
| Certificate File | |||
| Relocation Table | |||
| Debug Data | |||
| Architecture Data | |||
| Global Ptr | |||
| TLS Table | |||
| Load Config Table | |||
| Bound Import Table | |||
| Import Address Table | |||
| Delay Import Descriptor | |||
| COM+ Runtime Header | |||
| Reserved | |||
| Sections information |
IMAGE_ SECTION_ HEADER[0] |
Name[8] |
000001E8 ASCII".text"000001F0 DD 000126B0000001F4 DD 00001000000001F8 DD 00012800000001FC DD 0000040000000200 DD 0000000000000204 DD 0000000000000208 DW 00000000020A DW 00000000020C DD 60000020 CODE|EXECUTE|READ
|
| VirtualSize | |||
| VirtualAddress | |||
| SizeOfRawData | |||
| PointerToRawData | |||
| PointerToRelocations | |||
| PointerToLineNumbers | |||
| NumberOfRelocations | |||
| NumberOfLineNumbers | |||
| Characteristics | |||
| b& b& b& IMAGE_ SECTION_ HEADER[n] |
00000210 ASCII".data"; SECTION00000218 DD 0000101C ; VirtualSize = 0x101C0000021C DD 00014000 ; VirtualAddress = 0x1400000000220 DD 00000A00 ; SizeOfRawData = 0xA0000000224 DD 00012C00 ; PointerToRawData = 0x12C0000000228 DD 00000000 ; PointerToRelocations = 0x00000022C DD 00000000 ; PointerToLineNumbers = 0x000000230 DW 0000 ; NumberOfRelocations = 0x000000232 DW 0000 ; NumberOfLineNumbers = 0x000000234 DD C0000040 ; Characteristics = INITIALIZED_DATA|READ|WRITE00000238 ASCII".rsrc"; SECTION00000240 DD 00008960 ; VirtualSize = 0x896000000244 DD 00016000 ; VirtualAddress = 0x1600000000248 DD 00008A00 ; SizeOfRawData = 0x8A000000024C DD 00013600 ; PointerToRawData = 0x1360000000250 DD 00000000 ; PointerToRelocations = 0x000000254 DD 00000000 ; PointerToLineNumbers = 0x000000258 DW 0000 ; NumberOfRelocations = 0x00000025A DW 0000 ; NumberOfLineNumbers = 0x00000025C DD 40000040 ; Characteristics = INITIALIZED_DATA|READ
|
||
| SECTION[0] |
00000400 EA 22 DD 77 D7 23 DD 77 C*"C.wC.#C.w00000408 9A 18 DD 77 00 00 00 00 E!.C.w....00000410 2E 1E C7 77 83 1D C7 77 ..C.wF..C.w00000418 FF 1E C7 77 00 00 00 00 C?.C.w....00000420 93 9F E7 77 D8 05 E8 77 b.E8C'wC..C(w00000428 FD A5 E7 77 AD A9 E9 77 C=B%C'w­B)C)w00000430 A3 36 E7 77 03 38 E7 77 B#6C'w.8C'w00000438 41 E3 E6 77 60 8D E7 77 AC#C&w`BC'w00000440 E6 1B E6 77 2B 2A E7 77 C&.C&w+*C'w00000448 7A 17 E6 77 79 C8 E6 77 z.C&wyC.C&w00000450 14 1B E7 77 C1 30 E7 77 ..C'wC.0C'wb&
|
||
| b& b& b& SECTION[n] |
b&0001BF00 63 00 2E 00 63 00 68 00 c...c.h.0001BF08 6D 00 0A 00 43 00 61 00 m...C.a.0001BF10 6C 00 63 00 75 00 6C 00 l.c.u.l.0001BF18 61 00 74 00 6F 00 72 00 a.t.o.r.0001BF20 11 00 4E 00 6F 00 74 00 ..N.o.t.0001BF28 20 00 45 00 6E 00 6F 00 .E.n.o.0001BF30 75 00 67 00 68 00 20 00 u.g.h. .0001BF38 4D 00 65 00 6D 00 6F 00 M.e.m.o.0001BF40 72 00 79 00 00 00 00 00 r.y.....0001BF48 00 00 00 00 00 00 00 00 ........0001BF50 00 00 00 00 00 00 00 00 ........0001BF58 00 00 00 00 00 00 00 00 ........0001BF60 00 00 00 00 00 00 00 00 ........0001BF68 00 00 00 00 00 00 00 00 ........0001BF70 00 00 00 00 00 00 00 00 ........0001BF78 00 00 00 00 00 00 00 00 ........
|
||
2.2 The Windows NT data
As mentioned in the preceding section, e_lfanew storage in the MS-DOS data structure refers to the location of the Windows NT information. Hence, if you assume that the pMem pointer relates the start point of the memory space for a selected portable executable file, you can retrieve the MS-DOS header and also the Windows NT headers by the following lines, which you also can perceive in the PE viewer sample (pelib.cpp, PEStructure::OpenFileName()):
IMAGE_DOS_HEADER image_dos_header;IMAGE_NT_HEADERS image_nt_headers;PCHAR pMem;b&memcpy(&image_dos_header, pMem, sizeof(IMAGE_DOS_HEADER));memcpy(&image_nt_headers, pMem+image_dos_header.e_lfanew, sizeof(IMAGE_NT_HEADERS));
IMAGE_NT_HEADERS structure definition. It makes it possible to grasp what the image NT header maintains to execute a code inside the Windows NT OS. Now, you are conversant with the Windows NT structure; it consists of the "PE" Signature, the File Header, and the Optional Header. Do not forget to take a glimpse at their comments in the MSDN Library and in Table 1.
It seems to be very simple, the retrieval of the headers information. I recommend inspecting the MSDN library regarding the
One the whole, I consider merely, in most circumstances, the following cells of the IMAGE_NT_HEADERS structure:
FileHeader->NumberOfSectionsOptionalHeader->AddressOfEntryPointOptionalHeader->ImageBaseOptionalHeader->SectionAlignmentOptionalHeader->FileAlignmentOptionalHeader->SizeOfImageOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] ->VirtualAddressOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] ->Size
You can observe the main purpose of these values clearly, and their role when the internal virtual memory space allocated for an EXE file by the Windows task manager if you pay attention to their explanations in MSDN library, so I am not going to repeat the MSDN annotations here.
I should make a brief comment regarding the PE data directories, or OptionalHeader-> DataDirectory[], because I think there are a few aspects of interest concerning them. When you come to survey the Optional header through the Windows NT information, you will find that there are 16 directories at the end of the Optional Header, where you can find the consecutive directories, including their Relative Virtual Address and Size. I just mention here the notes from <winnt.h> to clarify these information:
// Export Directory#define IMAGE_DIRECTORY_ENTRY_EXPORT 0// Import Directory#define IMAGE_DIRECTORY_ENTRY_IMPORT 1// Resource Directory#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2// Exception Directory#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3// Security Directory#define IMAGE_DIRECTORY_ENTRY_SECURITY 4// Base Relocation Table#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5// Debug Directory#define IMAGE_DIRECTORY_ENTRY_DEBUG 6// Architecture Specific Data#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7// RVA of GP#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8// TLS Directory#define IMAGE_DIRECTORY_ENTRY_TLS 9// Load Configuration Directory#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10// Bound Import Directory in headers#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11// Import Address Table#define IMAGE_DIRECTORY_ENTRY_IAT 12// Delay Load Import Descriptors#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13// COM Runtime descriptor#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14
The last one (15) was reserved for use in the future; I have not yet seen any purpose for it, even in PE64.
For instance, if you want to perceive the relative virtual address (RVA) and the size of the resource data, it is enough to retrieve them by:
DWORD dwRVA = image_nt_headers.OptionalHeader-> DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE]->VirtualAddress;DWORD dwSize = image_nt_headers.OptionalHeader-> DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE]->Size;
To comprehend more regarding the significance of data directories, I forward you to Section 3.4.3 of the Microsoft Portable Executable and the Common Object File Format Specification document by Microsoft, and furthermore Section 6 of this document, where you discern the various types of sections and their applications. You will see the section’s advantage subsequently.
2.3 The Section Headers and Sections
You currently observe how the portable executable files declare the location and the size of a section on a disk storage file and inside the virtual memory space allocated for the program with IMAGE_NT_HEADERS-> OptionalHeader->SizeOfImage by the Windows task manager, as well the characteristics to demonstrate the type of the section. To better understand the Section header as my previous declaration, I suggest having a brief look at the IMAGE_SECTION_HEADER structure definition in the MSDN library. For an EXE packer developer, VirtualSize, VirtualAddress, SizeOfRawData, PointerToRawData, and Characteristics cells have significant rules. When developing an EXE packer, you should be clever enough to play with them. There are somet hings to note when you modify them; you should take care to align the VirtualSize and VirtualAddress according to OptionalHeader->SectionAlignment, as well as SizeOfRawData and PointerToRawData in line with OptionalHeader->FileAlignment. Otherwise, you will corrupt your target EXE file and it will never run. Regarding Characteristics, I pay attention mostly to establish a section by IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_INITIALIZED_DATA, I prefer that my new section has the ability to initialize such data during the running process, such as import table; besides, I need it to be able to modify itself by the loader with my settings in the section characteristics to read- and writeable.
Moreover, you should pay attention to the section names; you can know the purpose of each section by its name. I will just forward you to Section 6 of the Microsoft Portable Executable and the Common Object File Format Specification documents. I believe it represents the totality of sections by their names; this is also included in Table 2.
Table 2: Section names
| ".text" | Code Section |
| "CODE" | Code Section of file linked by Borland Delphi or Borland Pascal |
| ".data" | Data Section |
| "DATA" | Data Section of file linked by Borland Delphi or Borland Pascal |
| ".rdata" | Section for Constant Data |
| ".idata" | Import Table |
| ".edata" | Export Table |
| ".tls" | TLS Table |
| ".reloc" | Relocation Information |
| ".rsrc" | Resource Information |
To comprehend the section headers and also the sections, you can run the sample PE viewer. With this PE viewer, you can realize only the application of the section headers in a file image, so to observe the main significance in the Virtual Memory, you should try to load a PE file by a debugger. The next section represents the main idea of using the virtual address and size in the virtual memory by using a debugger. The last note is about IMAGE_NT_HEADERS-> FileHeader->NumberOfSections, that provides a number of sections in a PE file. Do not forget to adjust it whenever you remove or add some sections to a PE file. I am talking about section injection!
3 Debugger, Disassembler and some Useful Tools
In this part, you will become familiar with the necessary and essential equipment to develop your PE tools.
3.1 Debuggers
The first essential prerequisite to become a PE tools developer is to have enough experience with bug tracer tools. Furthermore, you should know most of the assembly instructions. To me, the Intel documents are the best references. You can obtain them from the Intel site for IA-32, and on top of that IA-64; the future belongs to IA-64 CPUs, Windows XP 64-bit, and also PE64!
- IA-32 Intel Architecture Software Developer’s Manuals
- Intel Itanium Architecture Assembly Language Reference Guide
- The Intel Itanium Processor Developer Resource Guide
To trace a PE file, SoftICE by Compuware Corporation, I knew it also as named NuMega when I was at high school, is the best debugger in the world. It implements process tracing by using the kernel mode method debugging without applying Windows debugging application programming interface (API) functions. In addition, I will introduce one perfect debugger in user mode level. It utilizes the Windows debugging API to trace a PE file and also attaches itself to an active process. These API functions have been provided by Microsoft teams, inside the Windows Kernel32 library, to trace a specific process, by using Microsoft tools, or perhaps, to make your own debugger! Some of those API functions inlude:
- CreateThread()
- CreateProcess()
- OpenProcess()
- DebugActiveProcess()
- GetThreadContext()
- SetThreadContext()
- ContinueDebugEvent()
- DebugBreak()
- ReadProcessMemory()
- WriteProcessMemory()
- SuspendThread()
- ResumeThread()
3.1.1 SoftICE
It was in 1987; Frank Grossman and Jim Moskun decided to establish a company called NuMega Technologies in Nashua, NH, to develop some equipment to trace and test the reliability of Microsoft Windows software programs. Now, it is a part of Compuware Corporation and its product has participated to accelerate the reliability in Windows software, and additionally in Windows driver developments. Currently, everyone knows the Compuware DriverStudio that is used to establish an environment for implementing the elaboration of a kernel driver or a system file by aiding the Windows Driver Development Kit (DDK). It bypasses the involvement of DDK to implement a portable executable file of kernel level for a Windows system software developer. For us, only one instrument of DriverStudio is important, SoftICE; this debugger can be used to trace every portable executable file, a PE file for user mode level or a PE file for kernel mode level.
Figure 1: SoftICE Window
| EAX=00000000EBX=7FFDD000 ECX=0007FFB0 EDX=7C90EB94 ESI=FFFFFFFF EDI=7C919738 EBP=0007FFF0 ESP=0007FFC4 EIP=010119E0 o d i s z a p c CS=0008 DS=0023 SS=0010 ES=0023 FS=0030 GS=0000 SS:0007FFC4=87C816D4F |
| 0023:01013000 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ……………. 0023:01013010 01 00 00 00 20 00 00 00-0A 00 00 00 0A 00 00 00 ……………. 0023:01013020 20 00 00 00 00 00 00 00-53 63 69 43 61 6C 63 00 ……..SciCalc. 0023:01013030 00 00 00 00 00 00 00 00-62 61 63 6B 67 72 6F 75 ……..backgrou 0023:01013040 6E 64 00 00 00 00 00 00-2E 00 00 00 00 00 00 00 nd………….. |
| 0010:0007FFC4 4F 6D 81 7C 38 07 91 7C-FF FF FF FF 00 90 FD 7F Om |8 b.| . 0010:0007FFD4 ED A6 54 80 C8 FF 07 00-E8 B4 F5 81 FF FF FF FF T . 0010:0007FFE4 F3 99 83 7C 58 6D 81 7C-00 00 00 00 00 00 00 00 Xm |…….. 0010:0007FFF4 00 00 00 00 E0 19 01 01-00 00 00 00 00 00 00 00 …. …. |
| 010119E0 PUSH EBP 010119E1 MOV EBP,ESP 010119E3 PUSH -1 010119E5 PUSH 01001570 010119EA PUSH 01011D60 010119EF MOV EAX,DWORD PTR FS:[0] 010119F5 PUSH EAX 010119F6 MOV DWORD PTR FS:[0],ESP 010119FD ADD ESP,-68 01011A00 PUSH EBX 01011A01 PUSH ESI 01011A02 PUSH EDI 01011A03 MOV DWORD PTR SS:[EBP-18],ESP 01011A06 MOV DWORD PTR SS:[EBP-4],0 |
| :_
|
3.1.2 OllyDbg
It was about four years ago that I first saw this debugger by chance. For me, it was the best choice; I was not wealthy enough to purchase SoftICE, and at that time, SoftICE only had good functions for DOS, Windows 98, and Windows 2000. I found that this debugger supported all kinds of Windows versions. Therefore, I started to learn it very fast, and now it is my favorite debugger for the Windows OS. It is a debugger that can be used to trace all kinds of portable executable files except a Common Language Infrastructure (CLI) file format in user mode level, by using the Windows debugging API. Oleh Yuschuk, the author, is one of worthiest software developers I have seen in my life. He is a Ukrainian who now lives in Germany. I should mention here that his debugger is the best choice for hacker and cracker parties around the world! It is freeware! You can try it from the OllyDbg Homepage.
Figure 2: OllyDbg CPU Window I have introduced two debuggers without talking about how you can employ them, and also which parts you should pay attention to. Regarding using debuggers, I refer you to their instructions in help documents. However, I want to explain briefly the important parts of a debugger; of course, I am talking about low-level debuggers, or in other words, machine-language debuggers of the x86 CPU families. All of low-level debuggers consist of the following subdivisions: o d t s z a p c You can compare Figures 1 and 2 to distinguish the difference between SoftICE and OllyDbg. When you want to trace a PE file, you should mostly consider these five subdivisions. Furthermore, every debugger comprises of some other useful parts; you should discover them by yourself. You can consider OllyDbg and SoftICE to be excellent disassemblers, but I also want to introduce another disassembler tool that is famous in the reverse engineering world. Proview or PVDasm is an admirable disassembler by the Reverse-Engineering-Community; it is still under development and bug fixing. You can find its disassmbler source engine and employ it to create your own disassembler. W32DASM can disassemble both 16- and 32-bit executable file formats. In addition to its disassembling ability, you can employ it to analyze import, export, and resource data directories data. All reverse-engineering experts know that IDA Pro can be used to investigate, not only x86 instructions, but that of various kinds of CPU types like AVR, PIC, and so forth. It can illustrate the assembly source of a portable executable file by using colored graphics and tables, and is very useful for any newbie in this area. Furthermore, it has the capability to trace an executable file inside the user mode level in the same way as OllyDbg. A good PE tools developer is conversant with the tools that save his time, so I recommend that you select some appropriate instruments to investigate the base information under a portable executable file. LordPE by y0da is still the first choice to retrieve PE file information with the possibility to modify them. PE iDentifier is valuable to identify the type of compilers, packers, and cryptors of PE files. As of now, it can detect more than 500 different signature types of PE files. Resource Hacker can be employed to modify resource directory information; icon, menu, version info, string table, and so on. WinHex, it is clear what you can do with this tool. Eventually, CFF Explorer by Ntoskrnl is what you want to have as a PE Utility tool in your arsenal; it supports PE32/64, PE rebuild included Common Language Infrastructure (CLI) file. In other words, the .NET file, a resource modifier, and much more facilities which can not be found in others. Just try to discover every unimaginable option by hand. You are ready to do the first step of making your project. I have provided a library to add a new section and rebuild the portable executable file. Before starting, I wnat you to get familiar with the headers of a PE file, by using OllyDbg. You should first open a PE file; that pops up a menu, View->Executable file. Again, you get a popup menu: Special->PE header. You will observe a scene similar to Figure 3. Now, come to the Main Menu View->Memory, and try to distinguish the sections inside the Memory map window.
(3.1.3 Which parts are important in a debugger interface?
EAX
ECX
EDX
EBX
ESP
EBP
ESI
EDI
EIP
010119E0 PUSH EBP010119E1 MOV EBP,ESP010119E3 PUSH -1010119E5 PUSH 01001570010119EA PUSH 01011D60010119EF MOV EAX,DWORD PTR FS:[0]010119F5 PUSH EAX010119F6 MOV DWORD PTR FS:[0],ESP010119FD ADD ESP,-6801011A00 PUSH EBX01011A01 PUSH ESI01011A02 PUSH EDI01011A03 MOV DWORD PTR SS:[EBP-18],ESP01011A06 MOV DWORD PTR SS:[EBP-4],0
0023:01013000 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ……………. 0023:01013010 01 00 00 00 20 00 00 00-0A 00 00 00 0A 00 00 00 ……………. 0023:01013020 20 00 00 00 00 00 00 00-53 63 69 43 61 6C 63 00 ……..SciCalc. 0023:01013030 00 00 00 00 00 00 00 00-62 61 63 6B 67 72 6F 75 ……..backgrou 0023:01013040 6E 64 00 00 00 00 00 00-2E 00 00 00 00 00 00 00 nd…………..
0010:0007FFC4 4F 6D 81 7C 38 07 91 7C-FF FF FF FF 00 90 FD 7F Om |8 b.| . 0010:0007FFD4 ED A6 54 80 C8 FF 07 00-E8 B4 F5 81 FF FF FF FF T . 0010:0007FFE4 F3 99 83 7C 58 6D 81 7C-00 00 00 00 00 00 00 00 Xm |…….. 0010:0007FFF4 00 00 00 00 E0 19 01 01-00 00 00 00 00 00 00 00 …. ….
Command
SoftICE
OllyDbg
Run
F5
F9
Step Into
F11
F7
Step Over
F10
F8
Set Break Point
F8
F2
3.2 Disassembler
3.2.1 Proview disassembler
3.2.2 W32Dasm
3.2.3 IDA Pro
3.3 Some Useful Tools
3.3.1 LordPE
3.3.2 PEiD
3.3.3 Resource Hacker
3.3.4 WinHex
3.3.5 CFF Explorer
4 Add a New Section and Change the OEP
Figure 3
00000000000000020000000400000006000000080000000A0000000C0000000E00000010000000120000001400000016000000180000001A0000001C0000001D0000001E0000001F000000200000002100000022000000230000002400000025000000260000002700000028000000290000002A0000002B0000002C0000002D0000002E0000002F000000300000003100000032000000330000003400000035000000360000003700000038000000390000003A0000003B0000003C
|
4D 5A 9000 0300 0000 0400 0000 FFFF 0000 B800 0000 0000 0000 4000 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0000000 |
ASCII "MZ" DW 0090 DW 0003 DW 0000 DW 0004 DW 0000 DW FFFF DW 0000 DW 00B8 DW 0000 DW 0000 DW 0000 DW 0040 DW 0000 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DB 00 DD 000000F0 |
DOS EXE Signature DOS_PartPag = 90 (144.) DOS_PageCnt = 3 DOS_ReloCnt = 0 DOS_HdrSize = 4 DOS_MinMem = 0 DOS_MaxMem = FFFF (65535.) DOS_ReloSS = 0 DOS_ExeSP = B8 DOS_ChkSum = 0 DOS_ExeIP = 0 DOS_ReloCS = 0 DOS_TablOff = 40 DOS_Overlay = 0 Offset to PE signature |
|
Virtual_Address = Image_Base + Relative_Virtual_Address |
DWORD OEP_RVA = image_nt_headers-> OptionalHeader.AddressOfEntryPoint ;// OEP_RVA = 0x00012475DWORD OEP_VA = image_nt_headers-> OptionalHeader.ImageBase + OEP_RVA ;// OEP_VA = 0x01000000 + 0x00012475 = 0x01012475
PE Maker: Step 1
Download pemaker1.zip and test1.zip from the files at the end of this article.
DynLoader(), in loader.cpp, is reserved for the data of the new section—in other words, the Loader.
DynLoader Step 1
__stdcall void DynLoader(){_asm{//---------------------------------- DWORD_TYPE(DYN_LOADER_START_MAGIC)//---------------------------------- MOV EAX,01012475h // << Original OEP JMP EAX//---------------------------------- DWORD_TYPE(DYN_LOADER_END_MAGIC)//----------------------------------}}
Unfortunately, this source can only be applied for the sample test file. You should complete it by saving the value of the original OEP in the new section, and use it to reach the real OEP. I have accomplished it in Step 2 (Section 5).
4.1 Retrieve and Rebuild PE file
I have made a simple class library to recover PE information and to use it in a new PE file.
CPELibrary Class Step 1
//----------------------------------------------------------------class CPELibrary{private: //----------------------------------------- PCHAR pMem; DWORD dwFileSize; //-----------------------------------------protected: //----------------------------------------- PIMAGE_DOS_HEADER image_dos_header; PCHAR pDosStub; DWORD dwDosStubSize, dwDosStubOffset; PIMAGE_NT_HEADERS image_nt_headers; PIMAGE_SECTION_HEADER image_section_header[MAX_SECTION_NUM]; PCHAR image_section[MAX_SECTION_NUM]; //-----------------------------------------protected: //----------------------------------------- DWORD PEAlign(DWORD dwTarNum,DWORD dwAlignTo); void AlignmentSections(); //----------------------------------------- DWORD Offset2RVA(DWORD dwRO); DWORD RVA2Offset(DWORD dwRVA); //----------------------------------------- PIMAGE_SECTION_HEADER ImageRVA2Section(DWORD dwRVA); PIMAGE_SECTION_HEADER ImageOffset2Section(DWORD dwRO); //----------------------------------------- DWORD ImageOffset2SectionNum(DWORD dwRVA); PIMAGE_SECTION_HEADER AddNewSection(char* szName,DWORD dwSize); //-----------------------------------------public: //----------------------------------------- CPELibrary(); ~CPELibrary(); //----------------------------------------- void OpenFile(char* FileName); void SaveFile(char* FileName); //-----------------------------------------};
In Table 1, the usage of image_dos_header, pDosStub, image_nt_headers, image_section_header [MAX_SECTION_NUM], and image_section[MAX_SECTION_NUM] is clear. You use OpenFile() and SaveFile() to retrieve and rebuild a PE file. Furthermore, AddNewSection() is employed to create the new section, the important step.
4.2 Create data for the new section
You can comprehend the difference between incremental link and no-incremental link by looking at the following picture:
To acquire the virtual address of DynLoader(), you obtain the virtual address of JMP pemaker.DynLoader in the incremental link, but by no-incremental link, the real virtual address is gained by the following code:
DWORD dwVA= (DWORD) DynLoader;
This setting is more critical in the incremental link when you try to find the beginning and ending of the Loader, DynLoader(), by CPECryptor::ReturnToBytePtr():
void* CPECryptor::ReturnToBytePtr(void* FuncName, DWORD findstr){ void* tmpd; __asm { mov eax, FuncName jmp dfhjg: inc eaxdf: mov ebx, [eax] cmp ebx, findstr jnz hjg mov tmpd, eax } return tmpd;}
In pecrypt.cpp, I have represented another class, CPECryptor, to comprise the data of the new section. Nevertheless, the data of the new section is created by DynLoader() in loader.cpp, DynLoader Step 1. You use the CPECryptor class to enter this data in to the new section, and also some other stuff.
CPECryptor Class Step 1
//----------------------------------------------------------------class CPECryptor: public CPELibrary{private: //---------------------------------------- PCHAR pNewSection; //---------------------------------------- DWORD GetFunctionVA(void* FuncName); void* ReturnToBytePtr(void* FuncName, DWORD findstr); //----------------------------------------protected: //----------------------------------------public: //---------------------------------------- void CryptFile(int(__cdecl *callback) (unsigned int, unsigned int)); //----------------------------------------};//----------------------------------------------------------------
4.3 Some notes regarding creating a new PE file
- Align the VirtualAddress and the VirtualSize of each section by SectionAlignment:
image_section_header[i]->VirtualAddress= PEAlign(image_section_header[i]->VirtualAddress, image_nt_headers->OptionalHeader.SectionAlignment);image_section_header[i]->Misc.VirtualSize= PEAlign(image_section_header[i]->Misc.VirtualSize, image_nt_headers->OptionalHeader.SectionAlignment);
- Align the PointerToRawData and the SizeOfRawData of each section by FileAlignment:
image_section_header[i]->PointerToRawData = PEAlign(image_section_header[i]->PointerToRawData, image_nt_headers->OptionalHeader.FileAlignment);image_section_header[i]->SizeOfRawData = PEAlign(image_section_header[i]->SizeOfRawData, image_nt_headers->OptionalHeader.FileAlignment);
- Correct the SizeofImage by the virtual size and the virtual address of the last section:
image_nt_headers->OptionalHeader.SizeOfImage = image_section_header[LastSection]->VirtualAddress + image_section_header[LastSection]->Misc.VirtualSize;
- Set the Bound Import Directory header to zero because this directory is not very important to execute a PE file:
image_nt_headers-> OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT]. VirtualAddress = 0;image_nt_headers-> OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_ IMPORT].Size = 0;
4.4 Some notes regarding linking this VC Project
- Set Linker->General->Enable Incremental Linking to No (/INCREMENTAL:NO).
(
5 Store Important Data and Reach the Original OEP
Right now, we save the Original OEP and also the Image Base in order to reach to the virtual address of OEP. I have reserved a free space at the end of DynLoader() to store them, DynLoader Step 2.
PE Maker - Step 2
Download the pemaker2.zip source files from the end of the article.
DynLoader Step 2
__stdcall void DynLoader(){_asm{//------------------------------------ DWORD_TYPE(DYN_LOADER_START_MAGIC)//------------------------------------Main_0: PUSHAD // get base ebp CALL Main_1Main_1: POP EBP SUB EBP,OFFSET Main_1 MOV EAX,DWORD PTR [EBP+_RO_dwImageBase] ADD EAX,DWORD PTR [EBP+_RO_dwOrgEntryPoint] PUSH EAX RETN // >> JMP to Original OEP//---------------------------------- DWORD_TYPE(DYN_LOADER_START_DATA1)//----------------------------------//---------------------------------- DWORD_TYPE(DYN_LOADER_END_MAGIC)//----------------------------------}}_RO_dwImageBase: DWORD_TYPE(0xCCCCCCCC)_RO_dwOrgEntryPoint: DWORD_TYPE(0xCCCCCCCC)
The new function, CPECryptor::CopyData1(), will implement the copy of the Image Base value and the Offset of Entry Point value into 8 bytes of free space in the loader.
5.1 Restore the first register’s context
It is important to recover the Original Context of the thread. You have not yet done it in the DynLoader Step 2 source code. You can modify the source of DynLoader() to repossess the first Context.
__stdcall void DynLoader(){_asm{//------------------------------------ DWORD_TYPE(DYN_LOADER_START_MAGIC)//------------------------------------Main_0: PUSHAD// Save the registers context in stack CALL Main_1Main_1: POP EBP// Get Base EBP SUB EBP,OFFSET Main_1 MOV EAX,DWORD PTR [EBP+_RO_dwImageBase] ADD EAX,DWORD PTR [EBP+_RO_dwOrgEntryPoint] MOV DWORD PTR [ESP+1Ch],EAX // pStack.Eax <- EAX POPAD // Restore the first registers context from stack PUSH EAX XOR EAX, EAX RETN // >> JMP to Original OEP//---------------------------------- DWORD_TYPE(DYN_LOADER_START_DATA1)//----------------------------------_RO_dwImageBase: DWORD_TYPE(0xCCCCCCCC)_RO_dwOrgEntryPoint: DWORD_TYPE(0xCCCCCCCC)//---------------------------------- DWORD_TYPE(DYN_LOADER_END_MAGIC)//----------------------------------}}
5.2 Restore the original stack
You also can recover the original stack by setting the value of the beginning stack + 0×34 to the Original OEP, but it is not very important. Nevertheless, in the following code, I have accomplished the loader code by a simple trick to reach the OEP in addition to redecorating the stack. You can observe the implementation by tracing using OllyDbg or SoftICE.
__stdcall void DynLoader(){_asm{//---------------------------------- DWORD_TYPE(DYN_LOADER_START_MAGIC)//----------------------------------Main_0: PUSHAD // Save the registers context in stack CALL Main_1Main_1: POP EBP SUB EBP,OFFSET Main_1 MOV EAX,DWORD PTR [EBP+_RO_dwImageBase] ADD EAX,DWORD PTR [EBP+_RO_dwOrgEntryPoint] MOV DWORD PTR [ESP+54h],EAX // pStack.Eip <- EAX POPAD // Restore the first registers context from stack CALL _OEP_Jump DWORD_TYPE(0xCCCCCCCC)_OEP_Jump: PUSH EBP MOV EBP,ESP MOV EAX,DWORD PTR [ESP+3Ch] // EAX <- pStack.Eip MOV DWORD PTR [ESP+4h],EAX // _OEP_Jump RETURN pointer <- EAX XOR EAX,EAX LEAVE RETN//---------------------------------- DWORD_TYPE(DYN_LOADER_START_DATA1)//----------------------------------_RO_dwImageBase: DWORD_TYPE(0xCCCCCCCC)_RO_dwOrgEntryPoint: DWORD_TYPE(0xCCCCCCCC)//---------------------------------- DWORD_TYPE(DYN_LOADER_END_MAGIC)//----------------------------------}}
5.3 Approach OEP by structured exception handling
try-except statement in C++ clarifies the operation of structured exception handling. Besides the assembly code of this code, it elucidates the structured exception handler installation, the raise of an exception, and the exception handler function.
An exception is generated when a program falls into a fault code execution and an error happens, so in such a special condition, the program immediately jumps to a function called the exception handler from exception handler list of the Thread Information Block.
The next example of a
#include "stdafx.h"#include "windows.h"void RAISE_AN_EXCEPTION(){_asm{ INT 3 INT 3 INT 3 INT 3}}int _tmain(int argc, _TCHAR* argv[]){ __try { __try{ printf("1: Raise an Exception\n"); RAISE_AN_EXCEPTION(); } __finally { printf("2: In Finally\n"); } } __except( printf("3: In Filter\n"), EXCEPTION_EXECUTE_HANDLER ) { printf("4: In Exception Handler\n"); } return 0;}
; main()00401000: PUSH EBP00401001: MOV EBP,ESP00401003: PUSH -100401005: PUSH 00407160; __try {; the structured exception handler (SEH) installation 0040100A: PUSH _except_handler30040100F: MOV EAX,DWORD PTR FS:[0]00401015: PUSH EAX00401016: MOV DWORD PTR FS:[0],ESP0040101D: SUB ESP,800401020: PUSH EBX00401021: PUSH ESI00401022: PUSH EDI00401023: MOV DWORD PTR SS:[EBP-18],ESP; __try {00401026: XOR ESI,ESI00401028: MOV DWORD PTR SS:[EBP-4],ESI0040102B: MOV DWORD PTR SS:[EBP-4],100401032: PUSH OFFSET "1: Raise an Exception"00401037: CALL printf0040103C: ADD ESP,4; the raise a exception, INT 3 exception; RAISE_AN_EXCEPTION()0040103F: INT300401040: INT300401041: INT300401042: INT3; } __finally {00401043: MOV DWORD PTR SS:[EBP-4],ESI00401046: CALL 0040104D0040104B: JMP 004010800040104D: PUSH OFFSET "2: In Finally"00401052: CALL printf00401057: ADD ESP,40040105A: RETN; }; }; __except( 0040105B: JMP 004010800040105D: PUSH OFFSET "3: In Filter"00401062: CALL printf00401067: ADD ESP,40040106A: MOV EAX,1 ; EXCEPTION_EXECUTE_HANDLER = 10040106F: RETN; , EXCEPTION_EXECUTE_HANDLER ); {; the exception handler funtion00401070: MOV ESP,DWORD PTR SS:[EBP-18]00401073: PUSH OFFSET "4: In Exception Handler"00401078: CALL printf0040107D: ADD ESP,4; }00401080: MOV DWORD PTR SS:[EBP-4],-10040108C: XOR EAX,EAX; restore previous SEH0040108E: MOV ECX,DWORD PTR SS:[EBP-10]00401091: MOV DWORD PTR FS:[0],ECX00401098: POP EDI00401099: POP ESI0040109A: POP EBX0040109B: MOV ESP,EBP0040109D: POP EBP0040109E: RETN
Make a Win32 console project, and link and run the preceding C++ code, to perceive the result:
| 1: Raise an Exception 3: In Filter 2: In Finally 4: In Exception Handler _
|
This program runs the exception expression, printf("3: In Filter\n");, when an exception happens—in this example, the INT 3 exception. You can employ other kinds of exception too. In OllyDbg, Debugging options->Exceptions, you can see a short list of different types of exceptions.
5.3.1 Implement Exception Handler
You want to construct a structured exception handler to reach OEP. Now, I think you have distinguished the SEH installation, the exception raise, and the exception expression filter, by foregoing the assembly code. To establish your exception handler approach, you need to comprise the following codes:
- SEH installation:
LEA EAX,[EBP+_except_handler1_OEP_Jump]PUSH EAXPUSH DWORD PTR FS:[0]MOV DWORD PTR FS:[0],ESP
- An Exception Raise:
INT 3
- Exception handler expression filter:
_except_handler1_OEP_Jump: PUSH EBP MOV EBP,ESP ... // EXCEPTION_CONTINUE_SEARCH = 0 MOV EAX, EXCEPTION_CONTINUE_SEARCH LEAVE RETN
So, you yearn to make the ensuing C++ code in assembly language to inaugurate your engine to approach the Offset of the Entry Point by SEH.
__try // SEH installation{ __asm { INT 3 // An Exception Raise }}__except( ..., EXCEPTION_CONTINUE_SEARCH ){}// Exception handler expression filter
In assembly code…
; ---------------------------------------------------- ; the structured exception handler (SEH) installation ; __try { LEA EAX,[EBP+_except_handler1_OEP_Jump] PUSH EAX PUSH DWORD PTR FS:[0] MOV DWORD PTR FS:[0],ESP ; ---------------------------------------------------- ; the raise a INT 3 exception INT 3 INT 3 INT 3 INT 3 ; } ; __except( ... ; ---------------------------------------------------- ; exception handler expression filter_except_handler1_OEP_Jump: PUSH EBP MOV EBP,ESP ... MOV EAX, EXCEPTION_CONTINUE_SEARCH ; EXCEPTION_CONTINUE_SEARCH = 0 LEAVE RETN ; , EXCEPTION_CONTINUE_SEARCH ) { }
The exception value, __except(…, Value), determines how the exception is handled. It can have three values: 1, 0, -1. To understand them, refer to the try-except statement description in the MSDN library. You set it to EXCEPTION_CONTINUE_SEARCH (0), not to run the exception handler function; therefore, by this value, the exception is not recognized. It is simply ignored, and the thread continues its code execution.
How the SEH installation is implemented
As you perceived from the illustrated code, the SEH installation is done by the FS segment register. Microsoft Windows 32 bit uses the FS segment register as a pointer to the data block of the main thread. The first 0×1C bytes comprise the information of the Thread Information Block (TIB). Therefore, FS:[00h] refers to ExceptionList of the main thread, Table 3. In your code, you have pushed the pointer to _except_handler1_OEP_Jump in the stack and changed the value of ExceptionList, FS:[00h], to the beginning of the stack, ESP.
Thread Information Block (TIB)
typedef struct _NT_TIB32 { DWORD ExceptionList; DWORD StackBase; DWORD StackLimit; DWORD SubSystemTib; union { DWORD FiberData; DWORD Version; }; DWORD ArbitraryUserPointer; DWORD Self;} NT_TIB32, *PNT_TIB32;
Table 3: FS segment register and Thread Information Block
| DWORD PTR FS:[00h] | ExceptionList |
| DWORD PTR FS:[04h] | StackBase |
| DWORD PTR FS:[08h] | StackLimit |
| DWORD PTR FS:[0Ch] | SubSystemTib |
| DWORD PTR FS:[10h] | FiberData / Version |
| DWORD PTR FS:[14h] | ArbitraryUserPointer |
| DWORD PTR FS:[18h] | Self |
5.3.2 Attain OEP by adjusting the Thread Context
In this part, you effectuate your performance by accomplishing the OEP approach. You change the Context of the thread and ignore every simple exception handling, and let the thread continue the execution, but in the original OEP!
| Context Flags | 0×00000000 | ContextFlags | |
|
Context Debug Registers |
0×00000004 | Dr0 | |
| 0×00000008 | Dr1 | ||
| 0×0000000C | Dr2 | ||
| 0×00000010 | Dr3 | ||
| 0×00000014 | Dr6 | ||
| 0×00000018 | Dr7 | ||
|
Context Floating Point |
0×0000001C | FloatSave | StatusWord |
| 0×00000020 | StatusWord | ||
| 0×00000024 | TagWord | ||
| 0×00000028 | ErrorOffset | ||
| 0×0000002C | ErrorSelector | ||
| 0×00000030 | DataOffset | ||
| 0×00000034 | DataSelector | ||
| 0×00000038 … 0×00000087 |
|||