├── LICENSE.txt ├── MyPinTool.cpp ├── MyPinTool.h ├── MyPinTool.sln ├── MyPinTool.vcxproj ├── Tracer.cpp ├── Tracer.h ├── Util.cpp ├── ad.cpp ├── ad.h ├── common.h ├── icpin_importer.py ├── makefile ├── makefile.rules ├── memaccess.cpp ├── memaccess.h └── readme.md /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | -------------------------------------------------------------------------------- /MyPinTool.cpp: -------------------------------------------------------------------------------- 1 | #include "MyPinTool.h" 2 | 3 | KNOB knob_imageName(KNOB_MODE_WRITEONCE, "pintool", "i", "", "Image name (defaults to main exe"); 4 | 5 | VOID Fini(INT32 code, VOID *v) 6 | { 7 | // Print mem accesses 8 | tracer::print_results(); 9 | // Print anti-debug gadgets backtraces 10 | ad_hook::printAllAdBacktraces(); 11 | Util::Log(FALSE, "#DONE (%x)\n", code); 12 | Util::logend(); 13 | } 14 | 15 | INT32 Usage() 16 | { 17 | PIN_ERROR("This Pintool prints a trace of memory addresses\n" + KNOB_BASE::StringKnobSummary() + "\n"); 18 | return -1; 19 | } 20 | 21 | VOID Image(IMG img, VOID *v) 22 | { 23 | // Full binary path 24 | string imagePath = IMG_Name(img); 25 | // Get the image name 26 | string imageName = imagePath.substr(IMG_Name(img).rfind("\\") + 1); 27 | Util::Log(TRUE, "[LOAD] %s [%p - %p]\n", imagePath.c_str(), IMG_LowAddress(img), IMG_HighAddress(img)); 28 | // TODO: Allow command line parametrization (for dlls) 29 | if (knob_imageName.Value().empty() && IMG_IsMainExecutable(img) 30 | || (Util::StrtoLower(knob_imageName.Value()) == Util::StrtoLower(imageName))) { 31 | // TODO: HANDLE CODE RUN FROM RDATA AND OTHER SECTIONS 32 | // Get the .text section bounds 33 | SEC section = IMG_SecHead(img); 34 | do { 35 | if (SEC_Name(section) == string(".text")) { 36 | Util::base = IMG_LowAddress(img); 37 | Util::start = SEC_Address(section); 38 | Util::end = Util::start + SEC_Size(section); 39 | Util::entry = IMG_Entry(img); 40 | Util::Log(TRUE, "[TRACKER] Watching %s [%p - %p], entry at %08x\n", imageName.c_str(), Util::start, Util::end, Util::entry); 41 | break; 42 | } 43 | section = SEC_Next(section); 44 | } while (section != SEC_Invalid()); 45 | // TODO: handle multiple ranges 46 | Util::imageName = imageName; 47 | } 48 | // Walk through the symbols in the symbol table. 49 | for (SYM sym = IMG_RegsymHead(img); SYM_Valid(sym); sym = SYM_Next(sym)) { 50 | string undFuncName = PIN_UndecorateSymbolName(SYM_Name(sym), UNDECORATION_NAME_ONLY); 51 | // If it is a watched symbol, update object with address 52 | ad_hook::UpdateWatchedAD(undFuncName, imageName, IMG_LowAddress(img) + SYM_Value(sym)); 53 | } 54 | } 55 | 56 | #define MAX_DEBUG_LEN 1024 57 | VOID exhandler(THREADID threadIndex, CONTEXT_CHANGE_REASON reason, const CONTEXT *from, CONTEXT *to, INT32 info, VOID *v) 58 | { 59 | char *debugstr=NULL; 60 | vector trace; 61 | 62 | if (reason == CONTEXT_CHANGE_REASON_EXCEPTION) { 63 | switch (info) { 64 | case 0xe0434352: 65 | break; 66 | case 0x40010006: 67 | debugstr = (*(char**)(PIN_GetContextReg(from, REG_ESP) + 0x18)); 68 | if (debugstr[0] != '%') { 69 | Util::Log(TRUE, "[DEBUG] %s", debugstr); 70 | } 71 | break; 72 | case 0x4001000a: 73 | // TODO: Print unicode debug output? 74 | break; 75 | case EXCEPTION_BREAKPOINT: 76 | Util::Log(TRUE, "[EXCEPTION_BREAKPOINT] code: %#x\tip: %p -> %p\n", info, PIN_GetContextReg(from, REG_PC), PIN_GetContextReg(to, REG_PC)); 77 | break; 78 | case STATUS_GUARD_PAGE_VIOLATION: 79 | Util::Log(TRUE, "[STATUS_GUARD_PAGE_VIOLATION] code: %#x\tip: %p -> %p\n", info, PIN_GetContextReg(from, REG_PC), PIN_GetContextReg(to, REG_PC)); 80 | break; 81 | case EXCEPTION_ACCESS_VIOLATION: 82 | Util::Log(TRUE, "[EXCEPTION] code: %#x\tip: %p -> %p\n", info, PIN_GetContextReg(from, REG_PC), PIN_GetContextReg(to, REG_PC)); 83 | Util::printContext(from, 40); 84 | trace = tracer::GetTrace(threadIndex); 85 | Util::Log(TRUE, "[%#x] ", threadIndex); 86 | for (auto &addr : trace) { 87 | Util::Log(TRUE, "%p ", addr); 88 | } 89 | Util::Log(TRUE, "\n"); 90 | break; 91 | default: 92 | Util::Log(TRUE, "[EXCEPTION] code: %#x\tip: %p -> %p\n", info, PIN_GetContextReg(from, REG_PC), PIN_GetContextReg(to, REG_PC)); 93 | Util::printContext(from, 0); 94 | break; 95 | } 96 | } 97 | return; 98 | } 99 | 100 | EXCEPT_HANDLING_RESULT internalException(THREADID tid, EXCEPTION_INFO *pExceptInfo, PHYSICAL_CONTEXT *pPhysCtxt, VOID *v) 101 | { 102 | Util::Log(TRUE, "[PINBUG] It was at this moment that pintool knew - %s\n", pExceptInfo->ToString().c_str()); 103 | Fini(pExceptInfo->m_exceptCode, v); 104 | return EHR_UNHANDLED; 105 | } 106 | 107 | VOID AppStartCallback(VOID *v) 108 | { 109 | Util::Log(FALSE, "[TIME] Initial instrumentation took %f seconds\n", Util::queryElapsedTime(TRUE)); 110 | } 111 | 112 | int main(int argc, char *argv[]) 113 | { 114 | // Time accounting 115 | Util::startTimer(); 116 | // Initialize symbol processing 117 | PIN_InitSymbols(); 118 | // Pin init 119 | if (PIN_Init(argc, argv)) { 120 | return Usage(); 121 | } 122 | // Setup the list of watched functions and instructions 123 | ad_hook::setup(); 124 | // Open trace file 125 | Util::loginit("pinatrace.out"); 126 | // Instrumentation for each image load 127 | IMG_AddInstrumentFunction(Image, 0); 128 | // Start tracer 129 | TRACE_AddInstrumentFunction(tracer::Trace, 0); 130 | INS_AddInstrumentFunction(tracer::Instruction, 0); 131 | // Register callback for pintool internal exception 132 | PIN_AddInternalExceptionHandler(internalException, NULL); 133 | // Register callback for intrumented binary exception 134 | PIN_AddContextChangeFunction(exhandler, 0); 135 | // Register function to be called at the end of all things 136 | PIN_AddFiniFunction(Fini, 0); 137 | PIN_AddApplicationStartFunction(AppStartCallback, NULL); 138 | // Never returns 139 | PIN_StartProgram(); 140 | // Nope 141 | return 0; 142 | } 143 | -------------------------------------------------------------------------------- /MyPinTool.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "common.h" 3 | #include "ad.h" 4 | 5 | const string reasons[] = { 6 | "CONTEXT_CHANGE_REASON_FATALSIGNAL", 7 | "CONTEXT_CHANGE_REASON_SIGNAL", 8 | "CONTEXT_CHANGE_REASON_SIGRETURN", 9 | "CONTEXT_CHANGE_REASON_APC", 10 | "CONTEXT_CHANGE_REASON_EXCEPTION", 11 | "CONTEXT_CHANGE_REASON_CALLBACK" 12 | }; 13 | -------------------------------------------------------------------------------- /MyPinTool.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25123.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MyPinTool", "MyPinTool.vcxproj", "{639EF517-FCFC-408E-9500-71F0DC0458DB}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.ActiveCfg = Debug|x64 17 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.Build.0 = Debug|x64 18 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x86.ActiveCfg = Debug|Win32 19 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x86.Build.0 = Debug|Win32 20 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.ActiveCfg = Release|x64 21 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.Build.0 = Release|x64 22 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x86.ActiveCfg = Release|Win32 23 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /MyPinTool.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Debug 10 | x64 11 | 12 | 13 | Release 14 | Win32 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {639EF517-FCFC-408E-9500-71F0DC0458DB} 23 | MyPinTool 24 | Win32Proj 25 | 10.0.17134.0 26 | 27 | 28 | 29 | DynamicLibrary 30 | MultiByte 31 | true 32 | v141 33 | 34 | 35 | DynamicLibrary 36 | MultiByte 37 | v141 38 | 39 | 40 | DynamicLibrary 41 | MultiByte 42 | true 43 | v141 44 | 45 | 46 | DynamicLibrary 47 | MultiByte 48 | v141 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | <_ProjectFileVersion>10.0.40219.1 67 | $(ProjectDir)$(Configuration)\ 68 | $(Configuration)\ 69 | false 70 | false 71 | $(ProjectDir)$(Platform)\$(Configuration)\ 72 | $(Platform)\$(Configuration)\ 73 | false 74 | false 75 | $(ProjectDir)$(Configuration)\ 76 | $(Configuration)\ 77 | false 78 | false 79 | $(ProjectDir)$(Platform)\$(Configuration)\ 80 | $(Platform)\$(Configuration)\ 81 | false 82 | false 83 | AllRules.ruleset 84 | 85 | 86 | AllRules.ruleset 87 | 88 | 89 | AllRules.ruleset 90 | 91 | 92 | AllRules.ruleset 93 | 94 | 95 | 96 | 97 | $(LibraryPath) 98 | $(IncludePath) 99 | 100 | 101 | D:\pin-3.0-76991-msvc-windows\ia32\runtime\pincrt;D:\pin-3.0-76991-msvc-windows\ia32\lib\pincrt;D:\pin-3.0-76991-msvc-windows\ia32\lib-ext\pincrt;$(LibraryPath) 102 | 103 | 104 | 105 | /GR- /GS- /EHs- /EHa- /FP:strict /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions) 106 | Disabled 107 | ..\..\include\pin;..\..\include\pin\gen;..\InstLib;..\..\..\extras\xed-ia32\include;..\..\..\extras\components\include;..\..\..\extras\stlport\include;..\..\..\extras;..\..\..\extras\libstdc++\include;..\..\..\extras\crt\include;..\..\..\extras\crt;..\..\..\extras\crt\include\arch-x86;..\..\..\extras\crt\include\kernel\uapi;..\..\..\extras\crt\include\kernel\uapi\asm-x86;%(AdditionalIncludeDirectories) 108 | TARGET_IA32;HOST_IA32;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;__PIN__=1;PIN_CRT=1;__i386__ 109 | false 110 | 111 | 112 | Default 113 | MultiThreaded 114 | false 115 | true 116 | NotSet 117 | false 118 | 119 | 120 | Level3 121 | ProgramDatabase 122 | 4530;%(DisableSpecificWarnings) 123 | 124 | 125 | /export:main %(AdditionalOptions) 126 | pin.lib;xed.lib;pinvm.lib;kernel32.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-32.lib 127 | ..\..\..\ia32\lib;..\..\..\ia32\lib-ext;..\..\..\extras\xed-ia32\lib;..\..\..\ia32\runtime\pincrt;%(AdditionalLibraryDirectories) 128 | true 129 | %(IgnoreSpecificDefaultLibraries) 130 | true 131 | NotSet 132 | false 133 | Ptrace_DllMainCRTStartup%4012 134 | 0x55000000 135 | MachineX86 136 | true 137 | 138 | 139 | 140 | 141 | X64 142 | 143 | 144 | /GR- /GS- /EHs- /EHa- /FP:strict /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions) 145 | Disabled 146 | ..\..\include\pin;..\..\include\pin\gen;..\InstLib;..\..\..\extras\xed-intel64\include;..\..\..\extras\components\include;..\..\..\extras\stlport\include;..\..\..\extras;..\..\..\extras\libstdc++\include;..\..\..\extras\crt\include;..\..\..\extras\crt;..\..\..\extras\crt\include\arch-x86_64;..\..\..\extras\crt\include\kernel\uapi;..\..\..\extras\crt\include\kernel\uapi\asm-x86;%(AdditionalIncludeDirectories) 147 | TARGET_IA32E;HOST_IA32E;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;__PIN__=1;PIN_CRT=1;__LP64__ 148 | false 149 | 150 | 151 | Default 152 | MultiThreaded 153 | false 154 | true 155 | false 156 | 157 | 158 | Level3 159 | ProgramDatabase 160 | 4530;%(DisableSpecificWarnings) 161 | 162 | 163 | /export:main %(AdditionalOptions) 164 | pin.lib;xed.lib;pinvm.lib;kernel32.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-64.lib 165 | ..\..\..\intel64\lib;..\..\..\intel64\lib-ext;..\..\..\extras\xed-intel64\lib;..\..\..\intel64\runtime\pincrt;%(AdditionalLibraryDirectories) 166 | true 167 | %(IgnoreSpecificDefaultLibraries) 168 | true 169 | NotSet 170 | false 171 | Ptrace_DllMainCRTStartup 172 | 0xC5000000 173 | MachineX64 174 | true 175 | 176 | 177 | 178 | 179 | /GR- /GS- /EHs- /EHa- /FP:strict /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions) 180 | false 181 | false 182 | ..\..\include\pin;..\..\include\pin\gen;..\InstLib;..\..\..\extras\xed-ia32\include\xed;..\..\..\extras\components\include;..\..\..\extras\stlport\include;..\..\..\extras;..\..\..\extras\libstdc++\include;..\..\..\extras\crt\include;..\..\..\extras\crt;..\..\..\extras\crt\include\arch-x86;..\..\..\extras\crt\include\kernel\uapi;..\..\..\extras\crt\include\kernel\uapi\asm-x86;%(AdditionalIncludeDirectories) 183 | TARGET_IA32;HOST_IA32;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;__PIN__=1;PIN_CRT=1;__i386__ 184 | false 185 | 186 | 187 | Default 188 | MultiThreaded 189 | false 190 | true 191 | NotSet 192 | false 193 | 194 | 195 | Level3 196 | 197 | 198 | 4530;%(DisableSpecificWarnings) 199 | 200 | 201 | /export:main %(AdditionalOptions) 202 | pin.lib;xed.lib;pinvm.lib;kernel32.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-32.lib;crtbeginS.obj 203 | ..\..\..\ia32\lib;..\..\..\ia32\lib-ext;..\..\..\extras\xed-ia32\lib;..\..\..\ia32\runtime\pincrt;%(AdditionalLibraryDirectories) 204 | true 205 | %(IgnoreSpecificDefaultLibraries) 206 | true 207 | NotSet 208 | true 209 | 210 | 211 | 212 | 213 | Ptrace_DllMainCRTStartup%4012 214 | 0x55000000 215 | MachineX86 216 | false 217 | NotSet 218 | 219 | 220 | 221 | 222 | X64 223 | 224 | 225 | /GR- /GS- /EHs- /EHa- /FP:strict /Oi- /FIinclude/msvc_compat.h %(AdditionalOptions) 226 | false 227 | false 228 | ..\..\include\pin;..\..\include\pin\gen;..\InstLib;..\..\..\extras\xed-intel64\include\xed;..\..\..\extras\components\include;..\..\..\extras\stlport\include;..\..\..\extras;..\..\..\extras\libstdc++\include;..\..\..\extras\crt\include;..\..\..\extras\crt;..\..\..\extras\crt\include\arch-x86_64;..\..\..\extras\crt\include\kernel\uapi;..\..\..\extras\crt\include\kernel\uapi\asm-x86;%(AdditionalIncludeDirectories) 229 | TARGET_IA32E;HOST_IA32E;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;__PIN__=1;PIN_CRT=1;__LP64__ 230 | false 231 | 232 | 233 | Default 234 | MultiThreaded 235 | false 236 | true 237 | false 238 | 239 | 240 | Level3 241 | 242 | 243 | 4530;%(DisableSpecificWarnings) 244 | true 245 | 246 | 247 | /export:main %(AdditionalOptions) 248 | crtbeginS.obj;pin.lib;xed.lib;pinvm.lib;kernel32.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-64.lib 249 | ..\..\..\intel64\lib;..\..\..\intel64\lib-ext;..\..\..\extras\xed-intel64\lib;..\..\..\intel64\runtime\pincrt;%(AdditionalLibraryDirectories) 250 | true 251 | %(IgnoreSpecificDefaultLibraries) 252 | true 253 | NotSet 254 | true 255 | 256 | 257 | 258 | 259 | Ptrace_DllMainCRTStartup 260 | 0xC5000000 261 | MachineX64 262 | 263 | 264 | %(Inputs) 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | -------------------------------------------------------------------------------- /Tracer.cpp: -------------------------------------------------------------------------------- 1 | #include "Tracer.h" 2 | 3 | vector> tracer::trace(MAX_NB_THREADS, vector(BBL_BACKTRACE)); 4 | map> tracer::dynamicCodeAllocs; 5 | UINT tracer::current[MAX_NB_THREADS] = { 0 }; 6 | std::tr1::unordered_map tracer::gadgets; 7 | 8 | // This must be fast 9 | // TODO: use trace buffer ? https://software.intel.com/sites/landingpage/pintool/docs/65163/Pin/html/index.html#Buffering 10 | VOID tracer::track(THREADID tid, ADDRINT addr) 11 | { 12 | if (tid < MAX_NB_THREADS) { 13 | trace[tid][current[tid]] = addr; 14 | // current[tid] should point at the next 'free' bbl address 15 | // so the insert call in GetTrace is straightfoward [) 16 | if (++current[tid] >= BBL_BACKTRACE) { 17 | current[tid] = 0; 18 | } 19 | } 20 | return; 21 | } 22 | 23 | VOID tracer::trackdynamic(THREADID tid, CONTEXT *ctxt, ADDRINT sp, BOOL guard) 24 | { 25 | EXCEPTION_INFO exceptInfo; 26 | ADDRINT ip; 27 | 28 | // Just print backtrace on how we got here 29 | auto& trace = GetTrace(tid); 30 | Util::Log(TRUE, "[DYNAMIC_CODE] Thread %p backtrace: ", tid); 31 | for (auto addr : trace) { 32 | Util::Log(FALSE, "-> %#p ", addr); 33 | } 34 | Util::Log(FALSE, "\n--------\n"); 35 | 36 | // Rethrow the guard page 37 | if (guard) { 38 | // Capture exception to-be address 39 | ip = PIN_GetContextReg(ctxt, REG_PC); 40 | // Check the page for guard flag 41 | Util::Log(TRUE, "[DYNAMIC_CODE] PAGE_GUARD AT %p\n", ip); 42 | // Initialize a PAGE_GUARD_EXCEPTION 43 | PIN_InitAccessFaultInfo(&exceptInfo, EXCEPTCODE_ACCESS_WINDOWS_GUARD_PAGE, ip, ip, FAULTY_ACCESS_EXECUTE); 44 | //PIN_InitWindowsExceptionInfo(&exceptInfo, STATUS_GUARD_PAGE_VIOLATION, ip, 0, NULL); 45 | PIN_RaiseException(ctxt, tid, &exceptInfo); 46 | } 47 | return; 48 | } 49 | 50 | // Instrument all the basic blocks for tracing 51 | VOID tracer::LogCode(BBL bbl) 52 | { 53 | INS ins = BBL_InsHead(bbl); 54 | for (UINT i=0; i= TRACKANDLOG) { 75 | // Log the dynamic code found 76 | LogCode(bbl); 77 | // This might also need to raise the page guard exception 78 | BBL_InsertCall(bbl, IPOINT_BEFORE, (AFUNPTR)trackdynamic, 79 | IARG_THREAD_ID, 80 | IARG_CONTEXT, 81 | IARG_REG_VALUE, REG_SP, 82 | IARG_BOOL, tracking==TRACK_LOG_RAISE, 83 | IARG_END); 84 | } 85 | } 86 | } 87 | } 88 | 89 | // TODO: Could this be made faster with PIN_FAST_ANALYSIS_CALL? 90 | ADDRINT tracer::IsThisCode(ADDRINT addr) 91 | { 92 | if (addr) { 93 | // This address belongs to watched binary's .text 94 | if ((addr >= Util::start) && (addr < Util::end)) { 95 | return TRACK; 96 | } 97 | auto &it = dynamicCodeAllocs.upper_bound(addr); 98 | if (it != dynamicCodeAllocs.begin()) { 99 | it--; 100 | // Check upper bound 101 | if (addr < it->second.first) { 102 | if (it->second.second&PAGE_GUARD) { 103 | return TRACK_LOG_RAISE; 104 | } 105 | if (it->second.second&PAGE_ANYEXE) { 106 | return TRACKANDLOG; 107 | } 108 | } 109 | } 110 | } 111 | return NOTCODE; 112 | } 113 | 114 | VOID tracer::Instruction(INS ins, VOID *v) 115 | { 116 | ADDRINT addr = INS_Address(ins); 117 | // Only intrument our binary of interest 118 | if (IsThisCode(addr) && !INS_IsCall(ins)) { 119 | // This intruction reads and is not a jump (ignore .text jump tables) 120 | // TODO: Insert callback AFTER write 121 | if (INS_IsMemoryWrite(ins)) { 122 | INS_InsertIfPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)IsThisCode, 123 | IARG_MEMORYWRITE_EA, 124 | IARG_END); 125 | INS_InsertThenPredicatedCall( 126 | ins, IPOINT_BEFORE, (AFUNPTR)RecordMemAccess, 127 | IARG_INST_PTR, 128 | IARG_MEMORYWRITE_EA, 129 | IARG_MEMORYWRITE_SIZE, 130 | IARG_UINT32, WRITE, 131 | IARG_END); 132 | } 133 | // Must be mutually exclusive! treat read+write as a write 134 | else if (INS_IsMemoryRead(ins) && !INS_IsIndirectBranchOrCall(ins)) { 135 | // Insert callback BEFORE READ 136 | INS_InsertIfPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)IsThisCode, 137 | IARG_MEMORYREAD_EA, 138 | IARG_END); 139 | INS_InsertThenPredicatedCall( 140 | ins, IPOINT_BEFORE, (AFUNPTR)RecordMemAccess, 141 | IARG_INST_PTR, 142 | IARG_MEMORYREAD_EA, 143 | IARG_MEMORYREAD_SIZE, 144 | IARG_UINT32, READ, 145 | IARG_END); 146 | } 147 | } 148 | } 149 | 150 | vector tracer::GetTrace(THREADID tid) 151 | { 152 | const vector::iterator& it = trace[tid].begin()+current[tid]; 153 | //Util::Log(TRUE, "Trace requested. current[tid] is %#x. hit bbl is %#p\n", current[tid], trace[tid][current[tid]]); 154 | vector v = vector(it, trace[tid].end()); 155 | v.insert(v.end(), trace[tid].begin(), it); 156 | return v; 157 | } 158 | 159 | // Returns the current BBL address 160 | ADDRINT tracer::GetCurrentBBL(THREADID tid) 161 | { 162 | return current[tid]==0 ? trace[tid][BBL_BACKTRACE-1] : trace[tid][current[tid]-1]; 163 | } 164 | 165 | // For current, nb = 1, for previous nb == 2, etc. 166 | ADDRINT tracer::GetPreviousBBLAddress(THREADID tid, UINT nb) 167 | { 168 | return current[tid] >= nb ? trace[tid][current[tid] - nb] : trace[tid][BBL_BACKTRACE - nb]; 169 | } 170 | 171 | VOID tracer::addCodeRange(THREADID tid, ADDRINT start, ADDRINT end, WIN::DWORD protect) 172 | { 173 | dynamicCodeAllocs.insert(pair>(start, pair(end, protect))); 174 | //Util::Log(TRUE, "[DYNAMIC_CODE] added watched range: %08x-%08x (%08x) \n", start, end, protect); 175 | Util::Log(TRUE, "[DYNAMIC_CODE] allocation backtrace: "); 176 | auto& trace = GetTrace(tid); 177 | for (auto addr : trace) { 178 | Util::Log(FALSE, "-> %p ", addr); 179 | } 180 | Util::Log(FALSE, "\n--------\n"); 181 | Util::Log(TRUE, "[LIST] List of dynamic code allocs:\n"); 182 | for (auto &range : dynamicCodeAllocs) { 183 | Util::Log(TRUE, "%p-%p (%08x)\n", range.first, range.second.first, range.second.second); 184 | } 185 | Util::Log(TRUE, "[ENDLIST]\n"); 186 | return; 187 | } 188 | 189 | VOID tracer::removeCodeRange(ADDRINT start) 190 | { 191 | if (dynamicCodeAllocs.erase(start)) { 192 | Util::Log(TRUE, "[DYNAMIC_CODE] Memory range freed\n"); 193 | Util::Log(TRUE, "[LIST] List of dynamic code allocs:\n"); 194 | for (auto &range : dynamicCodeAllocs) { 195 | Util::Log(TRUE, "%08x-%08x (%08x)\n", range.first, range.second.first, range.second.second); 196 | } 197 | Util::Log(TRUE, "[ENDLIST]\n"); 198 | } 199 | return; 200 | } 201 | 202 | VOID tracer::UpdateCodeRangeProtect(ADDRINT address, WIN::DWORD protect) 203 | { 204 | auto &it = dynamicCodeAllocs.find(address); 205 | //Util::Log(TRUE, "[DYNAMIC_CODE] range protection [%08x] %08x -> %08x\n", address, dynamicCodeAllocs[address].second, protect); 206 | if (it != dynamicCodeAllocs.end()) { 207 | dynamicCodeAllocs[address].second = protect; 208 | } 209 | } 210 | 211 | // Last pass to get final writes 212 | VOID tracer::GetLastMemState() 213 | { 214 | for (auto& g : gadgets) { 215 | UINT64 val = 0; 216 | if (g.second->type == WRITE) { 217 | WriteGadget *wg = static_cast(g.second); 218 | for (auto& p : wg->offset_values) { 219 | PIN_SafeCopy(&val, (VOID*)p.first, wg->len); 220 | wg->update_offset_values(p.first, val); 221 | } 222 | } 223 | } 224 | } 225 | 226 | // Record a memory read or write on .text 227 | VOID tracer::RecordMemAccess(ADDRINT ip, ADDRINT addr, size_t size, INT type) 228 | { 229 | UINT64 val = 0; 230 | // Need to create new gadget? 231 | auto& it = gadgets.find(ip); 232 | if (it == gadgets.end()) { 233 | if (type == READ) { 234 | ReadGadget *rg = new ReadGadget(ip, addr, addr + size); 235 | gadgets.insert(pair(ip, rg)); 236 | } 237 | else { 238 | // Write gadget 239 | PIN_SafeCopy(&val, (VOID*)addr, size); 240 | WriteGadget *wg = new WriteGadget(ip, addr, val, size); 241 | gadgets.insert(pair(ip, wg)); 242 | } 243 | Gadget::current++; 244 | } 245 | else { 246 | // Insertion failed, existing gadget -> update offsets and values 247 | if (type == READ) { 248 | ReadGadget *rg = static_cast(it->second); 249 | rg->update_range(addr, addr + size); 250 | } 251 | else { 252 | // Write gadget 253 | WriteGadget *wg = static_cast(it->second); 254 | PIN_SafeCopy(&val, (VOID*)addr, size); 255 | wg->update_offset_values(addr, val); 256 | } 257 | } 258 | return; 259 | } 260 | 261 | VOID tracer::print_results() 262 | { 263 | // Print runtime 264 | Util::Log(FALSE, "TIME: Running instrumented took %.2lf seconds\n", Util::queryElapsedTime(TRUE)); 265 | // First get the last writes 266 | GetLastMemState(); 267 | // Sorting method: first seen 268 | struct FirstSeenComp 269 | { 270 | bool operator()(const Gadget* a, const Gadget* b) const { 271 | if (a->firstSeen < b->firstSeen) { 272 | return true; 273 | } 274 | return false; 275 | } 276 | }; 277 | // Sort the gadgets by first seen 278 | std::set ordered; 279 | for (auto& p : gadgets) { 280 | ordered.insert(p.second); 281 | } 282 | Util::Log(FALSE, "GADGET LIST ------------------------------ \n"); 283 | for (auto& p : ordered) { 284 | p->print(); 285 | } 286 | Util::Log(TRUE, "Total: %lu gadgets\n", gadgets.size()); // this will flush 287 | } 288 | -------------------------------------------------------------------------------- /Tracer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "common.h" 3 | #include "memaccess.h" 4 | 5 | #define MAX_NB_THREADS 200 6 | #define BBL_BACKTRACE 80 7 | 8 | 9 | // Everything static - cant afford singleton overhead 10 | class tracer 11 | { 12 | private: 13 | enum TRACKTYPE { 14 | NOTCODE=0, 15 | TRACK, 16 | TRACKANDLOG, 17 | TRACK_LOG_RAISE 18 | }; 19 | static vector> trace; // one trace vector for each thread 20 | static UINT current[MAX_NB_THREADS]; 21 | static map> dynamicCodeAllocs; 22 | static std::tr1::unordered_map gadgets; // List of gadgets 23 | static VOID GetLastMemState(); 24 | public: 25 | static VOID track(THREADID, ADDRINT); 26 | static VOID trackdynamic(THREADID, CONTEXT*, ADDRINT, BOOL); 27 | static VOID Trace(TRACE, VOID*); 28 | static ADDRINT IsThisCode(ADDRINT); 29 | static VOID Instruction(INS, VOID*); 30 | static vector GetTrace(THREADID); 31 | static VOID addCodeRange(THREADID, ADDRINT, ADDRINT, WIN::DWORD); 32 | static VOID removeCodeRange(ADDRINT); 33 | static VOID UpdateCodeRangeProtect(ADDRINT, WIN::DWORD); 34 | static ADDRINT GetCurrentBBL(THREADID); 35 | static ADDRINT GetPreviousBBLAddress(THREADID, UINT); 36 | static VOID LogCode(BBL); 37 | static VOID RecordMemAccess(ADDRINT, ADDRINT, size_t, INT); 38 | static VOID print_results(); 39 | }; -------------------------------------------------------------------------------- /Util.cpp: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | 3 | namespace Util { 4 | // Vars 5 | FILE *log; 6 | time_t tStart; 7 | string imageName; 8 | ADDRINT base, start, end, entry; 9 | 10 | VOID loginit(string filename) 11 | { 12 | log = fopen(filename.c_str(), "w"); 13 | } 14 | 15 | VOID logend() 16 | { 17 | fflush(log); 18 | fclose(log); 19 | } 20 | 21 | VOID Log(BOOL now, const char *fmt ...) 22 | { 23 | va_list argptr; 24 | va_start(argptr, fmt); 25 | vfprintf(log, fmt, argptr); 26 | va_end(argptr); 27 | if (now) { 28 | fflush(log); 29 | } 30 | } 31 | 32 | VOID startTimer() 33 | { 34 | time(&tStart); 35 | return; 36 | } 37 | 38 | double queryElapsedTime(BOOL reset) 39 | { 40 | time_t tNow; 41 | time(&tNow); 42 | double elapsed = difftime(tNow, tStart); 43 | if (reset) { 44 | startTimer(); 45 | } 46 | return elapsed; 47 | } 48 | 49 | string StrtoLower(string s) 50 | { 51 | string ret(s); 52 | for (int i = 0; s[i]; i++) { 53 | ret[i] = tolower(s[i]); 54 | } 55 | return ret; 56 | } 57 | 58 | #if _WIN64 59 | VOID printContext(const CONTEXT *ctx, UINT32 c) 60 | { 61 | Log(TRUE, "RAX = %p\tRBX = %p\tRCX = %p\nRDX = %p\tRSI = %p\tRDI = %p\nRBP = %p\tRSP = %p\tRIP = %p\n", 62 | PIN_GetContextReg(ctx, REG_RAX), 63 | PIN_GetContextReg(ctx, REG_RBX), 64 | PIN_GetContextReg(ctx, REG_RCX), 65 | PIN_GetContextReg(ctx, REG_RDX), 66 | PIN_GetContextReg(ctx, REG_RSI), 67 | PIN_GetContextReg(ctx, REG_RDI), 68 | PIN_GetContextReg(ctx, REG_RBP), 69 | PIN_GetContextReg(ctx, REG_RSP), 70 | PIN_GetContextReg(ctx, REG_RIP)); 71 | // TODO: use the safe copy API 72 | //UINT count = ((c == -1) ? ((PIN_GetContextReg(ctx, REG_RBP)-PIN_GetContextReg(ctx, REG_RSP))/sizeof(ADDRINT))+1 : c); 73 | //ADDRINT *ptr = (ADDRINT*)PIN_GetContextReg(ctx, REG_RSP); 74 | //for (UINT32 i = 0; i < count; i++) { 75 | // Log(TRUE, "[%08x]: %08x\n", ptr, *ptr); 76 | // ptr++; 77 | //} 78 | } 79 | #else 80 | VOID printContext(const CONTEXT *ctx, UINT32 c) 81 | { 82 | Log(TRUE, "EAX = %08x\tEBX = %08x\tECX = %08x\nEDX = %08x\tESI = %08x\tEDI = %08x\nEBP = %08x\tESP = %08x\tEIP = %08x\n", 83 | PIN_GetContextReg(ctx, REG_EAX), 84 | PIN_GetContextReg(ctx, REG_EBX), 85 | PIN_GetContextReg(ctx, REG_ECX), 86 | PIN_GetContextReg(ctx, REG_EDX), 87 | PIN_GetContextReg(ctx, REG_ESI), 88 | PIN_GetContextReg(ctx, REG_EDI), 89 | PIN_GetContextReg(ctx, REG_EBP), 90 | PIN_GetContextReg(ctx, REG_ESP), 91 | PIN_GetContextReg(ctx, REG_EIP)); 92 | // TODO: use the safe copy API 93 | UINT count = ((c == -1) ? ((PIN_GetContextReg(ctx, REG_EBP) - PIN_GetContextReg(ctx, REG_ESP)) / sizeof(VOID*)) + 1 : c); 94 | ADDRINT *ptr = (ADDRINT*)PIN_GetContextReg(ctx, REG_ESP); 95 | for (UINT32 i = 0; i < count; i++) { 96 | Log(TRUE, "[%08x]: %08x\n", ptr, *ptr); 97 | ptr++; 98 | } 99 | } 100 | #endif 101 | } -------------------------------------------------------------------------------- /ad.cpp: -------------------------------------------------------------------------------- 1 | #include "ad.h" 2 | 3 | // class statics 4 | std::tr1::unordered_set ad_hook::ad_functions; // List of watched potential aad functions 5 | 6 | // routine hook ad contructor 7 | ad_hook::ad_hook(enum TYPE t, string n, string d, AFUNPTR h) : type(t), name(n), hook(h), genre(ROUTINE) 8 | { 9 | // Convert dll string to lower case so hash function works as intended 10 | dll = Util::StrtoLower(d); 11 | } 12 | 13 | ad_hook::ad_hook(enum TYPE t, string n, string d, AFUNPTR h, AFUNPTR p) : type(t), name(n), hook(h), post(p), genre(ROUTINE) 14 | { 15 | // Convert dll string to lower case so hash function works as intended 16 | dll = Util::StrtoLower(d); 17 | } 18 | 19 | // instruction hook ad constructor 20 | ad_hook::ad_hook(enum TYPE t, string n, AFUNPTR h) : type(t), name(n), hook(h), dll(string("nope.dll")), genre(INSTRUCTION) {} 21 | 22 | //#define EMULATE_WINDOWS_BOTCHED_LONG_INT 23 | VOID ad_hook::HookInterrupt(ad_hook *adf, CONTEXT *ctxt, THREADID tid) 24 | { 25 | UINT8 op, intcode=3; // default to int 3 26 | EXCEPTION_INFO exceptInfo; 27 | ADDRINT ip = PIN_GetContextReg(ctxt, REG_PC); 28 | 29 | adf->UpdateTrace(tracer::GetTrace(tid)); 30 | // Fire a replacement interrupt to the OS if long int 31 | PIN_SafeCopy(&op, (VOID*)ip, sizeof(op)); 32 | if (op == 0xCD) { 33 | PIN_SafeCopy(&intcode, (VOID*)(ip + 1), sizeof(op)); 34 | if (intcode == 0x3 || intcode == 0x2d) { 35 | // Log and trace 36 | Util::Log(TRUE, "[INT] Using software interrupt (OP: #%x, INT #%x) at %p\n", op, intcode, ip); 37 | PIN_InitExceptionInfo(&exceptInfo, EXCEPTCODE_DBG_BREAKPOINT_TRAP, ip); 38 | #ifndef EMULATE_WINDOWS_BOTCHED_LONG_INT 39 | // Default: NOT emulating windows botched behavior 40 | #ifdef _WIN64 41 | PIN_SetContextReg(ctxt, REG_PC, ip + 3); // Context points after the interrupt instruction 42 | #else 43 | PIN_SetContextReg(ctxt, REG_PC, ip + 2); // Context points after the interrupt instruction 44 | #endif 45 | #else 46 | // EMULATING windows botched behavior 47 | #ifdef _WIN64 48 | PIN_SetContextReg(ctxt, REG_PC, ip + 2); // Context points in the middle of the instruction 49 | #else 50 | PIN_SetContextReg(ctxt, REG_PC, ip + 1); // Context points in the middle of the instruction 51 | #endif 52 | #endif 53 | PIN_RaiseException(ctxt, tid, &exceptInfo); 54 | } 55 | } 56 | // Log and trace 57 | Util::Log(TRUE, "[INTERRUPT] Using software interrupt (OP: #%x, INT #%x) at %p\n", op, intcode, ip); 58 | return; 59 | } 60 | 61 | VOID ad_hook::HookVirtualAlloc(ad_hook *adf, THREADID tid, WIN::SIZE_T dwSize, WIN::DWORD protect) 62 | { 63 | //Util::Log(TRUE, "[VirtualAlloc] TID %#x call at bbl %p (protect %08x)\n", tid, tracer::GetCurrentBBL(tid), protect); 64 | // Keep a per-thread ref to the call in order to link with post 65 | adf->allocs[tid].first = dwSize; 66 | adf->allocs[tid].second = protect; 67 | } 68 | 69 | VOID ad_hook::PostVirtualAlloc(ad_hook *adf, THREADID tid, ADDRINT mem, ADDRINT ret) 70 | { 71 | // Check call success and return address belongs to us 72 | if (mem && tracer::IsThisCode(ret)) { 73 | // Is there a ongoing call on that thread? 74 | auto &alloc = adf->allocs.find(tid); 75 | if (alloc != adf->allocs.end()) { 76 | // Update trace only if mem is GUARD or EXE 77 | if (alloc->second.second&(PAGE_GUARD|PAGE_ANYEXE)) { 78 | adf->UpdateTrace(tracer::GetTrace(tid)); 79 | } 80 | // Watch new code range 81 | tracer::addCodeRange(tid, mem, mem + alloc->second.first, alloc->second.second); 82 | } 83 | } 84 | // Clear the record 85 | adf->allocs.erase(tid); 86 | } 87 | 88 | VOID ad_hook::HookVirtualProtect(ad_hook *adf, THREADID tid, ADDRINT address, WIN::DWORD protect) 89 | { 90 | if (tracer::IsThisCode(tracer::GetCurrentBBL(tid)) && protect&(PAGE_GUARD|PAGE_ANYEXE)) { 91 | Util::Log(TRUE, "[VirtualProtect] TID %#x call (protect %08x)\n", tid, protect); 92 | // Only record trace if the protection is interesting 93 | adf->UpdateTrace(tracer::GetTrace(tid)); 94 | } 95 | tracer::UpdateCodeRangeProtect(address, protect); 96 | return; 97 | } 98 | 99 | VOID ad_hook::HookVirtualFree(ad_hook *adf, THREADID tid, WIN::LPVOID lpAddress) 100 | { 101 | //Util::Log(TRUE, "[VirtualFree] & = %08x\n", lpAddress); 102 | if (lpAddress) { 103 | tracer::removeCodeRange((ADDRINT)lpAddress); 104 | } 105 | } 106 | 107 | // This runs post function 108 | VOID ad_hook::HookNtQueryObject(ad_hook *adf, THREADID tid, ADDRINT handle, ADDRINT type, ADDRINT mem, ADDRINT size) 109 | { 110 | #define ObjectAllInformation 3 111 | if (type == ObjectAllInformation && size) { 112 | Util::Log(TRUE, "[ANTIDEBUG] Attempting to detect debugger via NtQueryObject (%#p,%#p,%#p)\n", type, mem, size); 113 | adf->UpdateTrace(tracer::GetTrace(tid)); 114 | } 115 | return; 116 | } 117 | 118 | VOID ad_hook::HookCloseHandle(ad_hook *adf, THREADID tid, ADDRINT handle) 119 | { 120 | // TODO: Less specific check 121 | #define BADHANDLE 0x12345 122 | 123 | if (handle == BADHANDLE) { 124 | adf->UpdateTrace(tracer::GetTrace(tid)); 125 | Util::Log(TRUE, "[ANTIDEBUG] Attempting to close invalid handle\n"); 126 | } 127 | else { 128 | // Util::Log(TRUE, "CloseHandle(%x)\n", handle); 129 | } 130 | } 131 | 132 | VOID ad_hook::UpdateTrace(vector& newtrace) 133 | { 134 | ADDRINT bblip = newtrace[BBL_BACKTRACE - 1]; 135 | //Util::Log(TRUE, "Hit at BB %#p\n", bblip); 136 | auto& backtrace = backtraces[bblip]; 137 | // Check that we do not already have a trace 138 | if (backtrace.empty()) { 139 | backtrace = newtrace; 140 | } 141 | else { 142 | // TODO: more analysis on different traces 143 | } 144 | } 145 | 146 | // Static hook 147 | VOID ad_hook::HookNtQueryInformationProcess(ad_hook *adf, THREADID tid, UINT32 handle, UINT32 flag) 148 | { 149 | #define ProcessDebugObjectHandle 0x1e 150 | #define ProcessDebugFlags 0x1f 151 | #define ProcessDebugPort 0x7 152 | 153 | if (flag == ProcessDebugObjectHandle) { 154 | adf->UpdateTrace(tracer::GetTrace(tid)); 155 | Util::Log(TRUE, "[ANTIDEBUG] Attempting to query process debug object\n"); 156 | } 157 | else if (flag == ProcessDebugFlags) { 158 | adf->UpdateTrace(tracer::GetTrace(tid)); 159 | Util::Log(TRUE, "[ANTIDEBUG] Attempting to query process debug flags\n"); 160 | } 161 | else if (flag == ProcessDebugPort) { 162 | adf->UpdateTrace(tracer::GetTrace(tid)); 163 | Util::Log(TRUE, "[ANTIDEBUG] Attempting to query process debug port\n"); 164 | } 165 | else { 166 | //Util::Log(TRUE, "NtQueryInformationProcess Flag = %x\n", flag); 167 | } 168 | return; 169 | } 170 | 171 | BOOL ad_hook::UpdateWatchedAD(string fnName, string imageName, ADDRINT address) 172 | { 173 | auto& it = ad_functions.find(ad_hook(UNDEFINED, fnName, imageName, NULL)); 174 | if (it != ad_functions.end()) { 175 | RTN routine = RTN_FindByAddress(address); 176 | if (RTN_Valid(routine)) { 177 | it->instrumentRoutine(routine); 178 | return TRUE; 179 | } 180 | else { 181 | Util::Log(TRUE, "INVALID RTN\n"); 182 | } 183 | } 184 | return FALSE; 185 | } 186 | 187 | VOID ad_hook::printAllAdBacktraces() 188 | { 189 | for (auto& ad : ad_functions) { 190 | ad.PrintTrace(FALSE); 191 | } 192 | return; 193 | } 194 | 195 | VOID ad_hook::instrumentRoutine(RTN rtn) const 196 | { 197 | RTN_Open(rtn); 198 | switch (type) { 199 | case CLOSEHANDLE: 200 | RTN_InsertCall(rtn, IPOINT_BEFORE, hook, 201 | IARG_PTR, this, 202 | IARG_THREAD_ID, 203 | IARG_FUNCARG_ENTRYPOINT_VALUE, 0, 204 | IARG_END); 205 | break; 206 | case NTQIP: 207 | RTN_InsertCall(rtn, IPOINT_BEFORE, hook, 208 | IARG_PTR, this, 209 | IARG_THREAD_ID, 210 | IARG_FUNCARG_ENTRYPOINT_VALUE, 0, 211 | IARG_FUNCARG_ENTRYPOINT_VALUE, 1, 212 | IARG_END); 213 | break; 214 | case NTQOB: 215 | RTN_InsertCall(rtn, IPOINT_AFTER, hook, 216 | IARG_PTR, this, 217 | IARG_THREAD_ID, 218 | IARG_FUNCARG_ENTRYPOINT_VALUE, 0, 219 | IARG_FUNCARG_ENTRYPOINT_VALUE, 1, 220 | IARG_FUNCARG_ENTRYPOINT_VALUE, 2, 221 | IARG_FUNCARG_ENTRYPOINT_VALUE, 3, 222 | IARG_END); 223 | break; 224 | case UEXCEPT: 225 | RTN_InsertCall(rtn, IPOINT_BEFORE, hook, 226 | IARG_PTR, this, 227 | IARG_THREAD_ID, 228 | IARG_REG_VALUE, REG_SP, 229 | IARG_END); 230 | break; 231 | case VMALLOC: 232 | RTN_InsertCall(rtn, IPOINT_BEFORE, hook, 233 | IARG_PTR, this, 234 | IARG_THREAD_ID, 235 | IARG_FUNCARG_ENTRYPOINT_VALUE, 1, 236 | IARG_FUNCARG_ENTRYPOINT_VALUE, 3, 237 | IARG_END); 238 | RTN_InsertCall(rtn, IPOINT_AFTER, post, 239 | IARG_PTR, this, 240 | IARG_THREAD_ID, 241 | IARG_FUNCRET_EXITPOINT_VALUE, 242 | IARG_RETURN_IP, 243 | IARG_END); 244 | break; 245 | case VMFREE: 246 | RTN_InsertCall(rtn, IPOINT_BEFORE, hook, 247 | IARG_PTR, this, 248 | IARG_THREAD_ID, 249 | IARG_FUNCARG_ENTRYPOINT_VALUE, 0, 250 | IARG_END); 251 | break; 252 | case VMPROT: 253 | RTN_InsertCall(rtn, IPOINT_BEFORE, hook, 254 | IARG_PTR, this, 255 | IARG_THREAD_ID, 256 | IARG_FUNCARG_ENTRYPOINT_VALUE, 0, 257 | IARG_FUNCARG_ENTRYPOINT_VALUE, 2, 258 | IARG_END); 259 | break; 260 | } 261 | RTN_Close(rtn); 262 | Util::Log(TRUE, "[HOOK] - %s\n", this->name.c_str()); 263 | return; 264 | } 265 | 266 | VOID ad_hook::instrumentInstruction(INS ins, VOID *v) 267 | { 268 | if (INS_IsInterrupt(ins)) { 269 | if (tracer::IsThisCode(INS_Address(ins))) { 270 | // Util::Log(FALSE, "[%#p] int %x\n", INS_Address(ins), INS_OperandImmediate(ins, 0)); 271 | tr1::unordered_set::iterator &ref = ad_functions.find(ad_hook(INTERRUPT, string("interrupts"), (AFUNPTR)HookInterrupt)); 272 | if (ref != ad_functions.end()) { 273 | INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)HookInterrupt, 274 | IARG_PTR, &*ref, 275 | IARG_CONTEXT, 276 | IARG_THREAD_ID, 277 | IARG_END); 278 | } 279 | } 280 | } 281 | // else if... 282 | return; 283 | } 284 | 285 | VOID ad_hook::setup() 286 | { 287 | // Routine based 288 | ad_functions.insert(ad_hook(CLOSEHANDLE, string("CloseHandle"), string("kernelbase.dll"), (AFUNPTR)HookCloseHandle)); 289 | ad_functions.insert(ad_hook(NTQIP, string("NtQueryInformationProcess"), string("ntdll.dll"), (AFUNPTR)HookNtQueryInformationProcess)); 290 | ad_functions.insert(ad_hook(NTQOB, string("NtQueryObject"), string("ntdll.dll"), (AFUNPTR)HookNtQueryObject)); 291 | ad_functions.insert(ad_hook(VMALLOC, string("VirtualAlloc"), string("kernelbase.dll"), (AFUNPTR)HookVirtualAlloc, (AFUNPTR)PostVirtualAlloc)); 292 | ad_functions.insert(ad_hook(VMFREE, string("VirtualFree"), string("kernelbase.dll"), (AFUNPTR)HookVirtualFree)); 293 | ad_functions.insert(ad_hook(VMPROT, string("VirtualProtect"), string("kernelbase.dll"), (AFUNPTR)HookVirtualProtect)); 294 | // ADD MORE HERE 295 | // Instruction based 296 | ad_functions.insert(ad_hook(INTERRUPT, string("interrupts"), (AFUNPTR)HookInterrupt)); 297 | INS_AddInstrumentFunction(instrumentInstruction, 0); 298 | return; 299 | } 300 | 301 | VOID ad_hook::PrintTrace(BOOL forward) const 302 | { 303 | Util::Log(FALSE, "BACKTRACES for %s\n", name.c_str()); 304 | for (auto& trace : backtraces) { 305 | Util::Log(FALSE, "[%#p] : ", trace.first); 306 | for (auto addr : trace.second) { 307 | Util::Log(FALSE, "-> %#p ", addr); 308 | } 309 | Util::Log(FALSE, "\n--------\n"); 310 | } 311 | Util::Log(TRUE, "----------------------\n"); 312 | return; 313 | } 314 | -------------------------------------------------------------------------------- /ad.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "common.h" 3 | #include "Tracer.h" 4 | 5 | class ad_hook 6 | { 7 | friend struct hash; 8 | private: 9 | enum GENRE { 10 | ROUTINE, 11 | INSTRUCTION 12 | }; 13 | enum TYPE { 14 | UNDEFINED, 15 | CLOSEHANDLE, 16 | NTQIP, 17 | INTERRUPT, 18 | NTQOB, 19 | UEXCEPT, 20 | VMALLOC, 21 | VMFREE, 22 | VMPROT 23 | }; 24 | GENRE genre; 25 | TYPE type; 26 | string name; 27 | string dll; 28 | // For instrumenting 29 | AFUNPTR hook; 30 | AFUNPTR post; 31 | UINT nbArgs; 32 | // Tracking 33 | tr1::unordered_map> backtraces; 34 | vector forwardtrace; 35 | tr1::unordered_map> allocs; 36 | // List of all watched aad functions 37 | static std::tr1::unordered_set ad_functions; 38 | VOID ad_hook::UpdateTrace(vector& newtrace); 39 | public: 40 | // Constructor 41 | ad_hook(enum TYPE, string, string, AFUNPTR); 42 | ad_hook(enum TYPE, string, string, AFUNPTR, AFUNPTR); 43 | ad_hook(enum TYPE, string, AFUNPTR); 44 | // Members 45 | VOID instrumentRoutine(RTN) const; 46 | VOID PrintTrace(BOOL) const; 47 | // Statics 48 | static VOID setup(); 49 | static BOOL UpdateWatchedAD(string, string, ADDRINT); 50 | static VOID printAllAdBacktraces(); 51 | static VOID instrumentInstruction(INS, VOID*); 52 | // Hooks (have to be static) 53 | static VOID HookCloseHandle(ad_hook*, THREADID, ADDRINT); 54 | static VOID HookNtQueryInformationProcess(ad_hook*, THREADID, UINT32, UINT32); 55 | static VOID HookInterrupt(ad_hook*, CONTEXT*, THREADID); 56 | static VOID HookNtQueryObject(ad_hook*, THREADID, ADDRINT, ADDRINT, ADDRINT, ADDRINT); 57 | static VOID HookVirtualAlloc(ad_hook*, THREADID, WIN::SIZE_T, WIN::DWORD); 58 | static VOID HookVirtualProtect(ad_hook*, THREADID, ADDRINT, WIN::DWORD); 59 | static VOID HookVirtualFree(ad_hook*, THREADID, WIN::LPVOID); 60 | static VOID PostVirtualAlloc(ad_hook*, THREADID, ADDRINT, ADDRINT); 61 | // Equal operator for set 62 | bool operator==(const ad_hook &other) const { 63 | return type == other.type 64 | || (name==other.name && dll==other.dll); 65 | } 66 | }; 67 | // Hash functor for set 68 | template <> 69 | struct hash { 70 | std::size_t operator()(const ad_hook& k) const { 71 | return (hash()(k.name) ^ hash()(k.dll)); 72 | } 73 | }; -------------------------------------------------------------------------------- /common.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // Standard C 4 | #include 5 | #include 6 | #include 7 | // C++ 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | // Pin 16 | #include "pin.H" 17 | 18 | // Memory access types 19 | #define READ 0 20 | #define WRITE 1 21 | #define OTHER 2 22 | 23 | typedef unsigned long DWORD; 24 | namespace WIN { 25 | #pragma once 26 | #define _WINDOWS_H_PATH_ C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\um 27 | #include 28 | } 29 | 30 | #define PAGE_ANYEXE (PAGE_EXECUTE|PAGE_EXECUTE_READ|PAGE_EXECUTE_READWRITE|PAGE_EXECUTE_WRITECOPY) 31 | 32 | #ifdef _WIN64 33 | #define REG_PC REG_RIP 34 | #define REG_SP REG_RSP 35 | #else: 36 | #define REG_PC REG_EIP 37 | #define REG_SP REG_ESP 38 | #endif 39 | 40 | namespace Util { 41 | // Vars 42 | extern FILE *log; 43 | extern time_t tStart; 44 | extern string imageName; 45 | extern ADDRINT base, start, end, entry; 46 | // Funcs 47 | UINT64 READ_SIZE(ADDRINT, size_t); 48 | VOID loginit(string); 49 | VOID logend(); 50 | VOID Log(BOOL, const char* fmt...); 51 | VOID startTimer(); 52 | double queryElapsedTime(BOOL); 53 | string StrtoLower(string); 54 | VOID printContext(const CONTEXT*, UINT32); 55 | } -------------------------------------------------------------------------------- /icpin_importer.py: -------------------------------------------------------------------------------- 1 | import sys, re 2 | 3 | read_regex = re.compile(r'^#\d+] .*?\+(.*): R \[\+(.*?) - .*?\) - (.*) bytes$') 4 | write_regex = re.compile(r'^#\d+] .*?\+(.*): W \[\+(.*?)\] = (.*) \(\d+ values\)') 5 | 6 | class Gadget(object): 7 | 8 | def __init__(self, ip): 9 | self.ip=ip 10 | 11 | def __hash__(self): 12 | return self.ip 13 | 14 | class ReadGadget(Gadget): 15 | 16 | def __init__(self, ip): 17 | super().__init__(ip) 18 | self.reads = {} 19 | 20 | def update(self, offset, size): 21 | assert offset not in self.reads 22 | self.reads[offset] = size 23 | 24 | def __repr__(self): 25 | return f'{self.ip:X} READ:'+'\n'.join(f'\t{offset:X} - {offset+size:X}' for offset, size in self.reads.items()) 26 | 27 | class WriteGadget(Gadget): 28 | 29 | def __init__(self, ip): 30 | super().__init__(ip) 31 | self.writes = {} 32 | 33 | def update(self, offset, values): 34 | self.writes.setdefault(offset, []).extend(values) 35 | 36 | def __repr__(self): 37 | ret = f'{self.ip:X} WRITE: {len(self.writes)} ' + ('values\n' if len(self.writes)>1 else 'value\n') 38 | ret += '\n'.join(f'\t{offset:X}: [' + ', '.join(f'{val:X}' for val in values) + ']' \ 39 | for offset, values in self.writes.items()) 40 | return ret 41 | 42 | class Importer(object): 43 | 44 | def __init__(self, filename): 45 | self.filename = filename 46 | 47 | def loadDB(self): 48 | gadgets = {} 49 | with open(self.filename, 'r') as f: 50 | for line in f.readlines(): 51 | m = read_regex.match(line) 52 | if m: 53 | ip = int(m.group(1), 16) 54 | gadgets.setdefault(ip, ReadGadget(ip)).update(int(m.group(2), 16), int(m.group(3), 16)) 55 | else: 56 | m = write_regex.match(line) 57 | if m: 58 | ip = int(m.group(1), 16) 59 | values = [int(v, 16) for v in m.group(3).split()] 60 | gadgets.setdefault(ip, WriteGadget(ip)).update(int(m.group(2), 16), values) 61 | return gadgets 62 | 63 | if __name__ == '__main__': 64 | imp = Importer(sys.argv[1]) 65 | gadgets = imp.loadDB() 66 | for g in gadgets.values(): 67 | print(g) 68 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | ############################################################## 2 | # 3 | # DO NOT EDIT THIS FILE! 4 | # 5 | ############################################################## 6 | 7 | # If the tool is built out of the kit, PIN_ROOT must be specified in the make invocation and point to the kit root. 8 | ifdef PIN_ROOT 9 | CONFIG_ROOT := $(PIN_ROOT)/source/tools/Config 10 | else 11 | CONFIG_ROOT := ../Config 12 | endif 13 | include $(CONFIG_ROOT)/makefile.config 14 | include makefile.rules 15 | include $(TOOLS_ROOT)/Config/makefile.default.rules 16 | 17 | ############################################################## 18 | # 19 | # DO NOT EDIT THIS FILE! 20 | # 21 | ############################################################## 22 | -------------------------------------------------------------------------------- /makefile.rules: -------------------------------------------------------------------------------- 1 | ############################################################## 2 | # 3 | # This file includes all the test targets as well as all the 4 | # non-default build rules and test recipes. 5 | # 6 | ############################################################## 7 | 8 | 9 | ############################################################## 10 | # 11 | # Test targets 12 | # 13 | ############################################################## 14 | 15 | ###### Place all generic definitions here ###### 16 | 17 | # This defines tests which run tools of the same name. This is simply for convenience to avoid 18 | # defining the test name twice (once in TOOL_ROOTS and again in TEST_ROOTS). 19 | # Tests defined here should not be defined in TOOL_ROOTS and TEST_ROOTS. 20 | TEST_TOOL_ROOTS := MyPinTool 21 | 22 | # This defines the tests to be run that were not already defined in TEST_TOOL_ROOTS. 23 | TEST_ROOTS := 24 | 25 | # This defines the tools which will be run during the the tests, and were not already defined in 26 | # TEST_TOOL_ROOTS. 27 | TOOL_ROOTS := 28 | 29 | # This defines the static analysis tools which will be run during the the tests. They should not 30 | # be defined in TEST_TOOL_ROOTS. If a test with the same name exists, it should be defined in 31 | # TEST_ROOTS. 32 | # Note: Static analysis tools are in fact executables linked with the Pin Static Analysis Library. 33 | # This library provides a subset of the Pin APIs which allows the tool to perform static analysis 34 | # of an application or dll. Pin itself is not used when this tool runs. 35 | SA_TOOL_ROOTS := 36 | 37 | # This defines all the applications that will be run during the tests. 38 | APP_ROOTS := 39 | 40 | # This defines any additional object files that need to be compiled. 41 | OBJECT_ROOTS := 42 | 43 | # This defines any additional dlls (shared objects), other than the pintools, that need to be compiled. 44 | DLL_ROOTS := 45 | 46 | # This defines any static libraries (archives), that need to be built. 47 | LIB_ROOTS := 48 | 49 | ###### Define the sanity subset ###### 50 | 51 | # This defines the list of tests that should run in sanity. It should include all the tests listed in 52 | # TEST_TOOL_ROOTS and TEST_ROOTS excluding only unstable tests. 53 | SANITY_SUBSET := $(TEST_TOOL_ROOTS) $(TEST_ROOTS) 54 | 55 | 56 | ############################################################## 57 | # 58 | # Test recipes 59 | # 60 | ############################################################## 61 | 62 | # This section contains recipes for tests other than the default. 63 | # See makefile.default.rules for the default test rules. 64 | # All tests in this section should adhere to the naming convention: .test 65 | 66 | 67 | ############################################################## 68 | # 69 | # Build rules 70 | # 71 | ############################################################## 72 | 73 | # This section contains the build rules for all binaries that have special build rules. 74 | # See makefile.default.rules for the default build rules. 75 | -------------------------------------------------------------------------------- /memaccess.cpp: -------------------------------------------------------------------------------- 1 | #include "memaccess.h" 2 | 3 | volatile size_t Gadget::current = 0; 4 | 5 | // ReadGadget 6 | 7 | ReadGadget::ReadGadget(ADDRINT i, ADDRINT start, ADDRINT end) : Gadget(READ, i) { 8 | range.first = start; 9 | range.second = end; 10 | } 11 | 12 | VOID ReadGadget::update_range(ADDRINT start, ADDRINT end) { 13 | if (start < range.first) { 14 | range.first = start; 15 | } 16 | if (end > range.second) { 17 | range.second = end; 18 | } 19 | } 20 | 21 | VOID ReadGadget::print() const { 22 | size_t len = range.second - range.first; 23 | ADDRINT base = Util::base; 24 | Util::Log(FALSE, "#%.4lu] %s+%#lx: R [+%#lx - %#lx) - %#lx bytes\n", firstSeen, Util::imageName.c_str(), ip - base, range.first - base, range.second - base, range.second - range.first); 25 | Util::Log(FALSE, "----------------------------------------\n"); 26 | return; 27 | } 28 | 29 | // WriteGadget 30 | 31 | WriteGadget::WriteGadget(ADDRINT i, ADDRINT o, UINT64 val, size_t l) : Gadget(WRITE, i) { 32 | len = l; 33 | offset_values[o].push_back(val); 34 | } 35 | 36 | VOID WriteGadget::update_offset_values(ADDRINT address, UINT64 value) { 37 | offset_values[address].push_back(value); 38 | } 39 | 40 | VOID WriteGadget::print() const { 41 | ADDRINT base = Util::base; 42 | for (const auto& p : offset_values) { 43 | Util::Log(FALSE, "#%.4lu] %s+%#lx: W [+%#lx] = ", firstSeen, Util::imageName.c_str(), ADDRINT(ip) - base, p.first - base); 44 | for (const auto& value : p.second) { 45 | Util::Log(FALSE, "0x%.*lx ", len << 1, value); 46 | } 47 | Util::Log(FALSE, " (%lu values)\n", p.second.size()); 48 | } 49 | Util::Log(FALSE, "----------------------------------------\n"); 50 | return; 51 | } -------------------------------------------------------------------------------- /memaccess.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "common.h" 3 | 4 | class WriteGadget; 5 | 6 | class Gadget { 7 | public: 8 | // Vars 9 | ADDRINT ip; 10 | INT type; 11 | volatile static size_t current; 12 | size_t firstSeen; 13 | // Funcs 14 | Gadget(INT ty, ADDRINT i) : ip(i), type(ty), firstSeen(current) {} 15 | virtual VOID print() const = 0; 16 | }; 17 | 18 | class ReadGadget : public Gadget 19 | { 20 | public: 21 | // [start, end) 22 | pair range; 23 | ReadGadget(ADDRINT, ADDRINT, ADDRINT); 24 | VOID update_range(ADDRINT, ADDRINT); 25 | VOID print() const; 26 | }; 27 | 28 | class WriteGadget : public Gadget 29 | { 30 | public: 31 | size_t len; 32 | tr1::unordered_map> offset_values; 33 | WriteGadget(ADDRINT, ADDRINT, UINT64, size_t); 34 | VOID update_offset_values(ADDRINT, UINT64); 35 | VOID print() const; 36 | }; 37 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # ICPin # 2 | #### An Integrity-Check Monitoring Pintool #### 3 | 4 | ## What ## 5 | A pintool that records the reads and writes to the executable in memory. It 6 | also tracks dynamically executed code and handles some antidebug checks (it is 7 | immune to most antidebug by pintool`s design) and outputs backtraces of watched 8 | behavior. 9 | 10 | ## How ## 11 | ### Building ### 12 | * Download MSCV version from https://software.intel.com/en-us/articles/pin-a-binary-instrumentation-tool-downloads 13 | * Open MyPinTool.sln in Visual Studio 14 | * Adjust the include and link directories to match your pintool install location 15 | * Build the solution 16 | 17 | ### Running ### 18 | `pin -t path/to/ICPin.dll -- /path/to/target/executable` 19 | 20 | ### Importing Results In Python ### 21 | ```python 22 | from icpin_importer import Importer 23 | 24 | imp = Importer('/path/to/pinatrace.out') 25 | gadgets = imp.loadDB() 26 | ``` 27 | 28 | ### Ouput Sample (edited) ### 29 | ``` 30 | [LOAD] c:\Program Files (x86)\ExEPath\Exe.exe [0x620000 - 0xc89fff] 31 | [LOAD] C:\WINDOWS\SYSTEM32\MSCOREE.DLL [0x738c0000 - 0x73918fff] 32 | [LOAD] C:\WINDOWS\System32\KERNEL32.dll [0x74c10000 - 0x74ceffff] 33 | [LOAD] C:\WINDOWS\System32\KERNELBASE.dll [0x74e30000 - 0x74fd0fff] 34 | [HOOK] - CloseHandle 35 | [HOOK] - VirtualFree 36 | [HOOK] - VirtualAlloc 37 | [HOOK] - VirtualProtect 38 | [LOAD] C:\WINDOWS\SYSTEM32\ntdll.dll [0x77060000 - 0x771e1fff] 39 | [HOOK] - NtQueryObject 40 | [HOOK] - NtQueryInformationProcess 41 | [HOOK] - KiUserExceptionDispatcher 42 | [TIME] Initial instrumentation took 0.000000 seconds 43 | [LOAD] C:\WINDOWS\System32\ADVAPI32.dll [0x743d0000 - 0x74446fff] 44 | [LOAD] C:\WINDOWS\System32\msvcrt.dll [0x75310000 - 0x753cdfff] 45 | [LOAD] C:\WINDOWS\System32\sechost.dll [0x753d0000 - 0x75410fff] 46 | [LOAD] C:\WINDOWS\System32\RPCRT4.dll [0x73ba0000 - 0x73c60fff] 47 | ---------------------- 48 | [ICPin] Using software interrupts to detect debugger 49 | [EXCEPTION] code: 0x80000003 ip: 0x53ce0168 -> 0x770d0020 50 | [KiUserExceptionDispatcher] Back from km, context EIP = 53ce0168 -> 53ce0169 51 | ---------------------- 52 | TIME: Running instrumented took 1497.00 seconds 53 | GADGET LIST ------------------------------ 54 | ---------------------------------------- 55 | #0021] Exe.dll+0x478945: R [+0x47a264 - 0x47a366) - 0x102 bytes 56 | ---------------------------------------- 57 | #0022] Exe.dll+0x29eb2f: R [+0x29eb91 - 0x29ebc1) - 0x30 bytes 58 | ---------------------------------------- 59 | #0023] Exe.dll+0x47257c: R [+0x472776 - 0x4727f4) - 0x7e bytes 60 | ---------------------------------------- 61 | #0058] Exe.dll+0xd39bd: R [+0x3ae7c - 0x4312c) - 0x82b0 bytes 62 | ---------------------------------------- 63 | #0077] Exe.dll+0xdfceb: R [+0x1762fc - 0x17f228) - 0x8f2c bytes 64 | ---------------------------------------- 65 | #0096] Exe.dll+0xe88b5: R [+0x37e18 - 0x40b50) - 0x8d38 bytes 66 | ---------------------------------------- 67 | Total: 942 gadgets 68 | BACKTRACES for NtQueryInformationProcess 69 | ---------------------- 70 | BACKTRACES for interrupts 71 | [0x53ce0168] : -> 0x53d9a667 -> 0x53d9a660 -> 0x53d9a674 -> 0x53d9a64b -> 0x53d9a654 -> 0x53d9a667 -> 0x53d9a660 -> 0x53d9a667 -> 0x53d9a660 -> 0x53d9a667 -> 0x53d9a660 -> 0x53d9a667 -> 0x53d9a660 -> 0x53d9a674 -> 0x53d9a67a -> 0x53ce62a9 -> 0x53ce65bf -> 0x53ce5d50 -> 0x53ce5d59 -> 0x53ce5f6c -> 0x53ce5f78 -> 0x53ce5fd5 -> 0x53ce60ff -> 0x53ce6283 -> 0x53ce628f -> 0x53ce653f -> 0x53ce0fe0 -> 0x53ce0ff5 -> 0x53ce10a0 -> 0x53ce6544 -> 0x53d99710 -> 0x53d99721 -> 0x53ce6554 -> 0x53ce65bf -> 0x53ce5d50 -> 0x53ce5d59 -> 0x53ce5f6c -> 0x53ce5f78 -> 0x53ce5f7f -> 0x53ce60ff -> 0x53ce6283 -> 0x53ce65bf -> 0x53ce65cb -> 0x53ce65d2 -> 0x53ce65dd -> 0x53ce65e0 -> 0x53ce65e5 -> 0x53ce65bf -> 0x53ce5d50 -> 0x53ce5d59 -> 0x53ce5f6c -> 0x53ce60ff -> 0x53ce610b -> 0x53ce6275 -> 0x53ce65bf -> 0x53ce5d50 -> 0x53ce5d59 -> 0x53ce5f6c -> 0x53ce60ff -> 0x53ce610b -> 0x53ce61f6 -> 0x53ce6283 -> 0x53ce65bf -> 0x53ce5d50 -> 0x53ce5d59 -> 0x53ce5f6c -> 0x53ce5f78 -> 0x53ce60d3 -> 0x53ce60ff -> 0x53ce610b -> 0x53ce61dd -> 0x53ce6283 -> 0x53ce65bf -> 0x53ce5d50 -> 0x53ce5d59 -> 0x53ce5f6c -> 0x53ce5f78 -> 0x53ce60a0 -> 0x53ce60b4 -> 0x53ce0168 72 | -------- 73 | [0x540edb95] : -> 0x540ed80b -> 0x540ed983 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed383 -> 0x540ed38f -> 0x540ed63c -> 0x540ed678 -> 0x540ed80b -> 0x540ed983 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed383 -> 0x540ed38f -> 0x540ed4b1 -> 0x540ed678 -> 0x540ed80b -> 0x540ed983 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed383 -> 0x540ed38f -> 0x540ed482 -> 0x540ed678 -> 0x540ed80b -> 0x540ed983 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed383 -> 0x540ed38f -> 0x540ed63c -> 0x540ed678 -> 0x540ed80b -> 0x540ed983 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed0c7 -> 0x540ed0d8 -> 0x540ed0ef -> 0x540ed383 -> 0x540ed38f -> 0x540ed3a8 -> 0x540ed678 -> 0x540ed80b -> 0x540ed983 -> 0x540ed98f -> 0x540ed996 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed383 -> 0x540ed678 -> 0x540ed80b -> 0x540ed983 -> 0x540ed98f -> 0x540eda1c -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed0c7 -> 0x540ed68b -> 0x540ed383 -> 0x540ed38f -> 0x540ed396 -> 0x540ed678 -> 0x540ed80b -> 0x540ed983 -> 0x540ed98f -> 0x540ed9a6 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed383 -> 0x540ed678 -> 0x540ed684 -> 0x540ed7fe -> 0x540ed983 -> 0x540ed0b5 -> 0x540ed0be -> 0x540ed0c7 -> 0x540ed2c8 -> 0x540ed2e4 -> 0x540edb95 74 | -------- 75 | ---------------------- 76 | #DONE (0) 77 | ``` 78 | 79 | ## References ## 80 | https://software.intel.com/sites/landingpage/pintool/docs/81205/Pin/html/ 81 | --------------------------------------------------------------------------------