├── .gitignore
├── README.md
├── control-gui
├── control-gui.xcodeproj
│ └── project.pbxproj
├── control-gui
│ ├── Images.xcassets
│ │ └── AppIcon.appiconset
│ │ │ ├── Contents.json
│ │ │ ├── icon_128x128.png
│ │ │ ├── icon_128x128@2x.png
│ │ │ ├── icon_16x16.png
│ │ │ ├── icon_16x16@2x.png
│ │ │ ├── icon_256x256.png
│ │ │ ├── icon_256x256@2x.png
│ │ │ ├── icon_32x32.png
│ │ │ ├── icon_32x32@2x.png
│ │ │ ├── icon_512x512.png
│ │ │ └── icon_512x512@2x.png
│ ├── cat-clipart-7.jpg
│ ├── cat_fish.png
│ ├── control-gui-Info.plist
│ ├── control-gui-Prefix.pch
│ ├── controlAppDelegate.h
│ ├── controlAppDelegate.m
│ ├── en.lproj
│ │ ├── Credits.rtf
│ │ ├── InfoPlist.strings
│ │ └── MainMenu.xib
│ ├── kernelControl.h
│ ├── kernelControl.m
│ ├── main.m
│ ├── status-available.tiff
│ └── status-away.tiff
└── control-guiTests
│ ├── control-guiTests-Info.plist
│ ├── control_guiTests.m
│ └── en.lproj
│ └── InfoPlist.strings
├── control
├── control.xcodeproj
│ ├── project.pbxproj
│ └── project.xcworkspace
│ │ └── contents.xcworkspacedata
└── control
│ └── main.c
├── distorm
├── COPYING
├── MANIFEST
├── MANIFEST.in
├── README.md
├── disOps
│ ├── disOps.py
│ ├── x86db.py
│ ├── x86header.py
│ └── x86sets.py
├── examples
│ ├── cs
│ │ ├── TestdiStorm
│ │ │ ├── Program.cs
│ │ │ ├── Properties
│ │ │ │ └── AssemblyInfo.cs
│ │ │ └── TestdiStorm.csproj
│ │ ├── distorm-net.sln
│ │ ├── distorm-net
│ │ │ ├── CodeInfo.cs
│ │ │ ├── DecodedInst.cs
│ │ │ ├── DecodedResult.cs
│ │ │ ├── DecomposedInst.cs
│ │ │ ├── DecomposedResult.cs
│ │ │ ├── Opcodes.cs
│ │ │ ├── Opcodes.tt
│ │ │ ├── Operand.cs
│ │ │ ├── Properties
│ │ │ │ └── AssemblyInfo.cs
│ │ │ ├── diStorm3.cs
│ │ │ └── distorm-net.csproj
│ │ └── readme
│ ├── ddk
│ │ ├── README
│ │ ├── distorm.ini
│ │ ├── dummy.c
│ │ ├── main.c
│ │ ├── makefile
│ │ └── sources
│ ├── java
│ │ ├── Makefile
│ │ ├── distorm
│ │ │ ├── .classpath
│ │ │ ├── .project
│ │ │ ├── .settings
│ │ │ │ └── org.eclipse.jdt.core.prefs
│ │ │ └── src
│ │ │ │ ├── Main.java
│ │ │ │ └── diStorm3
│ │ │ │ ├── CodeInfo.java
│ │ │ │ ├── DecodedInst.java
│ │ │ │ ├── DecodedResult.java
│ │ │ │ ├── DecomposedInst.java
│ │ │ │ ├── DecomposedResult.java
│ │ │ │ ├── OpcodeEnum.java
│ │ │ │ ├── Opcodes.java
│ │ │ │ ├── Operand.java
│ │ │ │ └── distorm3.java
│ │ ├── jdistorm.c
│ │ ├── jdistorm.h
│ │ ├── jdistorm.sln
│ │ └── jdistorm.vcproj
│ ├── linux
│ │ ├── Makefile
│ │ └── main.c
│ ├── tests
│ │ ├── Makefile
│ │ ├── main.cpp
│ │ ├── main.py
│ │ ├── test_distorm3.py
│ │ ├── tests.sln
│ │ ├── tests.vcxproj
│ │ └── tests.vcxproj.filters
│ └── win32
│ │ ├── disasm.sln
│ │ ├── disasm.vcxproj
│ │ ├── disasm.vcxproj.filters
│ │ └── main.cpp
├── include
│ ├── distorm.h
│ └── mnemonics.h
├── make
│ ├── linux
│ │ └── Makefile
│ ├── mac
│ │ └── Makefile
│ └── win32
│ │ ├── cdistorm.vcxproj
│ │ ├── cdistorm.vcxproj.filters
│ │ ├── distorm.sln
│ │ ├── resource.h
│ │ └── resource.rc
├── python
│ └── distorm3
│ │ ├── __init__.py
│ │ └── sample.py
├── setup.cfg
├── setup.py
└── src
│ ├── config.h
│ ├── decoder.c
│ ├── decoder.h
│ ├── distorm.c
│ ├── instructions.c
│ ├── instructions.h
│ ├── insts.c
│ ├── insts.h
│ ├── mnemonics.c
│ ├── operands.c
│ ├── operands.h
│ ├── prefix.c
│ ├── prefix.h
│ ├── textdefs.c
│ ├── textdefs.h
│ ├── wstring.c
│ ├── wstring.h
│ └── x86defs.h
├── kext
├── Info.plist
├── README.md
├── antidebug.c
├── antidebug.h
├── cpu_protections.c
├── cpu_protections.h
├── disasm_utils.c
├── disasm_utils.h
├── en.lproj
│ └── InfoPlist.strings
├── idt.c
├── idt.h
├── kernel_control.c
├── kernel_control.h
├── kernel_info.c
├── kernel_info.h
├── my_data_definitions.h
├── onyx-the-black-cat.xcodeproj
│ ├── project.pbxproj
│ └── project.xcworkspace
│ │ └── contents.xcworkspacedata
├── onyx_the_black_cat.c
├── patchkernel.c
├── patchkernel.h
├── proc.h
├── shared_data.h
├── syscall.h
├── sysent.c
├── sysent.h
├── sysproto.h
└── utlist.h
├── onyx-the-black-cat.xcworkspace
├── contents.xcworkspacedata
└── xcshareddata
│ └── IDEWorkspaceChecks.plist
└── tests
├── sysctlantidebug.c
├── taskforpid.c
├── testptrace.c
└── testptraceTrap.c
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | #
3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
4 |
5 | ## User settings
6 | xcuserdata/
7 |
8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
9 | *.xcscmblueprint
10 | *.xccheckout
11 |
12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
13 | build/
14 | DerivedData/
15 | *.moved-aside
16 | *.pbxuser
17 | !default.pbxuser
18 | *.mode1v3
19 | !default.mode1v3
20 | *.mode2v3
21 | !default.mode2v3
22 | *.perspectivev3
23 | !default.perspectivev3
24 |
25 | ## Xcode Patch
26 | *.xcodeproj/*
27 | !*.xcodeproj/project.pbxproj
28 | !*.xcodeproj/xcshareddata/
29 | !*.xcworkspace/contents.xcworkspacedata
30 | /*.gcno
31 |
32 | .DS_Store
33 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Onyx The Black Cat
2 | ==================
3 |
4 | Copyright © fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
5 | All rights reserved.
6 |
7 | Introduction
8 | -------------------------------------------------------------------------------
9 | A kernel module for Intel Mac OS X that will provide you with some
10 | anti anti-debug protection and other features.
11 |
12 | This module will allow you to debug programs which use these tricks without
13 | need to patch them (no need to patch lots of anti-debug calls and maybe
14 | checksum code).
15 | Compatible with all OS X versions since Snow Leopard (older probably supported!).
16 | Mavericks introduces kernel extension code signing but this still works
17 | if you load it manually.
18 |
19 | Features can be enabled or disabled using the control program. By default
20 | everything is disabled. This util requires root privileges to run. If you
21 | want to run it as normal user you can remove CTL_FLAG_PRIVILEGED from
22 | kernel_control.c source file.
23 |
24 | This code uses diStorm as its disassembler.
25 | Due to licensing differences its files are not included.
26 | You can download diStorm from:
27 | http://code.google.com/p/distorm/ and include the missing files.
28 | The only required change is to define SUPPORT_64BIT_OFFSET. You can do it
29 | either at diStorm's config.h file or at Xcode project settings.
30 |
31 | Included are small test programs to test the anti-debug tricks, and other
32 | features.
33 |
34 | The weird name is based on a big black cat named Onyx who is always hiding and
35 | running from me :).
36 | "I'm gonna hug you and kiss you and love you forever (and never use you up)"
37 | Elmyra Fudd.
38 |
39 | I hope it's useful for you. It is for me.
40 | If you find/know any other gdb anti-debug tricks, please drop me an email with
41 | some details so I can add them to the module.
42 |
43 | Have fun.
44 | fG!
45 |
46 | Installation
47 | -------------------------------------------------------------------------------
48 | Copy onyx-the-black-cat.kext to /System/Library/Extensions
49 | (sudo cp -rf onyx-the-black-cat.kext /System/Library/Extensions)
50 |
51 | and then load the module with kextload
52 | (sudo kextload /System/Library/Extensions/onyx-the-black-cat.kext)
53 |
54 | Unload module with kextunload
55 | (sudo kextunload /System/Library/Extensions/onyx-the-black-cat.kext)
56 |
57 | Use the control program to enable/disable features. Everything is disabled by
58 | default.
59 |
60 | You can check dmesg or /var/log/system.log for debug messages and anti-debug
61 | hits.
62 |
63 | Known Problems
64 | -------------------------------------------------------------------------------
65 | Still some ugly code :-)
66 |
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "size" : "16x16",
5 | "idiom" : "mac",
6 | "filename" : "icon_16x16.png",
7 | "scale" : "1x"
8 | },
9 | {
10 | "size" : "16x16",
11 | "idiom" : "mac",
12 | "filename" : "icon_16x16@2x.png",
13 | "scale" : "2x"
14 | },
15 | {
16 | "size" : "32x32",
17 | "idiom" : "mac",
18 | "filename" : "icon_32x32.png",
19 | "scale" : "1x"
20 | },
21 | {
22 | "size" : "32x32",
23 | "idiom" : "mac",
24 | "filename" : "icon_32x32@2x.png",
25 | "scale" : "2x"
26 | },
27 | {
28 | "size" : "128x128",
29 | "idiom" : "mac",
30 | "filename" : "icon_128x128.png",
31 | "scale" : "1x"
32 | },
33 | {
34 | "size" : "128x128",
35 | "idiom" : "mac",
36 | "filename" : "icon_128x128@2x.png",
37 | "scale" : "2x"
38 | },
39 | {
40 | "size" : "256x256",
41 | "idiom" : "mac",
42 | "filename" : "icon_256x256.png",
43 | "scale" : "1x"
44 | },
45 | {
46 | "size" : "256x256",
47 | "idiom" : "mac",
48 | "filename" : "icon_256x256@2x.png",
49 | "scale" : "2x"
50 | },
51 | {
52 | "size" : "512x512",
53 | "idiom" : "mac",
54 | "filename" : "icon_512x512.png",
55 | "scale" : "1x"
56 | },
57 | {
58 | "size" : "512x512",
59 | "idiom" : "mac",
60 | "filename" : "icon_512x512@2x.png",
61 | "scale" : "2x"
62 | }
63 | ],
64 | "info" : {
65 | "version" : 1,
66 | "author" : "xcode"
67 | }
68 | }
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_128x128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_128x128.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_128x128@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_128x128@2x.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_16x16.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_16x16@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_16x16@2x.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_256x256.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_256x256.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_256x256@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_256x256@2x.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_32x32.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_32x32@2x.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_512x512.png
--------------------------------------------------------------------------------
/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_512x512@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/Images.xcassets/AppIcon.appiconset/icon_512x512@2x.png
--------------------------------------------------------------------------------
/control-gui/control-gui/cat-clipart-7.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/cat-clipart-7.jpg
--------------------------------------------------------------------------------
/control-gui/control-gui/cat_fish.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/cat_fish.png
--------------------------------------------------------------------------------
/control-gui/control-gui/control-gui-Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | ${EXECUTABLE_NAME}
9 | CFBundleIconFile
10 |
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | ${PRODUCT_NAME}
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | 1.0
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | 1
25 | LSMinimumSystemVersion
26 | ${MACOSX_DEPLOYMENT_TARGET}
27 | NSHumanReadableCopyright
28 | Copyright © 2014 Put.as. All rights reserved.
29 | NSMainNibFile
30 | MainMenu
31 | NSPrincipalClass
32 | NSApplication
33 |
34 |
35 |
--------------------------------------------------------------------------------
/control-gui/control-gui/control-gui-Prefix.pch:
--------------------------------------------------------------------------------
1 | //
2 | // Prefix header
3 | //
4 | // The contents of this file are implicitly included at the beginning of every source file.
5 | //
6 |
7 | #ifdef __OBJC__
8 | #import
9 | #endif
10 |
--------------------------------------------------------------------------------
/control-gui/control-gui/controlAppDelegate.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * controlAppDelegate.h
36 | *
37 | */
38 |
39 | #import
40 | #import "kernelControl.h"
41 |
42 | @interface controlAppDelegate : NSObject
43 |
44 | @property (assign) IBOutlet NSWindow *window;
45 | @property (weak) IBOutlet NSTextField *statusField;
46 | @property (weak) IBOutlet NSButton *connectButton;
47 | @property (weak) IBOutlet NSButton *disconnectButton;
48 | @property (weak) IBOutlet NSImageView *status;
49 | @property (weak) IBOutlet NSButton *ptraceButton;
50 | @property (weak) IBOutlet NSButton *sysctlButton;
51 | @property (weak) IBOutlet NSButton *resumeFlagButton;
52 | @property (weak) IBOutlet NSButton *taskForPidButton;
53 | @property (weak) IBOutlet NSButton *kauthButton;
54 | @property (weak) IBOutlet NSButton *singleStepButton;
55 |
56 | - (IBAction)pressConnect:(id)sender;
57 | - (IBAction)pressDisconnect:(id)sender;
58 | - (IBAction)takePtrace:(id)sender;
59 | - (IBAction)takeSysctl:(id)sender;
60 | - (IBAction)takeResumeFlag:(id)sender;
61 | - (IBAction)takeTaskForPid:(id)sender;
62 | - (IBAction)takeKauth:(id)sender;
63 | - (IBAction)takeSingleStep:(id)sender;
64 |
65 | -(void)disableOptionButtons;
66 | -(void)enableOptionButtons;
67 |
68 | @property (strong) KernelControl *kc;
69 |
70 | @end
71 |
--------------------------------------------------------------------------------
/control-gui/control-gui/controlAppDelegate.m:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * controlAppDelegate.m
36 | *
37 | */
38 |
39 | #import "controlAppDelegate.h"
40 | #import "kernelControl.h"
41 | #import "shared_data.h"
42 |
43 | @implementation controlAppDelegate
44 |
45 |
46 | - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
47 | {
48 | self.kc = [KernelControl new];
49 | if ( [self.kc connectToKext] == 0 )
50 | {
51 | [self.statusField setStringValue:@"Connected to kext!"];
52 | [self.disconnectButton setEnabled:YES];
53 | [self.connectButton setEnabled:NO];
54 | NSImage *connectedImage = [NSImage imageNamed:@"status-available.tiff"];
55 | [self.status setImage:connectedImage];
56 | [self enableOptionButtons];
57 | }
58 | else
59 | {
60 | [self.statusField setStringValue:@"Failed to connect to kext!"];
61 | [self.disconnectButton setEnabled:NO];
62 | [self.connectButton setEnabled:YES];
63 | [self disableOptionButtons];
64 | }
65 | }
66 |
67 | - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
68 | {
69 | return YES;
70 | }
71 |
72 | -(void)enableOptionButtons
73 | {
74 | [self.ptraceButton setEnabled:YES];
75 | [self.sysctlButton setEnabled:YES];
76 | [self.resumeFlagButton setEnabled:YES];
77 | [self.taskForPidButton setEnabled:YES];
78 | [self.kauthButton setEnabled:YES];
79 | [self.singleStepButton setEnabled:YES];
80 | }
81 |
82 | -(void)disableOptionButtons
83 | {
84 | [self.ptraceButton setEnabled:NO];
85 | [self.sysctlButton setEnabled:NO];
86 | [self.resumeFlagButton setEnabled:NO];
87 | [self.taskForPidButton setEnabled:NO];
88 | [self.kauthButton setEnabled:NO];
89 | [self.singleStepButton setEnabled:NO];
90 | }
91 |
92 | - (IBAction)pressConnect:(id)sender
93 | {
94 | if ( [self.kc connectToKext] == 0 )
95 | {
96 | [self.statusField setStringValue:@"Connected to kext!"];
97 | [self.disconnectButton setEnabled:YES];
98 | [self.connectButton setEnabled:NO];
99 | NSImage *connectedImage = [NSImage imageNamed:@"status-available.tiff"];
100 | [self.status setImage:connectedImage];
101 | [self enableOptionButtons];
102 | }
103 | else
104 | {
105 | [self.statusField setStringValue:@"Failed to connect to kext!"];
106 | [self.disconnectButton setEnabled:NO];
107 | [self disableOptionButtons];
108 | }
109 | }
110 |
111 | - (IBAction)pressDisconnect:(id)sender
112 | {
113 | [self.kc disconnectFromKext];
114 | [self.statusField setStringValue:@"Disconnected from kext!"];
115 | [self.disconnectButton setEnabled:NO];
116 | [self.connectButton setEnabled:YES];
117 | NSImage *connectedImage = [NSImage imageNamed:@"status-away.tiff"];
118 | [self.status setImage:connectedImage];
119 | [self disableOptionButtons];
120 | }
121 |
122 | - (IBAction)takePtrace:(id)sender
123 | {
124 | if ( [[sender cell] state] == NSOnState)
125 | {
126 | [self.kc sendCommand:ANTI_PTRACE_ON];
127 | [self.statusField setStringValue:@"Enabled anti-anti-ptrace!"];
128 | }
129 | else if ( [[sender cell] state] == NSOffState)
130 | {
131 | [self.kc sendCommand:ANTI_PTRACE_OFF];
132 | [self.statusField setStringValue:@"Disabled anti-anti-ptrace!"];
133 | }
134 | }
135 |
136 | - (IBAction)takeSysctl:(id)sender
137 | {
138 | if ( [[sender cell] state] == NSOnState)
139 | {
140 | [self.kc sendCommand:ANTI_SYSCTL_ON];
141 | [self.statusField setStringValue:@"Enabled anti-sysctl-antidebugging!"];
142 | }
143 | else if ( [[sender cell] state] == NSOffState)
144 | {
145 | [self.kc sendCommand:ANTI_SYSCTL_OFF];
146 | [self.statusField setStringValue:@"Disabled anti-sysctl-antidebugging!"];
147 | }
148 | }
149 |
150 | - (IBAction)takeResumeFlag:(id)sender
151 | {
152 | if ( [[sender cell] state] == NSOnState)
153 | {
154 | [self.kc sendCommand:PATCH_RESUME_FLAG];
155 | [self.statusField setStringValue:@"Patched resume flag!"];
156 | }
157 | else if ( [[sender cell] state] == NSOffState)
158 | {
159 | [self.kc sendCommand:UNPATCH_RESUME_FLAG];
160 | [self.statusField setStringValue:@"Restored resume flag!"];
161 | }
162 | }
163 |
164 | - (IBAction)takeTaskForPid:(id)sender
165 | {
166 | if ( [[sender cell] state] == NSOnState)
167 | {
168 | [self.kc sendCommand:PATCH_TASK_FOR_PID];
169 | [self.statusField setStringValue:@"Enabled task_for_pid(0)!"];
170 | }
171 | else if ( [[sender cell] state] == NSOffState)
172 | {
173 | [self.kc sendCommand:UNPATCH_TASK_FOR_PID];
174 | [self.statusField setStringValue:@"Disabled task_for_pid(0)!"];
175 | }
176 | }
177 |
178 | - (IBAction)takeKauth:(id)sender {
179 | if ( [[sender cell] state] == NSOnState)
180 | {
181 | [self.kc sendCommand:ANTI_KAUTH_ON];
182 | [self.statusField setStringValue:@"Patched kauth anti-debugging!"];
183 | }
184 | else if ( [[sender cell] state] == NSOffState)
185 | {
186 | [self.kc sendCommand:ANTI_KAUTH_OFF];
187 | [self.statusField setStringValue:@"Restored kauth anti-debugging!"];
188 | }
189 | }
190 |
191 | - (IBAction)takeSingleStep:(id)sender
192 | {
193 | if ( [[sender cell] state] == NSOnState)
194 | {
195 | [self.kc sendCommand:PATCH_SINGLESTEP];
196 | [self.statusField setStringValue:@"Enabled single step!"];
197 | }
198 | else if ( [[sender cell] state] == NSOffState)
199 | {
200 | [self.kc sendCommand:UNPATCH_SINGLESTEP];
201 | [self.statusField setStringValue:@"Disabled single step!"];
202 | }
203 | }
204 |
205 | @end
206 |
--------------------------------------------------------------------------------
/control-gui/control-gui/en.lproj/Credits.rtf:
--------------------------------------------------------------------------------
1 | {\rtf1\ansi\ansicpg1252\cocoartf1265
2 | {\fonttbl\f0\fswiss\fcharset0 Helvetica;}
3 | {\colortbl;\red255\green255\blue255;}
4 | \paperw11900\paperh16840\vieww9600\viewh8400\viewkind0
5 | \pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720
6 |
7 | \f0\b\fs24 \cf0 Engineering:
8 | \b0 \
9 | fG!\
10 | \
11 |
12 | \b Human Interface Design:
13 | \b0 \
14 | Onyx!\
15 | \
16 |
17 | \b Testing:
18 | \b0 \
19 | Onyx!\
20 | \
21 |
22 | \b Documentation:
23 | \b0 \
24 | No one.\
25 | \
26 |
27 | \b With special thanks to:
28 | \b0 \
29 | Porsche.\
30 | \
31 |
32 | \b Icon by http://iconka.com.
33 | \b0 \
34 | }
--------------------------------------------------------------------------------
/control-gui/control-gui/en.lproj/InfoPlist.strings:
--------------------------------------------------------------------------------
1 | /* Localized versions of Info.plist keys */
2 |
3 |
--------------------------------------------------------------------------------
/control-gui/control-gui/kernelControl.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * kernelControl.h
36 | *
37 | */
38 |
39 | #import
40 |
41 | @interface KernelControl : NSObject
42 |
43 | @property int kSocket;
44 |
45 | -(int)connectToKext;
46 | -(int)disconnectFromKext;
47 | -(int)sendCommand:(int)command;
48 |
49 | @end
50 |
--------------------------------------------------------------------------------
/control-gui/control-gui/kernelControl.m:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * kernelControl.m
36 | *
37 | */
38 |
39 | #import "kernelControl.h"
40 | #include
41 | #include
42 | #include
43 | #include
44 | #include
45 | #include
46 | #include
47 | #include
48 | #include
49 | #include
50 | #include
51 | #include
52 | #include
53 | #include
54 | #include
55 | #include
56 | #include
57 | #include
58 |
59 | #include "shared_data.h"
60 |
61 | @implementation KernelControl
62 |
63 | -(int)connectToKext
64 | {
65 | struct sockaddr_ctl sc = {0};
66 | struct ctl_info ctl_info = {0};
67 | int ret = 0;
68 |
69 | self.kSocket = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
70 | if (self.kSocket < 0)
71 | {
72 | NSLog(@"[ERROR] Failed to create socket!\n");
73 | return -1;
74 | }
75 | // the control ID is dynamically generated so we must obtain sc_id using ioctl
76 | memset(&ctl_info, 0, sizeof(ctl_info));
77 | strncpy(ctl_info.ctl_name, BUNDLE_ID, MAX_KCTL_NAME);
78 | ctl_info.ctl_name[MAX_KCTL_NAME-1] = '\0';
79 | if (ioctl(self.kSocket, CTLIOCGINFO, &ctl_info) == -1)
80 | {
81 | NSLog(@"[ERROR] ioctl CTLIOCGINFO failed!\n");
82 | self.kSocket = -1;
83 | return -1;
84 | }
85 | #if DEBUG
86 | printf("[DEBUG] ctl_id: 0x%x for ctl_name: %s\n", ctl_info.ctl_id, ctl_info.ctl_name);
87 | #endif
88 |
89 | bzero(&sc, sizeof(struct sockaddr_ctl));
90 | sc.sc_len = sizeof(struct sockaddr_ctl);
91 | sc.sc_family = AF_SYSTEM;
92 | sc.ss_sysaddr = AF_SYS_CONTROL;
93 | sc.sc_id = ctl_info.ctl_id;
94 | sc.sc_unit = 0;
95 |
96 | ret = connect(self.kSocket, (struct sockaddr*)&sc, sizeof(sc));
97 | if (ret)
98 | {
99 | self.kSocket = -1;
100 | NSLog(@"[ERROR] Connect failed: %s!\n", strerror(errno));
101 | return -1;
102 | }
103 | return 0;
104 | }
105 |
106 | -(int)disconnectFromKext
107 | {
108 | close(self.kSocket);
109 | return 0;
110 | }
111 |
112 | -(int)sendCommand:(int)command
113 | {
114 | if (self.kSocket == -1)
115 | {
116 | NSLog(@"Can't send command, not connected!");
117 | return -1;
118 | }
119 | char *magic = MAGIC;
120 | size_t magic_len = strlen(magic)+1;
121 | int ret = setsockopt(self.kSocket, SYSPROTO_CONTROL, command, (void*)magic, (socklen_t)magic_len);
122 | if (ret)
123 | {
124 | NSLog(@"[ERROR] Kernel command execution failed!\n");
125 | return -1;
126 | }
127 | return 0;
128 | }
129 |
130 | @end
131 |
--------------------------------------------------------------------------------
/control-gui/control-gui/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // control-gui
4 | //
5 | // Created by reverser on 08/02/14.
6 | // Copyright (c) 2014 Put.as. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | int main(int argc, const char * argv[])
12 | {
13 | return NSApplicationMain(argc, argv);
14 | }
15 |
--------------------------------------------------------------------------------
/control-gui/control-gui/status-available.tiff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/status-available.tiff
--------------------------------------------------------------------------------
/control-gui/control-gui/status-away.tiff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/control-gui/control-gui/status-away.tiff
--------------------------------------------------------------------------------
/control-gui/control-guiTests/control-guiTests-Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | ${EXECUTABLE_NAME}
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundlePackageType
14 | BNDL
15 | CFBundleShortVersionString
16 | 1.0
17 | CFBundleSignature
18 | ????
19 | CFBundleVersion
20 | 1
21 |
22 |
23 |
--------------------------------------------------------------------------------
/control-gui/control-guiTests/control_guiTests.m:
--------------------------------------------------------------------------------
1 | //
2 | // control_guiTests.m
3 | // control-guiTests
4 | //
5 | // Created by reverser on 08/02/14.
6 | // Copyright (c) 2014 Put.as. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface control_guiTests : XCTestCase
12 |
13 | @end
14 |
15 | @implementation control_guiTests
16 |
17 | - (void)setUp
18 | {
19 | [super setUp];
20 | // Put setup code here. This method is called before the invocation of each test method in the class.
21 | }
22 |
23 | - (void)tearDown
24 | {
25 | // Put teardown code here. This method is called after the invocation of each test method in the class.
26 | [super tearDown];
27 | }
28 |
29 | - (void)testExample
30 | {
31 | XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
32 | }
33 |
34 | @end
35 |
--------------------------------------------------------------------------------
/control-gui/control-guiTests/en.lproj/InfoPlist.strings:
--------------------------------------------------------------------------------
1 | /* Localized versions of Info.plist keys */
2 |
3 |
--------------------------------------------------------------------------------
/control/control.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/control/control/main.c:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * The userland daemon to control Onyx The Black Cat kernel extension
36 | *
37 | * main.c
38 | *
39 | * Menus code ripped from Rubilyn rootkit :-)
40 | *
41 | */
42 |
43 | #include
44 | #include
45 | #include
46 | #include
47 | #include
48 | #include
49 | #include
50 | #include
51 | #include
52 | #include
53 | #include
54 | #include
55 | #include
56 | #include
57 |
58 | #include
59 | #include
60 | #include
61 | #include
62 |
63 | #include "shared_data.h"
64 |
65 | static int g_socket = -1;
66 |
67 | #define MAXLEN 4098
68 | #define MAXARG 512
69 | #define MAGIC "SpecialisRevelio"
70 |
71 | int
72 | connect_to_kernel(void)
73 | {
74 | struct sockaddr_ctl sc = {0};
75 | struct ctl_info ctl_info = {0};
76 | int ret = 0;
77 |
78 | g_socket = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
79 | if (g_socket < 0)
80 | {
81 | printf("[ERROR] Failed to create socket!\n");
82 | exit(1);
83 | }
84 | // the control ID is dynamically generated so we must obtain sc_id using ioctl
85 | memset(&ctl_info, 0, sizeof(ctl_info));
86 | strncpy(ctl_info.ctl_name, BUNDLE_ID, MAX_KCTL_NAME);
87 | ctl_info.ctl_name[MAX_KCTL_NAME-1] = '\0';
88 | if (ioctl(g_socket, CTLIOCGINFO, &ctl_info) == -1)
89 | {
90 | printf("[ERROR] ioctl CTLIOCGINFO failed!\n");
91 | exit(1);
92 | }
93 | #if DEBUG
94 | printf("[DEBUG] ctl_id: 0x%x for ctl_name: %s\n", ctl_info.ctl_id, ctl_info.ctl_name);
95 | #endif
96 |
97 | bzero(&sc, sizeof(struct sockaddr_ctl));
98 | sc.sc_len = sizeof(struct sockaddr_ctl);
99 | sc.sc_family = AF_SYSTEM;
100 | sc.ss_sysaddr = AF_SYS_CONTROL;
101 | sc.sc_id = ctl_info.ctl_id;
102 | sc.sc_unit = 0;
103 |
104 | ret = connect(g_socket, (struct sockaddr*)&sc, sizeof(sc));
105 | if (ret)
106 | {
107 | printf("[ERROR] Connect failed!\n");
108 | exit(1);
109 | }
110 | return 0;
111 | }
112 |
113 | void
114 | print_menu(void)
115 | {
116 | printf("[Onyx The Black Cat Kernel Control]\n");
117 | printf("[menu]\n");
118 | printf("[1] enable anti-anti-ptrace\n");
119 | printf("[2] disable anti-anti-ptrace\n");
120 | printf("[3] enable sysctl anti-anti-debug\n");
121 | printf("[4] disable sysctl anti-anti-debug\n");
122 | printf("[5] patch resume flag\n");
123 | printf("[6] restore resume flag\n");
124 | printf("[7] patch task_for_pid(0)\n");
125 | printf("[8] restore task_for_pid()\n");
126 | printf("[9] patch kauth\n");
127 | printf("[0] restore kauth\n");
128 | printf("[a] activate single-step-on-branch\n");
129 | printf("[b] restore single-step-on-branch\n");
130 | printf("[h] help\n");
131 | printf("[q] exit\n");
132 | }
133 |
134 | void
135 | execute_cmd(int cmd)
136 | {
137 | char *magic = MAGIC;
138 | size_t magic_len = strlen(magic)+1;
139 | int ret = setsockopt(g_socket, SYSPROTO_CONTROL, cmd, (void*)magic, (socklen_t)magic_len);
140 | if (ret)
141 | {
142 | printf("[ERROR] Kernel command execution failed!\n");
143 | }
144 | }
145 |
146 | void main_menu()
147 | {
148 | char str;
149 | do {
150 | printf("--> ");
151 | str = getchar();
152 | switch(str)
153 | {
154 | case '1':
155 | execute_cmd(ANTI_PTRACE_ON);
156 | break;
157 | case '2':
158 | execute_cmd(ANTI_PTRACE_OFF);
159 | break;
160 | case '3':
161 | execute_cmd(ANTI_SYSCTL_ON);
162 | break;
163 | case '4':
164 | execute_cmd(ANTI_SYSCTL_OFF);
165 | break;
166 | case '5':
167 | execute_cmd(PATCH_RESUME_FLAG);
168 | break;
169 | case '6':
170 | execute_cmd(UNPATCH_RESUME_FLAG);
171 | break;
172 | case '7':
173 | execute_cmd(PATCH_TASK_FOR_PID);
174 | break;
175 | case '8':
176 | execute_cmd(UNPATCH_TASK_FOR_PID);
177 | break;
178 | case '9':
179 | execute_cmd(ANTI_KAUTH_ON);
180 | break;
181 | case '0':
182 | execute_cmd(ANTI_KAUTH_OFF);
183 | break;
184 | case 'a':
185 | execute_cmd(PATCH_SINGLESTEP);
186 | break;
187 | case 'b':
188 | execute_cmd(UNPATCH_SINGLESTEP);
189 | break;
190 | case 'h':
191 | print_menu();
192 | break;
193 | case '?':
194 | print_menu();
195 | break;
196 | case 'q':
197 | exit(0);
198 | break;
199 | case 'x':
200 | exit(0);
201 | break;
202 | default:
203 | printf("Invalid selection!\n");
204 | break;
205 | }
206 | }
207 | while(getchar() != '\n');
208 | }
209 |
210 | int main(int argc, const char * argv[])
211 | {
212 | if (connect_to_kernel())
213 | {
214 | printf("[ERROR] Can't connect to kernel control socket!\n");
215 | exit(1);
216 | }
217 | print_menu();
218 | while(1)
219 | {
220 | main_menu();
221 | }
222 | return 0;
223 | }
224 |
--------------------------------------------------------------------------------
/distorm/COPYING:
--------------------------------------------------------------------------------
1 | :[diStorm3}:
2 | The ultimate disassembler library.
3 | Copyright (c) 2003-2016, Gil Dabah
4 | All rights reserved.
5 |
6 | Redistribution and use in source and binary forms, with or without
7 | modification, are permitted provided that the following conditions are met:
8 | 1. Redistributions of source code must retain the above copyright
9 | notice, this list of conditions and the following disclaimer.
10 | 2. Redistributions in binary form must reproduce the above copyright
11 | notice, this list of conditions and the following disclaimer in the
12 | documentation and/or other materials provided with the distribution.
13 | 3. All advertising materials mentioning features or use of this software
14 | must display the following acknowledgement:
15 | This product includes software developed by Gil Dabah.
16 | 4. Neither the name of Gil Dabah nor the
17 | names of its contributors may be used to endorse or promote products
18 | derived from this software without specific prior written permission.
19 |
20 | THIS SOFTWARE IS PROVIDED BY Gil Dabah ''AS IS'' AND ANY
21 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 | DISCLAIMED. IN NO EVENT SHALL Gil Dabah BE LIABLE FOR ANY
24 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
/distorm/MANIFEST:
--------------------------------------------------------------------------------
1 | COPYING
2 | setup.cfg
3 | setup.py
4 | include\distorm.h
5 | include\mnemonics.h
6 | python\distorm3\__init__.py
7 | python\distorm3\sample.py
8 | src\config.h
9 | src\decoder.c
10 | src\decoder.h
11 | src\distorm.c
12 | src\instructions.c
13 | src\instructions.h
14 | src\insts.c
15 | src\insts.h
16 | src\mnemonics.c
17 | src\operands.c
18 | src\operands.h
19 | src\prefix.c
20 | src\prefix.h
21 | src\textdefs.c
22 | src\textdefs.h
23 | src\wstring.c
24 | src\wstring.h
25 | src\x86defs.h
26 |
--------------------------------------------------------------------------------
/distorm/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include COPYING setup.cfg setup.py
2 | recursive-include src *.c *.h
3 | recursive-include include *.c *.h
4 | recursive-include . *.py
--------------------------------------------------------------------------------
/distorm/README.md:
--------------------------------------------------------------------------------
1 | Powerful Disassembler Library For x86/AMD64
2 | -----------
3 |
4 | Welcome to the diStorm3 binary stream disassembler library project.
5 |
6 | diStorm3 is really a decomposer, which means it takes an instruction and returns a binary structure which describes it rather than static text, which is great for advanced binary code analysis.
7 |
8 | diStorm3 is super lightweight (~45KB), ultra fast and easy to use (a single API)!
9 |
10 | "We benchmarked five popular open-source disassembly libraries and chose diStorm3, which had the best performance (and furthermore, has complete 64-bit support).", July 2014, Quoting David Williams-King in his Thesis about Binary Shuffling.
11 |
12 | diStorm3.3.3 is now licensed under BSD!
--------------------------------------------------------------------------------
/distorm/disOps/x86header.py:
--------------------------------------------------------------------------------
1 | #
2 | # x86header.py
3 | #
4 | # Copyright (C) 2009 Gil Dabah, http://ragestorm.net/disops/
5 | #
6 |
7 | class OperandType:
8 | """ Types of possible operands in an opcode.
9 | Refer to the diStorm's documentation or diStorm's instructions.h
10 | for more explanation about every one of them. """
11 | (NONE,
12 | IMM8,
13 | IMM16,
14 | IMM_FULL,
15 | IMM32,
16 | SEIMM8,
17 | IMM16_1, # NEW
18 | IMM8_1, # NEW
19 | IMM8_2, # NEW
20 | REG8,
21 | REG16,
22 | REG_FULL,
23 | REG32,
24 | REG32_64,
25 | FREG32_64_RM,
26 | RM8,
27 | RM16,
28 | RM_FULL,
29 | RM32_64,
30 | RM16_32,
31 | FPUM16,
32 | FPUM32,
33 | FPUM64,
34 | FPUM80,
35 | R32_M8,
36 | R32_M16,
37 | R32_64_M8,
38 | R32_64_M16,
39 | RFULL_M16,
40 | CREG,
41 | DREG,
42 | SREG,
43 | SEG,
44 | ACC8,
45 | ACC16,
46 | ACC_FULL,
47 | ACC_FULL_NOT64,
48 | MEM16_FULL,
49 | PTR16_FULL,
50 | MEM16_3264,
51 | RELCB,
52 | RELC_FULL,
53 | MEM,
54 | MEM_OPT, # NEW
55 | MEM32,
56 | MEM32_64, # NEW
57 | MEM64,
58 | MEM128,
59 | MEM64_128,
60 | MOFFS8,
61 | MOFFS_FULL,
62 | CONST1,
63 | REGCL,
64 | IB_RB,
65 | IB_R_FULL,
66 | REGI_ESI,
67 | REGI_EDI,
68 | REGI_EBXAL,
69 | REGI_EAX,
70 | REGDX,
71 | REGECX,
72 | FPU_SI,
73 | FPU_SSI,
74 | FPU_SIS,
75 | MM,
76 | MM_RM,
77 | MM32,
78 | MM64,
79 | XMM,
80 | XMM_RM,
81 | XMM16,
82 | XMM32,
83 | XMM64,
84 | XMM128,
85 | REGXMM0,
86 | # Below new for AVX:
87 | RM32,
88 | REG32_64_M8,
89 | REG32_64_M16,
90 | WREG32_64,
91 | WRM32_64,
92 | WXMM32_64,
93 | VXMM,
94 | XMM_IMM,
95 | YXMM,
96 | YXMM_IMM,
97 | YMM,
98 | YMM256,
99 | VYMM,
100 | VYXMM,
101 | YXMM64_256,
102 | YXMM128_256,
103 | LXMM64_128,
104 | LMEM128_256) = range(93)
105 |
106 | class OpcodeLength:
107 | """ The length of the opcode in bytes.
108 | Where a suffix of '3' means we have to read the REG field of the ModR/M byte (REG size is 3 bits).
109 | Suffix of 'd' means it's a Divided instruction (see documentation),
110 | tells the disassembler to read the REG field or the whole next byte.
111 |
112 | OL_33 and OL_4 are used in raw opcode bytes, they include the mandatory prefix,
113 | therefore when they are defined in the instruction tables, the mandatory prefix table is added,
114 | and they become OL_23 and OL_3 correspondingly. There is no effective opcode which is more than 3 bytes. """
115 | (OL_1, # 0
116 | OL_13, # 1
117 | OL_1d, # 2 - Can be prefixed (only by WAIT/9b)
118 | OL_2, # 3 - Can be prefixed
119 | OL_23, # 4 - Can be prefixed
120 | OL_2d, # 5
121 | OL_3, # 6 - Can be prefixed
122 | OL_33, # 7 - Internal only
123 | OL_4 # 8 - Internal only
124 | ) = range(9)
125 |
126 | """ Next-Opcode-Length dictionary is used in order to recursively build the instructions' tables dynamically.
127 | It is used in such a way that it indicates how many more nested tables
128 | we have to build and link starting from a given OL. """
129 | NextOL = {OL_13: OL_1, OL_1d: OL_1, OL_2: OL_1, OL_23: OL_13,
130 | OL_2d: OL_1d, OL_3: OL_2, OL_33: OL_23, OL_4: OL_3}
131 |
132 | class InstFlag:
133 | """ Instruction Flag contains all bit mask constants for describing an instruction.
134 | You can bitwise-or the flags. See diStorm's documentation for more explanation.
135 |
136 | The GEN_BLOCK is a special flag, it is used in the tables generator only;
137 | See GenBlock class inside x86db.py. """
138 | FLAGS_EX_START_INDEX = 32
139 | INST_FLAGS_NONE = 0
140 | (MODRM_REQUIRED, # 0
141 | NOT_DIVIDED, # 1
142 | _16BITS, # 2
143 | _32BITS, # 3
144 | PRE_LOCK, # 4
145 | PRE_REPNZ, # 5
146 | PRE_REP, # 6
147 | PRE_CS, # 7
148 | PRE_SS, # 8
149 | PRE_DS, # 9
150 | PRE_ES, # 10
151 | PRE_FS, # 11
152 | PRE_GS, # 12
153 | PRE_OP_SIZE, # 13
154 | PRE_ADDR_SIZE, # 14
155 | NATIVE, # 15
156 | USE_EXMNEMONIC, # 16
157 | USE_OP3, # 17
158 | USE_OP4, # 18
159 | MNEMONIC_MODRM_BASED, # 19
160 | MODRR_REQUIRED, # 20
161 | _3DNOW_FETCH, # 21
162 | PSEUDO_OPCODE, # 22
163 | INVALID_64BITS, # 23
164 | _64BITS, # 24
165 | PRE_REX, # 25
166 | USE_EXMNEMONIC2, # 26
167 | _64BITS_FETCH, # 27
168 | FORCE_REG0, # 28
169 | PRE_VEX, # 29
170 | MODRM_INCLUDED, # 30
171 | DST_WR, # 31
172 | VEX_L, # 32 From here on: flagsEx.
173 | VEX_W, # 33
174 | MNEMONIC_VEXW_BASED, # 34
175 | MNEMONIC_VEXL_BASED, # 35
176 | FORCE_VEXL, # 36
177 | MODRR_BASED, # 37
178 | VEX_V_UNUSED, # 38
179 | GEN_BLOCK, # 39 From here on: internal to disOps.
180 | EXPORTED # 40
181 | ) = [1 << i for i in xrange(41)]
182 | # Nodes are extended if they have any of the following flags:
183 | EXTENDED = (PRE_VEX | USE_EXMNEMONIC | USE_EXMNEMONIC2 | USE_OP3 | USE_OP4)
184 | SEGMENTS = (PRE_CS | PRE_SS | PRE_DS | PRE_ES | PRE_FS | PRE_FS)
185 |
186 | class ISetClass:
187 | """ Instruction-Set-Class indicates to which set the instruction belongs.
188 | These types are taken from the documentation of Intel/AMD. """
189 | (INTEGER,
190 | FPU,
191 | P6,
192 | MMX,
193 | SSE,
194 | SSE2,
195 | SSE3,
196 | SSSE3,
197 | SSE4_1,
198 | SSE4_2,
199 | SSE4_A,
200 | _3DNOW,
201 | _3DNOWEXT,
202 | VMX,
203 | SVM,
204 | AVX,
205 | FMA,
206 | CLMUL,
207 | AES) = range(1, 20)
208 |
209 | class FlowControl:
210 | """ The flow control instruction will be flagged in the lo nibble of the 'meta' field in _InstInfo of diStorm.
211 | They are used to distinguish between flow control instructions (such as: ret, call, jmp, jz, etc) to normal ones. """
212 | (CALL,
213 | RET,
214 | SYS,
215 | UNC_BRANCH,
216 | CND_BRANCH,
217 | INT,
218 | CMOV) = range(1, 8)
219 |
220 | class NodeType:
221 | """ A node can really be an object holder for an instruction-info object or
222 | another table (list) with a different size.
223 |
224 | GROUP - 8 entries in the table
225 | FULL - 256 entries in the table.
226 | Divided - 72 entries in the table (ranges: 0x0-0x7, 0xc0-0xff).
227 | Prefixed - 12 entries in the table (none, 0x66, 0xf2, 0xf3). """
228 | (NONE, # 0
229 | INFO, # 1
230 | INFOEX, # 2
231 | LIST_GROUP, # 3
232 | LIST_FULL, # 4
233 | LIST_DIVIDED, # 5
234 | LIST_PREFIXED # 6
235 | ) = range(0, 7)
236 |
237 | class CPUFlags:
238 | """ Specifies all the flags that the x86/x64 CPU supports, in a special compact order. """
239 | (CF, # 0
240 | IF, # 1
241 | PF, # 2
242 | DF, # 3
243 | AF, # 4
244 | OF, # 5
245 | ZF, # 6
246 | SF # 7
247 | ) = [1 << i for i in xrange(8)]
248 |
--------------------------------------------------------------------------------
/distorm/examples/cs/TestdiStorm/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.Reflection.Emit;
4 | using diStorm;
5 |
6 | namespace TestdiStorm
7 | {
8 | public class Program
9 | {
10 | private static IntPtr LeakNativeMethodPtr(MethodInfo x)
11 | {
12 |
13 | //if ((x.MethodImplementationFlags & MethodImplAttributes.InternalCall) != 0)
14 | // Console.WriteLine("{0} is an InternalCall method. These methods always point to the same address.", x.Name);
15 | var domain = AppDomain.CurrentDomain;
16 | var dynAsm = new AssemblyName("MethodLeakAssembly");
17 | var asmBuilder = domain.DefineDynamicAssembly(dynAsm, AssemblyBuilderAccess.Run);
18 | var moduleBuilder = asmBuilder.DefineDynamicModule("MethodLeakModule");
19 | var typeBuilder = moduleBuilder.DefineType("MethodLeaker", TypeAttributes.Public);
20 | var p = new Type[0];
21 | var methodBuilder = typeBuilder.DefineMethod("LeakNativeMethodPtr", MethodAttributes.Public | MethodAttributes.Static, typeof(IntPtr), null);
22 | var generator = methodBuilder.GetILGenerator();
23 |
24 | // Push unmanaged pointer to MethodInfo onto the evaluation stack
25 | generator.Emit(OpCodes.Ldftn, x);
26 | // Convert the pointer to type - unsigned int64
27 | //generator.Emit(OpCodes.Conv_Ovf_U);
28 | generator.Emit(OpCodes.Ret);
29 |
30 | // Assemble everything
31 | var type = typeBuilder.CreateType();
32 |
33 | var method = type.GetMethod("LeakNativeMethodPtr");
34 |
35 | try {
36 | // Call the method and return its JITed address
37 | var address = (IntPtr) method.Invoke(null, new object[0]);
38 |
39 | Console.WriteLine("0x{0}", address.ToString(string.Format("X{0})", IntPtr.Size * 2)));
40 | return address;
41 | }
42 | catch (Exception e) {
43 | Console.WriteLine("{0} cannot return an unmanaged address.");
44 | }
45 | return IntPtr.Zero;
46 | }
47 |
48 |
49 | private static unsafe void Main(string[] args)
50 | {
51 | var buf = new byte[4];
52 | buf[0] = (byte) 0xc3;
53 | buf[1] = (byte) 0x33;
54 | buf[2] = (byte) 0xc0;
55 | buf[3] = (byte) 0xc3;
56 | var ci = new CodeInfo((long) 0x1000, buf, DecodeType.Decode32Bits, 0);
57 | var dr = new DecodedResult(10);
58 | diStorm3.Decode(ci, dr);
59 |
60 | foreach (var x in dr.Instructions) {
61 | var s = String.Format("{0:X} {1} {2}", x.Offset, x.Mnemonic, x.Operands);
62 | Console.WriteLine(s);
63 | }
64 |
65 | var dr2 = new DecomposedResult(10);
66 | diStorm3.Decompose(ci, dr2);
67 |
68 | foreach (var y in dr2.Instructions) {
69 | if (y.Opcode != Opcode.RET)
70 | {
71 | var x = diStorm3.Format(ci, y);
72 | var s = String.Format("{0:X} {1} {2}", x.Offset, x.Mnemonic, x.Operands);
73 | Console.WriteLine(s);
74 | }
75 | }
76 |
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/distorm/examples/cs/TestdiStorm/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("TestDiStorm")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("TestDiStorm")]
13 | [assembly: AssemblyCopyright("Copyright © 2012")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("737cf66b-c136-47be-b92d-3f2fefbaf27a")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/distorm/examples/cs/TestdiStorm/TestdiStorm.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}
8 | Exe
9 | Properties
10 | TestDiStorm
11 | TestDiStorm
12 | v4.0
13 | 512
14 |
15 |
16 |
17 | x64
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 | true
26 | false
27 |
28 |
29 | x64
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 | true
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | {137ade63-2489-4235-91c6-6cb664cab63f}
55 | distorm-net
56 |
57 |
58 |
59 |
60 | copy $(SolutionDir)\..\..\distorm3.dll $(TargetDir)
61 |
62 |
69 |
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2012
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "distorm-net", "distorm-net\distorm-net.csproj", "{137ADE63-2489-4235-91C6-6CB664CAB63F}"
5 | EndProject
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestdiStorm", "TestDiStorm\TestdiStorm.csproj", "{2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Release|Any CPU.Build.0 = Release|Any CPU
18 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Release|Any CPU.Build.0 = Release|Any CPU
22 | EndGlobalSection
23 | GlobalSection(SolutionProperties) = preSolution
24 | HideSolutionNode = FALSE
25 | EndGlobalSection
26 | EndGlobal
27 |
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/CodeInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace diStorm
4 | {
5 | public class CodeInfo
6 | {
7 | public CodeInfo(long codeOffset, byte[] rawCode, DecodeType dt, int features)
8 | {
9 | _code = new byte[rawCode.Length];
10 | Array.Copy(rawCode, _code, _code.Length);
11 |
12 | _codeOffset = codeOffset;
13 | _decodeType = dt;
14 | _features = features;
15 | }
16 |
17 | internal long _codeOffset;
18 | internal long _nextOffset;
19 | internal byte[] _code;
20 | internal DecodeType _decodeType;
21 | internal int _features;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/DecodedInst.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace diStorm
4 | {
5 | public class DecodedInst
6 | {
7 | internal DecodedInst() { }
8 |
9 | public string Mnemonic { get; internal set; }
10 | public string Operands { get; internal set; }
11 | public string Hex { get; internal set; }
12 | public uint Size { get; internal set; }
13 | public IntPtr Offset { get; internal set; }
14 | }
15 | }
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/DecodedResult.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace diStorm
3 | {
4 | public class DecodedResult
5 | {
6 | public DecodedResult(int maxInstructions)
7 | {
8 | MaxInstructions = maxInstructions;
9 | Instructions = null;
10 | }
11 | public DecodedInst[] Instructions { get; internal set; }
12 | public int MaxInstructions { get; internal set; }
13 | }
14 | }
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/DecomposedInst.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace diStorm
4 | {
5 | public class DecomposedInst
6 | {
7 | public class ImmVariant
8 | {
9 | public ulong Imm { get; internal set; }
10 | public int Size { get; internal set; }
11 | }
12 | public class DispVariant
13 | {
14 | public ulong Displacement { get; internal set; }
15 | public int Size { get; internal set; }
16 | }
17 | internal int _segment;
18 | public IntPtr Address { get; internal set; }
19 | public ushort Flags { get; internal set; }
20 | public int Size { get; internal set; }
21 | public Opcode Opcode { get; internal set; }
22 | public int Segment { get { return _segment & 0x7f; } }
23 | public bool IsSegmentDefault { get { return (_segment & 0x80) == 0x80; } }
24 | public int Base { get; internal set; }
25 | public int Scale { get; internal set; }
26 | public int UnusedPrefixesMask { get; internal set; }
27 | public int Meta { get; internal set; }
28 | public int RegistersMask { get; internal set; }
29 | public int ModifiedFlagsMask { get; internal set; }
30 | public int TestedFlagsMask { get; internal set; }
31 | public int UndefinedFlagsMask { get; internal set; }
32 | public ImmVariant Imm { get; internal set; }
33 | public DispVariant Disp { get; internal set; }
34 | public Operand[] Operands { get; internal set; }
35 | }
36 | }
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/DecomposedResult.cs:
--------------------------------------------------------------------------------
1 | namespace diStorm
2 | {
3 | public class DecomposedResult
4 | {
5 | public DecomposedResult(int maxInstructions)
6 | {
7 | MaxInstructions = maxInstructions;
8 | Instructions = null;
9 | }
10 |
11 | public DecomposedInst[] Instructions { get; internal set; }
12 | public int MaxInstructions { get; private set; }
13 | }
14 | }
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/Opcodes.tt:
--------------------------------------------------------------------------------
1 | <#@ template debug="true" hostSpecific="true" #>
2 | <#@ output extension=".cs" #>
3 | <#@ Assembly Name="System.Core" #>
4 | <#@ Assembly Name="System.Windows.Forms" #>
5 | <#@ import namespace="System" #>
6 | <#@ import namespace="System.IO" #>
7 | <#@ import namespace="System.Diagnostics" #>
8 | <#@ import namespace="System.Linq" #>
9 | <#@ import namespace="System.Collections" #>
10 | <#@ import namespace="System.Collections.Generic" #>
11 | <#@ import namespace="System.Text.RegularExpressions" #>
12 | // This file was auto generated from the distrom opcodes.h file
13 | // on <#= DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.FFF") #>
14 | <#
15 | var mnemonics = File.ReadAllText(Host.ResolvePath(@"..\..\..\include\mnemonics.h"));
16 | var instRe = new Regex("typedef enum {(.+)} _InstructionType;", RegexOptions.Singleline);
17 | var regRe = new Regex("typedef enum {(.+)} _RegisterType;", RegexOptions.Singleline);
18 | var m = instRe.Match(mnemonics);
19 | var insts = m.Groups[1].Value.Split(',').Select(x => new {
20 | Name = x.Split('=')[0].Trim().Substring(2),
21 | Value = x.Split('=')[1].Trim(),
22 | }).ToArray();
23 | m = regRe.Match(mnemonics, m.Index + m.Length);
24 | var regs = m.Groups[1].Value.Split(',').Select(x => x.Trim()).ToArray();
25 | #>
26 | namespace diStorm
27 | {
28 | public enum Opcode : ushort {
29 | <# foreach (var i in insts) { #>
30 | <#= i.Name #> = <#= i.Value #>,<# } #>
31 | }
32 |
33 | public enum Register {
34 | <# foreach (var r in regs) { #>
35 | <#= r #>,<# } #>
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/Operand.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace diStorm
3 | {
4 |
5 | public enum OperandType : byte
6 | {
7 | None,
8 | Reg,
9 | Imm,
10 | Imm1,
11 | Imm2,
12 | Disp,
13 | Smem,
14 | Mem,
15 | Pc,
16 | Ptr
17 | }
18 |
19 | public class Operand
20 | {
21 | public OperandType Type { get; internal set; }
22 | public int Index { get; internal set; }
23 | public int Size { get; internal set; }
24 | }
25 | }
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("distorm-net")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("distorm-net")]
13 | [assembly: AssemblyCopyright("Copyright © 2012")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("ddf3403b-11ea-4470-9fb3-03e68ac68fb5")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/distorm/examples/cs/distorm-net/distorm-net.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {137ADE63-2489-4235-91C6-6CB664CAB63F}
8 | Library
9 | Properties
10 | diStorm
11 | diStorm
12 | v4.0
13 | 512
14 |
15 |
16 |
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 | true
25 | x64
26 |
27 |
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 | true
35 | x64
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | True
51 | True
52 | Opcodes.tt
53 |
54 |
55 |
56 |
57 |
58 | TextTemplatingFileGenerator
59 | Opcodes.cs
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
80 |
--------------------------------------------------------------------------------
/distorm/examples/cs/readme:
--------------------------------------------------------------------------------
1 | This is a .NET Wrapper of the distorm project for seamless decompilation of 32-bit and 64-bit intel binaries.
2 | This project is licensed under the GPLv3.
3 | By Dan Shechter
--------------------------------------------------------------------------------
/distorm/examples/ddk/README:
--------------------------------------------------------------------------------
1 | diStorm3 for Ring 0
2 | Gil Dabah Aug 2010
3 | http://ragestorm.net/distorm/
4 |
5 | Tested sample with DDK 7600.16385.1 using WinXPSP2.
6 |
7 | Steps of how to build the diStorm64 sample using the DDK.
8 |
9 | Warning - Make sure the path you extracted diStorm to does not include any spaces, otherwise you will get an error from the build.
10 |
11 | 1) Open the DDK's build environment, for example: "Win XP Free Build Environment",
12 | which readies the evnrionment variables for building a driver. Or run the SETENV.BAT in console.
13 |
14 | 2) Launch "build", once you're in the directory of the /ddkproj.
15 |
16 | 3) If everything worked smoothly, you should see a new file named "distorm.sys" under objfre_wxp_x86\i386
17 | (that's if you use WinXP and the Free Environment).
18 |
19 | - If you experienced any errors, try moving the whole distorm directory to c:\winddk\src\
20 | (or any other directory tree which doesn't contain spaces in its name).
21 |
22 | 4) Now you will have to register the new driver:
23 | a. Copy the distorm.sys file to \windows\system32\drivers\.
24 | b. Use the DDK's regini.exe with the supplied distorm.ini.
25 | c. Restart Windows for the effect to take place. :(
26 |
27 | **The alternative is to use some tool like KmdManager.exe, which will register the driver without a need for the .ini file, nor a reboot.
28 |
29 |
30 | 5) Now open your favorite debug-strings monitor (mine is DebugView).
31 | Make sure you monitor kernel debug-strings.
32 |
33 | 6) Launching "net start distorm" from command line, will run the DriverEntry code in "main.c",
34 | which will disassemble a few instructions from the KeBugcheck routine and dump it using DbgPrint.
35 |
36 |
37 | NOTES:
38 | -+----
39 | The sample uses the stack for storing the results from the decode function.
40 | If you have too many structures on the stack, you better allocate memory before calling the decode function,
41 | and later on free that memory. Don't use the NONPAGED pool if you don't really need it.
42 |
43 | _OffsetType is the type of the DecodedInstruction.Offset field, which defaults to 64bits,
44 | so make sure that when you print this variable you use %I64X, or when you use it anywhere else, you use the _OffsetType as well.
45 | Notice that we call directly distorm_decode64, since we SUPPORT_64BIT_OFFSET and because we don't have the macros of distorm.h.
46 |
47 | diStorm can be really compiled for all IRQL, it doesn't use any resource or the standard C library at all.
48 | Although the sample uses diStorm at PASSIVE level.
49 |
--------------------------------------------------------------------------------
/distorm/examples/ddk/distorm.ini:
--------------------------------------------------------------------------------
1 | \registry\machine\system\currentcontrolset\services\distorm
2 | ImagePath = system32\drivers\distorm.sys
3 | DisplayName = "distorm"
4 | Type = REG_DWORD 0x1
5 | Start = REG_DWORD 0x3
6 | Group = Extended base
7 | ErrorControl = REG_DWORD 0x1
8 | \registry\machine\system\currentcontrolset\services\distorm\Parameters
9 | BreakOnEntry = REG_DWORD 0x0
10 | DebugMask = REG_DWORD 0x0
11 | LogEvents = REG_DWORD 0x0
--------------------------------------------------------------------------------
/distorm/examples/ddk/dummy.c:
--------------------------------------------------------------------------------
1 | // Since the DDK's nmake is limited with directories, we will bypass that with this simple hack.
2 | // Thanks to Razvan Hobeanu.
3 | // Sep 2009.
4 |
5 |
6 | #include "../src/mnemonics.c"
7 | #include "../src/wstring.c"
8 | #include "../src/textdefs.c"
9 | #include "../src/x86defs.c"
10 | #include "../src/prefix.c"
11 | #include "../src/operands.c"
12 | #include "../src/insts.c"
13 | #include "../src/instructions.c"
14 | #include "../src/distorm.c"
15 | #include "../src/decoder.c"
16 |
--------------------------------------------------------------------------------
/distorm/examples/ddk/main.c:
--------------------------------------------------------------------------------
1 | /*
2 | * main.c
3 | * Sample kernel driver to show how diStorm can be easily compiled and used in Ring 0.
4 | *
5 | * /// Follow the README file in order to compile diStorm using the DDK. \\\
6 | *
7 | * Izik, Gil Dabah
8 | * Jan 2007
9 | * http://ragestorm.net/distorm/
10 | */
11 |
12 | #include
13 | #include "../include/distorm.h"
14 | #include "dummy.c"
15 |
16 | // The number of the array of instructions the decoder function will use to return the disassembled instructions.
17 | // Play with this value for performance...
18 | #define MAX_INSTRUCTIONS (15)
19 |
20 | void DriverUnload(IN PDRIVER_OBJECT DriverObject)
21 | {
22 | }
23 |
24 | NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
25 | {
26 | UNICODE_STRING pFcnName;
27 |
28 | // Holds the result of the decoding.
29 | _DecodeResult res;
30 | // Decoded instruction information.
31 | _DecodedInst decodedInstructions[MAX_INSTRUCTIONS];
32 | // next is used for instruction's offset synchronization.
33 | // decodedInstructionsCount holds the count of filled instructions' array by the decoder.
34 | unsigned int decodedInstructionsCount = 0, i, next;
35 | // Default decoding mode is 32 bits, could be set by command line.
36 | _DecodeType dt = Decode32Bits;
37 |
38 | // Default offset for buffer is 0, could be set in command line.
39 | _OffsetType offset = 0;
40 | char* errch = NULL;
41 |
42 | // Buffer to disassemble.
43 | unsigned char *buf;
44 | int len = 100;
45 |
46 | // Register unload routine
47 | DriverObject->DriverUnload = DriverUnload;
48 |
49 | DbgPrint("diStorm Loaded!\n");
50 |
51 | // Get address of KeBugCheck
52 | RtlInitUnicodeString(&pFcnName, L"KeBugCheck");
53 | buf = (char *)MmGetSystemRoutineAddress(&pFcnName);
54 | offset = (unsigned) (_OffsetType)buf;
55 |
56 | DbgPrint("Resolving KeBugCheck @ 0x%08x\n", buf);
57 | // Decode the buffer at given offset (virtual address).
58 |
59 | while (1) {
60 | res = distorm_decode64(offset, (const unsigned char*)buf, len, dt, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount);
61 | if (res == DECRES_INPUTERR) {
62 | DbgPrint(("NULL Buffer?!\n"));
63 | break;
64 | }
65 |
66 | for (i = 0; i < decodedInstructionsCount; i++) {
67 | // Note that we print the offset as a 64 bits variable!!!
68 | // It might be that you'll have to change it to %08X...
69 | DbgPrint("%08I64x (%02d) %s %s %s\n", decodedInstructions[i].offset, decodedInstructions[i].size,
70 | (char*)decodedInstructions[i].instructionHex.p,
71 | (char*)decodedInstructions[i].mnemonic.p,
72 | (char*)decodedInstructions[i].operands.p);
73 | }
74 |
75 | if (res == DECRES_SUCCESS || decodedInstructionsCount == 0) {
76 | break; // All instructions were decoded.
77 | }
78 |
79 | // Synchronize:
80 | next = (unsigned int)(decodedInstructions[decodedInstructionsCount-1].offset - offset);
81 | next += decodedInstructions[decodedInstructionsCount-1].size;
82 |
83 | // Advance ptr and recalc offset.
84 | buf += next;
85 | len -= next;
86 | offset += next;
87 | }
88 |
89 | DbgPrint(("Done!\n"));
90 | return STATUS_UNSUCCESSFUL; // Make sure the driver doesn't stay resident, so we can recompile and run again!
91 | }
92 |
--------------------------------------------------------------------------------
/distorm/examples/ddk/makefile:
--------------------------------------------------------------------------------
1 | !INCLUDE $(NTMAKEENV)\makefile.def
--------------------------------------------------------------------------------
/distorm/examples/ddk/sources:
--------------------------------------------------------------------------------
1 | TARGETNAME = distorm
2 | TARGETPATH = obj
3 | TARGETTYPE = DRIVER
4 |
5 | C_DEFINES = $(C_DEFINES) -DSUPPORT_64BIT_OFFSET -DLIBDISTORM
6 |
7 | INCLUDES = %BUILD%\inc;..\src;
8 | LIBS = %BUILD%\lib
9 |
10 | SOURCES = main.c
11 |
--------------------------------------------------------------------------------
/distorm/examples/java/Makefile:
--------------------------------------------------------------------------------
1 | UNAME_S := $(shell uname -s)
2 |
3 | ifeq ($(UNAME_S),Darwin)
4 |
5 | JAVA_HOME=$(shell /usr/libexec/java_home)
6 |
7 | all: libjdistorm.dylib
8 | libjdistorm.dylib: jdistorm.c jdistorm.h
9 | gcc -dynamiclib -o libjdistorm.dylib jdistorm.c -I ${JAVA_HOME}/include/ -I ${JAVA_HOME}/include/darwin/ -ldistorm3
10 |
11 | endif
12 |
13 | ifeq ($(UNAME_S),Linux)
14 |
15 | all: libjdistorm.so
16 | jdistorm.o: jdistorm.c jdistorm.h
17 | gcc -c jdistorm.c -fPIC -I ${JAVA_HOME}/include -I ${JAVA_HOME}/include/linux
18 |
19 | libjdistorm.so: jdistorm.o
20 | gcc -shared -o libjdistorm.so -L${JAVA_HOME}/jre/lib -ldistorm3 jdistorm.o
21 |
22 | endif
23 |
24 |
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | distorm
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Sun Oct 31 17:27:29 IST 2010
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.6
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.source=1.6
13 |
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/Main.java:
--------------------------------------------------------------------------------
1 | import java.nio.ByteBuffer;
2 |
3 | import diStorm3.distorm3.*;
4 | import diStorm3.CodeInfo;
5 | import diStorm3.DecodedInst;
6 | import diStorm3.OpcodeEnum;
7 | import diStorm3.distorm3;
8 | import diStorm3.DecodedResult;
9 | import diStorm3.DecomposedResult;
10 | import diStorm3.DecomposedInst;
11 |
12 | public class Main {
13 |
14 | public static void main(String[] args) {
15 | byte[] buf = new byte[4];
16 | buf[0] = (byte)0xc3;
17 | buf[1] = (byte)0x33;
18 | buf[2] = (byte)0xc0;
19 | buf[3] = (byte)0xc3;
20 | CodeInfo ci = new CodeInfo((long)0x1000, buf, DecodeType.Decode32Bits, 0);
21 | DecodedResult dr = new DecodedResult(10);
22 | distorm3.Decode(ci, dr);
23 |
24 | for (DecodedInst x : dr.mInstructions) {
25 | String s = String.format("%x %s %s", x.getOffset(), x.getMnemonic(), x.getOperands());
26 | System.out.println(s);
27 | }
28 |
29 | DecomposedResult dr2 = new DecomposedResult(10);
30 | distorm3.Decompose(ci, dr2);
31 |
32 | for (DecomposedInst y: dr2.mInstructions) {
33 | if (y.getOpcode() != OpcodeEnum.RET) {
34 | DecodedInst x = distorm3.Format(ci, y);
35 | String s = String.format("%x %s %s", x.getOffset(), x.getMnemonic(), x.getOperands());
36 | System.out.println(s);
37 | }
38 | }
39 |
40 | }
41 |
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/diStorm3/CodeInfo.java:
--------------------------------------------------------------------------------
1 | package diStorm3;
2 |
3 | import java.nio.ByteBuffer;
4 |
5 | public class CodeInfo {
6 | public CodeInfo(long codeOffset, ByteBuffer code, distorm3.DecodeType dt, int features) {
7 | mCodeOffset = codeOffset;
8 | mCode = code;
9 | mDecodeType = dt.ordinal();
10 | mFeatures = features;
11 | }
12 |
13 | public CodeInfo(long codeOffset, byte[] rawCode, distorm3.DecodeType dt, int features) {
14 | mCode = ByteBuffer.allocateDirect(rawCode.length);
15 | mCode.put(rawCode);
16 |
17 | mCodeOffset = codeOffset;
18 | mDecodeType = dt.ordinal();
19 | mFeatures = features;
20 | }
21 |
22 | private long mCodeOffset;
23 | private long mNextOffset;
24 | private ByteBuffer mCode;
25 | private int mDecodeType;
26 | private int mFeatures;
27 | }
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/diStorm3/DecodedInst.java:
--------------------------------------------------------------------------------
1 | package diStorm3;
2 |
3 | public class DecodedInst {
4 | DecodedInst()
5 | {
6 | }
7 | private String mMnemonic;
8 | private String mOperands;
9 | private String mHex;
10 | private int mSize;
11 | private long mOffset;
12 |
13 | public String getMnemonic() {
14 | return mMnemonic;
15 | }
16 |
17 | public String getOperands() {
18 | return mOperands;
19 | }
20 |
21 | public String getHex() {
22 | return mHex;
23 | }
24 |
25 | public int getSize() {
26 | return mSize;
27 | }
28 |
29 | public long getOffset() {
30 | return mOffset;
31 | }
32 | }
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/diStorm3/DecodedResult.java:
--------------------------------------------------------------------------------
1 | package diStorm3;
2 |
3 | public class DecodedResult {
4 | public DecodedResult(int maxInstructions) {
5 | mMaxInstructions = maxInstructions;
6 | mInstructions = null;
7 | }
8 |
9 | public DecodedInst[] mInstructions;
10 | private int mMaxInstructions;
11 | }
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/diStorm3/DecomposedInst.java:
--------------------------------------------------------------------------------
1 | package diStorm3;
2 |
3 | import diStorm3.Operand;
4 | import diStorm3.Opcodes;
5 |
6 | public class DecomposedInst {
7 | private class ImmVariant {
8 | private long mValue;
9 | private int mSize;
10 |
11 | public long getImm() {
12 | return mValue;
13 | }
14 |
15 | public int getSize() {
16 | return mSize;
17 | }
18 | }
19 |
20 | private class DispVariant {
21 |
22 | private long mDisplacement;
23 | private int mSize;
24 |
25 | public long getDisplacement() {
26 | return mDisplacement;
27 | }
28 |
29 | public int getSize() {
30 | return mSize;
31 | }
32 | }
33 |
34 | private long mAddr;
35 | private int mSize;
36 | private int mFlags;
37 | private int mSegment;
38 | private int mBase, mScale;
39 | private int mOpcode;
40 | public Operand[] mOperands;
41 | public DispVariant mDisp;
42 | public ImmVariant mImm;
43 | private int mUnusedPrefixesMask;
44 | private int mMeta;
45 | private int mRegistersMask;
46 | private int mModifiedFlagsMask;
47 | private int mTestedFlagsMask;
48 | private int mUndefinedFlagsMask;
49 |
50 | public long getAddress() {
51 | return mAddr;
52 | }
53 | public int getSize() {
54 | return mSize;
55 | }
56 | public OpcodeEnum getOpcode() {
57 | return Opcodes.lookup(mOpcode);
58 | }
59 | public int getSegment() {
60 | return mSegment & 0x7f;
61 | }
62 | public boolean isSegmentDefault() {
63 | return (mSegment & 0x80) == 0x80;
64 | }
65 | public int getBase() {
66 | return mBase;
67 | }
68 | public int getScale() {
69 | return mScale;
70 | }
71 | public int getUnusedPrefixesMask() {
72 | return mUnusedPrefixesMask;
73 | }
74 | public int getMeta() {
75 | return mMeta;
76 | }
77 | public int getRegistersMask() {
78 | return mRegistersMask;
79 | }
80 | public int getModifiedFlagsMask() {
81 | return mModifiedFlagsMask;
82 | }
83 | public int getTestedFlagsMask() {
84 | return mTestedFlagsMask;
85 | }
86 | public int getUndefinedFlagsMask() {
87 | return mUndefinedFlagsMask;
88 | }
89 | }
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/diStorm3/DecomposedResult.java:
--------------------------------------------------------------------------------
1 | package diStorm3;
2 |
3 | public class DecomposedResult {
4 | public DecomposedResult(int maxInstructions) {
5 | mMaxInstructions = maxInstructions;
6 | mInstructions = null;
7 | }
8 |
9 | public DecomposedInst[] mInstructions;
10 | private int mMaxInstructions;
11 | }
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/diStorm3/Operand.java:
--------------------------------------------------------------------------------
1 | package diStorm3;
2 |
3 | public class Operand {
4 |
5 | public enum OperandType {
6 | None, Reg, Imm, Imm1, Imm2, Disp, Smem, Mem, Pc, Ptr
7 | }
8 |
9 | private int mType;
10 | private int mIndex;
11 | private int mSize;
12 |
13 | public OperandType getType() {
14 | return OperandType.values()[mType];
15 | }
16 |
17 | public int getIndex() {
18 | return mIndex;
19 | }
20 |
21 | public int getSize() {
22 | return mSize;
23 | }
24 | }
--------------------------------------------------------------------------------
/distorm/examples/java/distorm/src/diStorm3/distorm3.java:
--------------------------------------------------------------------------------
1 | /*
2 | * diStorm3 JNI
3 | * Gil Dabah, Sep 2010
4 | *
5 | */
6 | package diStorm3;
7 | import diStorm3.CodeInfo;
8 | import diStorm3.DecodedResult;
9 | import diStorm3.DecomposedResult;
10 | import diStorm3.Opcodes;
11 |
12 | public class distorm3 {
13 |
14 | public enum DecodeType {
15 | Decode16Bits, Decode32Bits, Decode64Bits
16 | }
17 |
18 | public static native void Decompose(CodeInfo ci, DecomposedResult dr);
19 | public static native void Decode(CodeInfo ci, DecodedResult dr);
20 | public static native DecodedInst Format(CodeInfo ci, DecomposedInst di);
21 |
22 | public enum Registers {
23 | RAX, RCX, RDX, RBX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15,
24 | EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI, R8D, R9D, R10D, R11D, R12D, R13D, R14D, R15D,
25 | AX, CX, DX, BX, SP, BP, SI, DI, R8W, R9W, R10W, R11W, R12W, R13W, R14W, R15W,
26 | AL, CL, DL, BL, AH, CH, DH, BH, R8B, R9B, R10B, R11B, R12B, R13B, R14B, R15B,
27 | SPL, BPL, SIL, DIL,
28 | ES, CS, SS, DS, FS, GS,
29 | RIP,
30 | ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7,
31 | MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
32 | XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7, XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15,
33 | YMM0, YMM1, YMM2, YMM3, YMM4, YMM5, YMM6, YMM7, YMM8, YMM9, YMM10, YMM11, YMM12, YMM13, YMM14, YMM15,
34 | CR0, UNUSED0, CR2, CR3, CR4, UNUSED1, UNUSED2, UNUSED3, CR8,
35 | DR0, DR1, DR2, DR3, UNUSED4, UNUSED5, DR6, DR7
36 | };
37 |
38 | static {
39 | System.loadLibrary("jdistorm");
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/distorm/examples/java/jdistorm.h:
--------------------------------------------------------------------------------
1 | /* DO NOT EDIT THIS FILE - it is machine generated */
2 | #include
3 | /* Header for class Distorm3 */
4 |
5 | #ifndef _Included_Distorm3
6 | #define _Included_Distorm3
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 |
11 | #define PACKAGE_PREFIX "diStorm3/"
12 |
13 | /*
14 | * Class: com_reviverstudio_core_disasms_distorm3_Distorm3
15 | * Method: Decompose
16 | * Signature: (LdiStorm3/CodeInfo;LdiStorm3/DecomposedResult;)V
17 | */
18 | JNIEXPORT void JNICALL Java_diStorm3_distorm3_Decompose
19 | (JNIEnv *, jclass, jobject, jobject);
20 |
21 | /*
22 | * Class: com_reviverstudio_core_disasms_distorm3_Distorm3
23 | * Method: Decode
24 | * Signature: (LdiStorm3/CodeInfo;LdiStorm3/DecodedResult;)V
25 | */
26 | JNIEXPORT void JNICALL Java_diStorm3_distorm3_Decode
27 | (JNIEnv *, jclass, jobject, jobject);
28 |
29 | /*
30 | * Class: com_reviverstudio_core_disasms_distorm3_Distorm3
31 | * Method: Format
32 | * Signature: (LdiStorm3/CodeInfo;LdiStorm3/DecomposedInst;)LdiStorm3/DecodedInst;
33 | */
34 | JNIEXPORT jobject JNICALL Java_diStorm3_distorm3_Format
35 | (JNIEnv *, jclass, jobject, jobject);
36 |
37 | #ifdef __cplusplus
38 | }
39 | #endif
40 | #endif
41 |
--------------------------------------------------------------------------------
/distorm/examples/java/jdistorm.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 10.00
3 | # Visual Studio 2008
4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jdistorm", "jdistorm.vcproj", "{AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}"
5 | EndProject
6 | Global
7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
8 | Debug|x64 = Debug|x64
9 | Release|x64 = Release|x64
10 | EndGlobalSection
11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
12 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Debug|x64.ActiveCfg = Debug|x64
13 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Debug|x64.Build.0 = Debug|x64
14 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Release|x64.ActiveCfg = Release|x64
15 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Release|x64.Build.0 = Release|x64
16 | EndGlobalSection
17 | GlobalSection(SolutionProperties) = preSolution
18 | HideSolutionNode = FALSE
19 | EndGlobalSection
20 | EndGlobal
21 |
--------------------------------------------------------------------------------
/distorm/examples/java/jdistorm.vcproj:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
15 |
16 |
17 |
18 |
19 |
26 |
29 |
32 |
35 |
38 |
42 |
55 |
58 |
61 |
64 |
73 |
76 |
79 |
82 |
85 |
88 |
91 |
94 |
95 |
103 |
106 |
109 |
112 |
115 |
119 |
131 |
134 |
137 |
140 |
153 |
156 |
159 |
162 |
165 |
168 |
171 |
174 |
175 |
176 |
177 |
178 |
179 |
184 |
187 |
188 |
189 |
194 |
197 |
198 |
199 |
204 |
205 |
206 |
207 |
208 |
209 |
--------------------------------------------------------------------------------
/distorm/examples/linux/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # diStorm (Linux Port) / Demo Application Makefile
3 | #
4 |
5 | TARGET = disasm
6 | CC = gcc
7 | CFLAGS = -Wall -O2 -o
8 |
9 | all: disasm
10 |
11 | disasm:
12 | ${CC} ${CFLAGS} ${TARGET} main.c ../../distorm3.a
13 |
14 | clean:
15 | /bin/rm -rf *.o ${TARGET}
16 |
--------------------------------------------------------------------------------
/distorm/examples/linux/main.c:
--------------------------------------------------------------------------------
1 | // diStorm64 library sample
2 | // http://ragestorm.net/distorm/
3 | // Arkon, Stefan, 2005
4 | // Mikhail, 2006
5 | // JvW, 2007
6 |
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 | // For the compilers who don't have sysexits.h, which is not an ISO/ANSI include!
15 | #define EX_OK 0
16 | #define EX_USAGE 64
17 | #define EX_DATAERR 65
18 | #define EX_NOINPUT 66
19 | #define EX_NOUSER 67
20 | #define EX_NOHOST 68
21 | #define EX_UNAVAILABLE 69
22 | #define EX_SOFTWARE 70
23 | #define EX_OSERR 71
24 | #define EX_OSFILE 72
25 | #define EX_CANTCREAT 73
26 | #define EX_IOERR 74
27 | #define EX_TEMPFAIL 75
28 | #define EX_PROTOCOL 76
29 | #define EX_NOPERM 77
30 | #define EX_CONFIG 78
31 |
32 | #include "../../include/distorm.h"
33 |
34 | // The number of the array of instructions the decoder function will use to return the disassembled instructions.
35 | // Play with this value for performance...
36 | #define MAX_INSTRUCTIONS (1000)
37 |
38 | int main(int argc, char **argv)
39 | {
40 | // Version of used compiled library.
41 | unsigned int dver = 0;
42 | // Holds the result of the decoding.
43 | _DecodeResult res;
44 | // Decoded instruction information.
45 | _DecodedInst decodedInstructions[MAX_INSTRUCTIONS];
46 | // next is used for instruction's offset synchronization.
47 | // decodedInstructionsCount holds the count of filled instructions' array by the decoder.
48 | unsigned int decodedInstructionsCount = 0, i, next;
49 |
50 | // Default decoding mode is 32 bits, could be set by command line.
51 | _DecodeType dt = Decode32Bits;
52 |
53 | // Default offset for buffer is 0, could be set in command line.
54 | _OffsetType offset = 0;
55 | char* errch = NULL;
56 |
57 | // Index to file name in argv.
58 | int param = 1;
59 |
60 | // Handling file.
61 | FILE* f;
62 | unsigned long filesize = 0, bytesread = 0;
63 | struct stat st;
64 |
65 | // Buffer to disassemble.
66 | unsigned char *buf, *buf2;
67 |
68 | // Disassembler version.
69 | dver = distorm_version();
70 | printf("diStorm version: %u.%u.%u\n", (dver >> 16), ((dver) >> 8) & 0xff, dver & 0xff);
71 |
72 | // Check params.
73 | if (argc < 2 || argc > 4) {
74 | printf("Usage: ./disasm [-b16] [-b64] filename [memory offset]\r\nRaw disassembler output.\r\nMemory offset is origin of binary file in memory (address in hex).\r\nDefault decoding mode is -b32.\r\nexample: disasm -b16 demo.com 789a\r\n");
75 | return EX_USAGE;
76 | }
77 |
78 | if (strncmp(argv[param], "-b16", 4) == 0) {
79 | dt = Decode16Bits;
80 | param++;
81 | } else if (strncmp(argv[param], "-b64", 4) == 0) {
82 | dt = Decode64Bits;
83 | param++;
84 | } else if (*argv[param] == '-') {
85 | fputs("Decoding mode size isn't specified!\n", stderr);
86 | return EX_USAGE;
87 | } else if (argc == 4) {
88 | fputs("Too many parameters are set.\n", stderr);
89 | return EX_USAGE;
90 | }
91 | if (param >= argc) {
92 | fputs("Filename is missing.\n", stderr);
93 | return EX_USAGE;
94 | }
95 | if (param + 1 == argc-1) { // extra param?
96 | #ifdef SUPPORT_64BIT_OFFSET
97 | offset = strtoull(argv[param + 1], &errch, 16);
98 | #else
99 | offset = strtoul(argv[param + 1], &errch, 16);
100 | #endif
101 | if (*errch != '\0') {
102 | fprintf(stderr, "Offset `%s' couldn't be converted.\n", argv[param + 1]);
103 | return EX_USAGE;
104 | }
105 | }
106 |
107 | f = fopen(argv[param], "rb");
108 | if (f == NULL) {
109 | perror(argv[param]);
110 | return EX_NOINPUT;
111 | }
112 |
113 | if (fstat(fileno(f), &st) != 0) {
114 | perror("fstat");
115 | fclose(f);
116 | return EX_NOINPUT;
117 | }
118 | filesize = st.st_size;
119 |
120 | // We read the whole file into memory in order to make life easier,
121 | // otherwise we would have to synchronize the code buffer as well (so instructions won't be split).
122 | buf2 = buf = malloc(filesize);
123 | if (buf == NULL) {
124 | perror("File too large.");
125 | fclose(f);
126 | return EX_UNAVAILABLE;
127 | }
128 | bytesread = fread(buf, 1, filesize, f);
129 | if (bytesread != filesize) {
130 | perror("Can't read file into memory.");
131 | free(buf);
132 | fclose(f);
133 | return EX_IOERR;
134 | }
135 |
136 | fclose(f);
137 |
138 | printf("bits: %d\nfilename: %s\norigin: ", dt == Decode16Bits ? 16 : dt == Decode32Bits ? 32 : 64, argv[param]);
139 | #ifdef SUPPORT_64BIT_OFFSET
140 | if (dt != Decode64Bits) printf("%08llx\n", offset);
141 | else printf("%016llx\n", offset);
142 | #else
143 | printf("%08x\n", offset);
144 | #endif
145 |
146 | // Decode the buffer at given offset (virtual address).
147 | while (1) {
148 | // If you get an undefined reference linker error for the following line,
149 | // change the SUPPORT_64BIT_OFFSET in distorm.h.
150 | res = distorm_decode(offset, (const unsigned char*)buf, filesize, dt, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount);
151 | if (res == DECRES_INPUTERR) {
152 | // Null buffer? Decode type not 16/32/64?
153 | fputs("Input error, halting!\n", stderr);
154 | free(buf2);
155 | return EX_SOFTWARE;
156 | }
157 |
158 | for (i = 0; i < decodedInstructionsCount; i++)
159 | #ifdef SUPPORT_64BIT_OFFSET
160 | printf("%0*llx (%02d) %-24s %s%s%s\r\n", dt != Decode64Bits ? 8 : 16, decodedInstructions[i].offset, decodedInstructions[i].size, (char*)decodedInstructions[i].instructionHex.p, (char*)decodedInstructions[i].mnemonic.p, decodedInstructions[i].operands.length != 0 ? " " : "", (char*)decodedInstructions[i].operands.p);
161 | #else
162 | printf("%08x (%02d) %-24s %s%s%s\r\n", decodedInstructions[i].offset, decodedInstructions[i].size, (char*)decodedInstructions[i].instructionHex.p, (char*)decodedInstructions[i].mnemonic.p, decodedInstructions[i].operands.length != 0 ? " " : "", (char*)decodedInstructions[i].operands.p);
163 | #endif
164 |
165 | if (res == DECRES_SUCCESS) break; // All instructions were decoded.
166 | else if (decodedInstructionsCount == 0) break;
167 |
168 | // Synchronize:
169 | next = (unsigned int)(decodedInstructions[decodedInstructionsCount-1].offset - offset);
170 | next += decodedInstructions[decodedInstructionsCount-1].size;
171 | // Advance ptr and recalc offset.
172 | buf += next;
173 | filesize -= next;
174 | offset += next;
175 | }
176 |
177 | // Release buffer
178 | free(buf2);
179 |
180 | return EX_OK;
181 | }
182 |
--------------------------------------------------------------------------------
/distorm/examples/tests/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # diStorm (Linux Port) / Demo Application Makefile
3 | #
4 |
5 | TARGET = disasm
6 | CC = gcc
7 | CFLAGS = -Wall -O2 -I. -o
8 |
9 | all: disasm
10 |
11 | disasm:
12 | ${CC} ${CFLAGS} ${TARGET} main.cpp ../distorm64.a
13 |
14 | clean:
15 | /bin/rm -rf *.o ${TARGET}
16 |
--------------------------------------------------------------------------------
/distorm/examples/tests/main.cpp:
--------------------------------------------------------------------------------
1 | // diStorm64 library sample
2 | // http://ragestorm.net/distorm/
3 | // Arkon, Stefan, 2005
4 |
5 |
6 | #include
7 | #include
8 |
9 | #pragma comment(lib, "../../distorm.lib")
10 |
11 | #include "../../include/distorm.h"
12 |
13 | // The number of the array of instructions the decoder function will use to return the disassembled instructions.
14 | // Play with this value for performance...
15 | #define MAX_INSTRUCTIONS (1000)
16 |
17 | int main(int argc, char **argv)
18 | {
19 | _DecodeResult res;
20 | _DecodedInst decodedInstructions[1000];
21 | unsigned int decodedInstructionsCount = 0, i = 0;
22 | _OffsetType offset = 0;
23 | unsigned int dver = distorm_version();
24 | printf("diStorm version: %d.%d.%d\n", (dver >> 16), ((dver) >> 8) & 0xff, dver & 0xff);
25 |
26 | unsigned char rawData[] = {
27 |
28 | 0x68, 0, 0, 0, 0,
29 | 0x9b,
30 | 0xdf, 0xe0,
31 | 0x66, 0xa1, 0xcc, 0xb0, 0x97, 0x7c,
32 | 0xC7, 0xC1, 0x08, 0x00, 0x00, 0x00,
33 | 0xc7, 0xf8, 0xaa, 0xaa, 0xaa, 0xaa,
34 | 0x48, 0xC7, 0xC0, 0x00, 0x00, 0x00, 0x00
35 | } ;
36 | res = distorm_decode(offset, (const unsigned char*)rawData, sizeof(rawData), Decode64Bits, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount);
37 | for (int i = 0; i < decodedInstructionsCount; i++) {
38 | printf("%08I64x (%02d) %-24s %s%s%s\r\n", decodedInstructions[i].offset, decodedInstructions[i].size, (char*)decodedInstructions[i].instructionHex.p, (char*)decodedInstructions[i].mnemonic.p, decodedInstructions[i].operands.length != 0 ? " " : "", (char*)decodedInstructions[i].operands.p);
39 | }
40 |
41 | return 0;
42 | }
43 |
--------------------------------------------------------------------------------
/distorm/examples/tests/main.py:
--------------------------------------------------------------------------------
1 | #import distorm
2 | from pyasm import *
3 | from distorm3 import *
4 |
5 | _REGS = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15",
6 | "EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI", "R8D", "R9D", "R10D", "R11D", "R12D", "R13D", "R14D", "R15D",
7 | "AX", "CX", "DX", "BX", "SP", "BP", "SI", "DI", "R8W", "R9W", "R10W", "R11W", "R12W", "R13W", "R14W", "R15W",
8 | "AL", "CL", "DL", "BL", "AH", "CH", "DH", "BH", "R8B", "R9B", "R10B", "R11B", "R12B", "R13B", "R14B", "R15B",
9 | "SPL", "BPL", "SIL", "DIL",
10 | "ES", "CS", "SS", "DS", "FS", "GS",
11 | "RIP",
12 | "ST0", "ST1", "ST2", "ST3", "ST4", "ST5", "ST6", "ST7",
13 | "MM0", "MM1", "MM2", "MM3", "MM4", "MM5", "MM6", "MM7",
14 | "XMM0", "XMM1", "XMM2", "XMM3", "XMM4", "XMM5", "XMM6", "XMM7", "XMM8", "XMM9", "XMM10", "XMM11", "XMM12", "XMM13", "XMM14", "XMM15",
15 | "YMM0", "YMM1", "YMM2", "YMM3", "YMM4", "YMM5", "YMM6", "YMM7", "YMM8", "YMM9", "YMM10", "YMM11", "YMM12", "YMM13", "YMM14", "YMM15",
16 | "CR0", "", "CR2", "CR3", "CR4", "", "", "", "CR8",
17 | "DR0", "DR1", "DR2", "DR3", "", "", "DR6", "DR7"]
18 |
19 | def decode(x, mode = 1):
20 | sizes = [16, 32, 64]
21 | x = Assemble(x, sizes[mode])
22 | print x.encode('hex')
23 | #print distorm.Decode(0, x, mode)
24 | print Decode(0, x, mode)
25 |
26 | #decode("bswap ecx", 1)
27 | #distorm3.Decode(0, "480fc3c0".decode('hex'), 2)
28 |
29 |
30 | def xxx(x):
31 | buf = "".join(map(lambda txt: Assemble(txt, 32), x.split("\n")))
32 | print ",0x".join(map(lambda x: "%02x" % ord(x), buf))
33 | return Decode(0, buf, Decode32Bits)[0]
34 |
35 | def yyy(inst):
36 | print "%x (%d): " % (inst["addr"], inst["size"])
37 | print inst
38 | ops = filter(lambda x:x is not None, inst["ops"])
39 | for o in ops:
40 | if o["type"] == O_REG:
41 | print _REGS[o["index"]]
42 | elif o["type"] == O_IMM:
43 | print hex(inst["imm"])
44 | elif o["type"] == O_MEM:
45 | print "[",
46 | if inst["base"] != R_NONE:
47 | print _REGS[inst["base"]],
48 | print "+",
49 | print _REGS[o["index"]],
50 | if inst["scale"] != 0:
51 | print "*%d" % inst["scale"],
52 | if inst["dispSize"] != 0:
53 | print " + 0x%x" % (inst["disp"]),
54 | print "]"
55 | elif o["type"] == O_SMEM:
56 | print "[%s" % (_REGS[o["index"]]),
57 | if inst["dispSize"] != 0:
58 | print " + 0x%x" % (inst["disp"]),
59 | print "]"
60 | elif o["type"] == O_DISP:
61 | print "[0x%x]" % inst["disp"]
62 | elif o["type"] == O_PC:
63 | print hex(inst["imm"])
64 |
65 | #yyy(Decode(0, "0fae38".decode('hex'), Decode32Bits)[0])
66 | yyy(xxx("mov eax, [ebp*4]"))
67 |
--------------------------------------------------------------------------------
/distorm/examples/tests/tests.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 11.00
3 | # Visual Studio 2010
4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tests", "tests.vcxproj", "{C35D3921-227A-432A-BB5D-90ECEBAB08B2}"
5 | EndProject
6 | Global
7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
8 | Debug|Win32 = Debug|Win32
9 | Release|Win32 = Release|Win32
10 | EndGlobalSection
11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
12 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Debug|Win32.ActiveCfg = Debug|Win32
13 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Debug|Win32.Build.0 = Debug|Win32
14 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Release|Win32.ActiveCfg = Release|Win32
15 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Release|Win32.Build.0 = Release|Win32
16 | EndGlobalSection
17 | GlobalSection(SolutionProperties) = preSolution
18 | HideSolutionNode = FALSE
19 | EndGlobalSection
20 | EndGlobal
21 |
--------------------------------------------------------------------------------
/distorm/examples/tests/tests.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Release
10 | Win32
11 |
12 |
13 |
14 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}
15 | Win32Proj
16 | tests
17 |
18 |
19 |
20 | Application
21 | true
22 | Unicode
23 |
24 |
25 | Application
26 | false
27 | true
28 | Unicode
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 | true
42 |
43 |
44 | false
45 |
46 |
47 |
48 |
49 |
50 | Level3
51 | Disabled
52 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)
53 |
54 |
55 | Console
56 | true
57 |
58 |
59 |
60 |
61 | Level3
62 |
63 |
64 | MaxSpeed
65 | true
66 | true
67 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
68 |
69 |
70 | Console
71 | true
72 | true
73 | true
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/distorm/examples/tests/tests.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hpp;hxx;hm;inl;inc;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 |
18 |
19 | Source Files
20 |
21 |
22 |
--------------------------------------------------------------------------------
/distorm/examples/win32/disasm.sln:
--------------------------------------------------------------------------------
1 | Microsoft Visual Studio Solution File, Format Version 11.00
2 | # Visual Studio 2010
3 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "disasm", "disasm.vcxproj", "{91227BA8-F7EB-43CC-8C4A-A4944C00567B}"
4 | EndProject
5 | Global
6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
7 | Debug|Win32 = Debug|Win32
8 | Debug|x64 = Debug|x64
9 | Release|Win32 = Release|Win32
10 | Release|x64 = Release|x64
11 | EndGlobalSection
12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
13 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|Win32.ActiveCfg = Debug|Win32
14 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|Win32.Build.0 = Debug|Win32
15 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|x64.ActiveCfg = Debug|x64
16 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|x64.Build.0 = Debug|x64
17 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|Win32.ActiveCfg = Release|Win32
18 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|Win32.Build.0 = Release|Win32
19 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|x64.ActiveCfg = Release|x64
20 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|x64.Build.0 = Release|x64
21 | EndGlobalSection
22 | GlobalSection(SolutionProperties) = preSolution
23 | HideSolutionNode = FALSE
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/distorm/examples/win32/disasm.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 |
10 |
11 | Source Files
12 |
13 |
14 |
--------------------------------------------------------------------------------
/distorm/examples/win32/main.cpp:
--------------------------------------------------------------------------------
1 | // diStorm64 library sample
2 | // http://ragestorm.net/distorm/
3 | // Arkon, Stefan, 2005
4 |
5 |
6 | #include
7 | #include
8 | #include
9 | #include
10 |
11 | #include "../../include/distorm.h"
12 |
13 | // Link the library into our project.
14 | #pragma comment(lib, "../../distorm.lib")
15 |
16 | // The number of the array of instructions the decoder function will use to return the disassembled instructions.
17 | // Play with this value for performance...
18 | #define MAX_INSTRUCTIONS (1000)
19 |
20 | int main(int argc, char **argv)
21 | {
22 | // Version of used compiled library.
23 | unsigned long dver = 0;
24 | // Holds the result of the decoding.
25 | _DecodeResult res;
26 | // Decoded instruction information.
27 | _DecodedInst decodedInstructions[MAX_INSTRUCTIONS];
28 | // next is used for instruction's offset synchronization.
29 | // decodedInstructionsCount holds the count of filled instructions' array by the decoder.
30 | unsigned int decodedInstructionsCount = 0, i, next;
31 |
32 | // Default decoding mode is 32 bits, could be set by command line.
33 | _DecodeType dt = Decode32Bits;
34 |
35 | // Default offset for buffer is 0, could be set in command line.
36 | _OffsetType offset = 0;
37 | char* errch = NULL;
38 |
39 | // Index to file name in argv.
40 | int param = 1;
41 |
42 | // Handling file.
43 | HANDLE file;
44 | DWORD filesize, bytesread;
45 |
46 | // Buffer to disassemble.
47 | unsigned char *buf, *buf2;
48 |
49 | // Disassembler version.
50 | dver = distorm_version();
51 | printf("diStorm version: %d.%d.%d\n", (dver >> 16), ((dver) >> 8) & 0xff, dver & 0xff);
52 |
53 | // Check params.
54 | if (argc < 2 || argc > 4) {
55 | printf("Usage: disasm.exe [-b16] [-b64] filename [memory offset]\r\nRaw disassembler output.\r\nMemory offset is origin of binary file in memory (address in hex).\r\nDefault decoding mode is -b32.\r\nexample: disasm -b16 demo.com 789a\r\n");
56 | return -1;
57 | }
58 |
59 | if (strncmp(argv[param], "-b16", 4) == 0) {
60 | dt = Decode16Bits;
61 | param++;
62 | } else if (strncmp(argv[param], "-b64", 4) == 0) {
63 | dt = Decode64Bits;
64 | param++;
65 | } else if (*argv[param] == '-') {
66 | printf("Decoding mode size isn't specified!");
67 | return -1;
68 | } else if (argc == 4) {
69 | printf("Too many parameters are set.");
70 | return -1;
71 | }
72 | if (param >= argc) {
73 | printf("Filename is missing.");
74 | return -1;
75 | }
76 | if (param + 1 == argc-1) { // extra param?
77 | #ifdef SUPPORT_64BIT_OFFSET
78 | offset = _strtoui64(argv[param + 1], &errch, 16);
79 | #else
80 | offset = strtoul(argv[param + 1], &errch, 16);
81 | #endif
82 | if (*errch != '\0') {
83 | printf("Offset couldn't be converted.");
84 | return -1;
85 | }
86 | }
87 |
88 | file = CreateFile(argv[param], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
89 | if (file == INVALID_HANDLE_VALUE) {
90 | printf("Could not open file %s (error %d)\n", argv[param], GetLastError());
91 | return -2;
92 | }
93 |
94 | if ((filesize = GetFileSize(file, NULL)) < 0) {
95 | printf("Error getting filesize (error %d)\n", GetLastError());
96 | CloseHandle(file);
97 | return -3;
98 | }
99 |
100 | // We read the whole file into memory in order to make life easier,
101 | // otherwise we would have to synchronize the code buffer as well (so instructions won't be split).
102 | buf2 = buf = (unsigned char*)malloc(filesize);
103 | if (!ReadFile(file, buf, filesize, &bytesread, NULL)) {
104 | printf("Error reading file (error %d)\n", GetLastError());
105 | CloseHandle(file);
106 | free(buf);
107 | return -3;
108 | }
109 |
110 | if (filesize != bytesread) {
111 | printf("Internal read-error in system\n");
112 | CloseHandle(file);
113 | free(buf);
114 | return -3;
115 | }
116 |
117 | CloseHandle(file);
118 |
119 | printf("bits: %d\nfilename: %s\norigin: ", dt == Decode16Bits ? 16 : dt == Decode32Bits ? 32 : 64, argv[param]);
120 | #ifdef SUPPORT_64BIT_OFFSET
121 | if (dt != Decode64Bits) printf("%08I64x\n", offset);
122 | else printf("%016I64x\n", offset);
123 | #else
124 | printf("%08x\n", offset);
125 | #endif
126 |
127 | // Decode the buffer at given offset (virtual address).
128 | while (1) {
129 | // If you get an unresolved external symbol linker error for the following line,
130 | // change the SUPPORT_64BIT_OFFSET in distorm.h.
131 | res = distorm_decode(offset, (const unsigned char*)buf, filesize, dt, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount);
132 | if (res == DECRES_INPUTERR) {
133 | // Null buffer? Decode type not 16/32/64?
134 | printf("Input error, halting!");
135 | free(buf2);
136 | return -4;
137 | }
138 |
139 | for (i = 0; i < decodedInstructionsCount; i++) {
140 | #ifdef SUPPORT_64BIT_OFFSET
141 | printf("%0*I64x (%02d) %-24s %s%s%s\n", dt != Decode64Bits ? 8 : 16, decodedInstructions[i].offset, decodedInstructions[i].size, (char*)decodedInstructions[i].instructionHex.p, (char*)decodedInstructions[i].mnemonic.p, decodedInstructions[i].operands.length != 0 ? " " : "", (char*)decodedInstructions[i].operands.p);
142 | #else
143 | printf("%08x (%02d) %-24s %s%s%s\n", decodedInstructions[i].offset, decodedInstructions[i].size, (char*)decodedInstructions[i].instructionHex.p, (char*)decodedInstructions[i].mnemonic.p, decodedInstructions[i].operands.length != 0 ? " " : "", (char*)decodedInstructions[i].operands.p);
144 | #endif
145 | }
146 |
147 | if (res == DECRES_SUCCESS) break; // All instructions were decoded.
148 | else if (decodedInstructionsCount == 0) break;
149 |
150 | // Synchronize:
151 | next = (unsigned long)(decodedInstructions[decodedInstructionsCount-1].offset - offset);
152 | next += decodedInstructions[decodedInstructionsCount-1].size;
153 | // Advance ptr and recalc offset.
154 | buf += next;
155 | filesize -= next;
156 | offset += next;
157 | }
158 |
159 | // Release buffer
160 | free(buf2);
161 |
162 | return 0;
163 | }
164 |
--------------------------------------------------------------------------------
/distorm/make/linux/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # diStorm3 (Linux Port)
3 | #
4 |
5 | TARGET = libdistorm3.so
6 | COBJS = ../../src/mnemonics.o ../../src/wstring.o ../../src/textdefs.o ../../src/prefix.o ../../src/operands.o ../../src/insts.o ../../src/instructions.o ../../src/distorm.o ../../src/decoder.o
7 | CC = gcc
8 | CFLAGS += -fPIC -O2 -Wall -DSUPPORT_64BIT_OFFSET -DDISTORM_STATIC
9 | LDFLAGS += -shared
10 | PREFIX = /usr/local
11 | DESTDIR =
12 |
13 | all: clib
14 |
15 | clean:
16 | /bin/rm -rf ../../src/*.o ${TARGET} ../../distorm3.a ./../*.o
17 |
18 | clib: ${COBJS}
19 | ${CC} ${CFLAGS} ${VERSION} ${COBJS} ${LDFLAGS} -o ${TARGET}
20 | ar rs ../../distorm3.a ${COBJS}
21 |
22 | install: libdistorm3.so
23 | install -D -s ${TARGET} ${DESTDIR}/${PREFIX}/lib/${TARGET}
24 | @echo "... running ldconfig might be smart ..."
25 |
26 | .c.o:
27 | ${CC} ${CFLAGS} ${VERSION} -c $< -o $@
28 |
29 |
--------------------------------------------------------------------------------
/distorm/make/mac/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # diStorm3 (Mac Port)
3 | #
4 |
5 | TARGET = libdistorm3.dylib
6 | PYTHON_BUILD_DIR = ../../Python/macosx-x86
7 | COBJS = ../../src/mnemonics.o ../../src/wstring.o ../../src/textdefs.o ../../src/prefix.o ../../src/operands.o ../../src/insts.o ../../src/instructions.o ../../src/distorm.o ../../src/decoder.o
8 | CC = gcc
9 | CFLAGS = -arch i386 -arch x86_64 -O2 -Wall -fPIC -DSUPPORT_64BIT_OFFSET -DDISTORM_DYNAMIC
10 |
11 | all: clib
12 |
13 | clean:
14 | /bin/rm -rf ../../src/*.o ${TARGET} ../../libdistorm3.dylib ../../distorm3.a ../../*.a
15 |
16 | clib: ${COBJS}
17 | ${CC} ${CFLAGS} ${VERSION} ${COBJS} -fPIC -dynamiclib -o ${TARGET}
18 | [ -d ${PYTHON_BUILD_DIR} ] && rm -rf ${PYTHON_BUILD_DIR} || true
19 | mkdir ${PYTHON_BUILD_DIR}
20 | cp ${TARGET} ${PYTHON_BUILD_DIR}/
21 | #ar rs ../../distorm3.a ${COBJS}
22 |
23 | .c.o:
24 | ${CC} ${CFLAGS} ${VERSION} -c $< -o $@
25 |
--------------------------------------------------------------------------------
/distorm/make/win32/cdistorm.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {50ac9ad6-0895-4596-b142-1a7fad1b97d5}
6 | cpp;c;cxx;def;odl;idl;hpj;bat;asm
7 |
8 |
9 | {8612ae75-7b41-4557-b23b-d3e14e7f9613}
10 | h;hpp;hxx;hm;inl;inc
11 |
12 |
13 |
14 |
15 | Source Files
16 |
17 |
18 | Source Files
19 |
20 |
21 | Source Files
22 |
23 |
24 | Source Files
25 |
26 |
27 | Source Files
28 |
29 |
30 | Source Files
31 |
32 |
33 | Source Files
34 |
35 |
36 | Source Files
37 |
38 |
39 | Source Files
40 |
41 |
42 | Source Files
43 |
44 |
45 |
46 |
47 | Header Files
48 |
49 |
50 | Header Files
51 |
52 |
53 | Header Files
54 |
55 |
56 | Header Files
57 |
58 |
59 | Header Files
60 |
61 |
62 | Header Files
63 |
64 |
65 | Header Files
66 |
67 |
68 | Header Files
69 |
70 |
71 | Header Files
72 |
73 |
74 | Header Files
75 |
76 |
77 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/distorm/make/win32/distorm.sln:
--------------------------------------------------------------------------------
1 | Microsoft Visual Studio Solution File, Format Version 11.00
2 | # Visual Studio 2010
3 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "distorm", "cdistorm.vcxproj", "{15051CE1-AB10-4239-973D-01B84F2AD0A9}"
4 | EndProject
5 | Global
6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
7 | clib|Win32 = clib|Win32
8 | clib|x64 = clib|x64
9 | dll|Win32 = dll|Win32
10 | dll|x64 = dll|x64
11 | EndGlobalSection
12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
13 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|Win32.ActiveCfg = clib|Win32
14 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|Win32.Build.0 = clib|Win32
15 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|x64.ActiveCfg = clib|x64
16 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|x64.Build.0 = clib|x64
17 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|Win32.ActiveCfg = dll|Win32
18 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|Win32.Build.0 = dll|Win32
19 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|x64.ActiveCfg = dll|x64
20 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|x64.Build.0 = dll|x64
21 | EndGlobalSection
22 | GlobalSection(SolutionProperties) = preSolution
23 | HideSolutionNode = FALSE
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/distorm/make/win32/resource.h:
--------------------------------------------------------------------------------
1 | //{{NO_DEPENDENCIES}}
2 | // Microsoft Visual C++ generated include file.
3 | // Used by resource.rc
4 |
5 | // Next default values for new objects
6 | //
7 | #ifdef APSTUDIO_INVOKED
8 | #ifndef APSTUDIO_READONLY_SYMBOLS
9 | #define _APS_NEXT_RESOURCE_VALUE 101
10 | #define _APS_NEXT_COMMAND_VALUE 40001
11 | #define _APS_NEXT_CONTROL_VALUE 1001
12 | #define _APS_NEXT_SYMED_VALUE 101
13 | #endif
14 | #endif
15 |
--------------------------------------------------------------------------------
/distorm/make/win32/resource.rc:
--------------------------------------------------------------------------------
1 | // Microsoft Visual C++ generated resource script.
2 | //
3 | #include "resource.h"
4 |
5 | #define APSTUDIO_READONLY_SYMBOLS
6 | /////////////////////////////////////////////////////////////////////////////
7 | //
8 | // Generated from the TEXTINCLUDE 2 resource.
9 | //
10 | #include "afxres.h"
11 |
12 | /////////////////////////////////////////////////////////////////////////////
13 | #undef APSTUDIO_READONLY_SYMBOLS
14 |
15 | /////////////////////////////////////////////////////////////////////////////
16 | // English (United States) resources
17 |
18 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
19 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
20 | #pragma code_page(1252)
21 |
22 | #ifdef APSTUDIO_INVOKED
23 | /////////////////////////////////////////////////////////////////////////////
24 | //
25 | // TEXTINCLUDE
26 | //
27 |
28 | 1 TEXTINCLUDE
29 | BEGIN
30 | "resource.h\0"
31 | END
32 |
33 | 2 TEXTINCLUDE
34 | BEGIN
35 | "#include ""afxres.h""\r\n"
36 | "\0"
37 | END
38 |
39 | 3 TEXTINCLUDE
40 | BEGIN
41 | "\r\n"
42 | "\0"
43 | END
44 |
45 | #endif // APSTUDIO_INVOKED
46 |
47 |
48 | /////////////////////////////////////////////////////////////////////////////
49 | //
50 | // Version
51 | //
52 |
53 | VS_VERSION_INFO VERSIONINFO
54 | FILEVERSION 3,3,4,0
55 | PRODUCTVERSION 3,3,4,0
56 | FILEFLAGSMASK 0x17L
57 | #ifdef _DEBUG
58 | FILEFLAGS 0x1L
59 | #else
60 | FILEFLAGS 0x0L
61 | #endif
62 | FILEOS 0x4L
63 | FILETYPE 0x2L
64 | FILESUBTYPE 0x0L
65 | BEGIN
66 | BLOCK "StringFileInfo"
67 | BEGIN
68 | BLOCK "040904b0"
69 | BEGIN
70 | VALUE "FileDescription", "diStorm3 module"
71 | VALUE "FileVersion", "3.3.4.0"
72 | VALUE "InternalName", "diStorm3"
73 | VALUE "LegalCopyright", "Copyright (C) 2003-2016 Gil Dabah"
74 | VALUE "OriginalFilename", "diStorm3.dll"
75 | VALUE "ProductName", "diStorm3 Disassembler Library"
76 | VALUE "ProductVersion", "3.3.4.0"
77 | END
78 | END
79 | BLOCK "VarFileInfo"
80 | BEGIN
81 | VALUE "Translation", 0x409, 1200
82 | END
83 | END
84 |
85 | #endif // English (United States) resources
86 | /////////////////////////////////////////////////////////////////////////////
87 |
88 |
89 |
90 | #ifndef APSTUDIO_INVOKED
91 | /////////////////////////////////////////////////////////////////////////////
92 | //
93 | // Generated from the TEXTINCLUDE 3 resource.
94 | //
95 |
96 |
97 | /////////////////////////////////////////////////////////////////////////////
98 | #endif // not APSTUDIO_INVOKED
99 |
100 |
--------------------------------------------------------------------------------
/distorm/python/distorm3/sample.py:
--------------------------------------------------------------------------------
1 | # Mario Vilas, http://breakingcode.wordpress.com
2 | # Licensed under BSD in 2016
3 |
4 | # Example code
5 |
6 | import distorm3
7 | import sys
8 | import optparse
9 |
10 | # Parse the command line arguments
11 | usage = 'Usage: %prog [--b16 | --b32 | --b64] filename [offset]'
12 | parser = optparse.OptionParser(usage=usage)
13 | parser.add_option( '--b16', help='80286 decoding',
14 | action='store_const', dest='dt', const=distorm3.Decode16Bits )
15 | parser.add_option( '--b32', help='IA-32 decoding [default]',
16 | action='store_const', dest='dt', const=distorm3.Decode32Bits )
17 | parser.add_option( '--b64', help='AMD64 decoding',
18 | action='store_const', dest='dt', const=distorm3.Decode64Bits )
19 | parser.set_defaults(dt=distorm3.Decode32Bits)
20 | options, args = parser.parse_args(sys.argv)
21 | if len(args) < 2:
22 | parser.error('missing parameter: filename')
23 | filename = args[1]
24 | offset = 0
25 | length = None
26 | if len(args) == 3:
27 | try:
28 | offset = int(args[2], 10)
29 | except ValueError:
30 | parser.error('invalid offset: %s' % args[2])
31 | if offset < 0:
32 | parser.error('invalid offset: %s' % args[2])
33 | elif len(args) > 3:
34 | parser.error('too many parameters')
35 |
36 | # Read the code from the file
37 | try:
38 | code = open(filename, 'rb').read()
39 | except Exception as e:
40 | parser.error('error reading file %s: %s' % (filename, e))
41 |
42 | # Print each decoded instruction
43 | # This shows how to use the Deocode - Generator
44 | iterable = distorm3.DecodeGenerator(offset, code, options.dt)
45 | for (offset, size, instruction, hexdump) in iterable:
46 | print("%.8x: %-32s %s" % (offset, hexdump, instruction))
47 |
48 | # It could also be used as a returned list:
49 | # l = distorm3.Decode(offset, code, options.dt)
50 | # for (offset, size, instruction, hexdump) in l:
51 | # print("%.8x: %-32s %s" % (offset, hexdump, instruction))
52 |
--------------------------------------------------------------------------------
/distorm/setup.cfg:
--------------------------------------------------------------------------------
1 | [wheel]
2 | universal = 1
3 |
4 | [install]
5 | force=1
6 | compile=1
7 | optimize=1
8 |
9 | [bdist_wininst]
10 | user-access-control=auto
11 |
--------------------------------------------------------------------------------
/distorm/src/config.h:
--------------------------------------------------------------------------------
1 | /*
2 | config.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #ifndef CONFIG_H
13 | #define CONFIG_H
14 |
15 | /* diStorm version number. */
16 | #define __DISTORMV__ 0x030304
17 |
18 | #include /* memset, memcpy - can be easily self implemented for libc independency. */
19 |
20 | #include "../include/distorm.h"
21 |
22 |
23 | /*
24 | * 64 bit offsets support:
25 | * This macro should be defined from compiler command line flags, e.g: -DSUPPORT_64BIT_OFFSET
26 | * Note: make sure that the caller (library user) defines it too!
27 | */
28 | /* #define SUPPORT_64BIT_OFFSET */
29 |
30 | /*
31 | * If you compile diStorm as a dynamic library (.dll or .so) file, make sure you uncomment the next line.
32 | * So the interface functions will be exported, otherwise they are useable only for static library.
33 | * For example, this macro is being set for compiling diStorm as a .dll for Python with CTypes.
34 | */
35 | /* #define DISTORM_DYNAMIC */
36 |
37 | /*
38 | * If DISTORM_LIGHT is defined, everything involved in formatting the instructions
39 | * as text will be excluded from compilation.
40 | * distorm_decode(..) and distorm_format(..) will not be available.
41 | * This will decrease the size of the executable and leave you with decomposition functionality only.
42 | *
43 | * Note: it should be either set in the preprocessor definitions manually or in command line -D switch.
44 | * #define DISTORM_LIGHT
45 | */
46 |
47 | /*
48 | * diStorm now supports little/big endian CPU's.
49 | * It should detect the endianness according to predefined macro's of the compiler.
50 | * If you don't use GCC/MSVC you will have to define it on your own.
51 | */
52 |
53 | /* These macros are used in order to make the code portable. */
54 | #ifdef __GNUC__
55 |
56 | #include
57 |
58 | #define _DLLEXPORT_
59 | #define _FASTCALL_
60 | #define _INLINE_ static
61 | /* GCC ignores this directive... */
62 | /*#define _FASTCALL_ __attribute__((__fastcall__))*/
63 |
64 | /* Set endianity (supposed to be LE though): */
65 | #ifdef __BIG_ENDIAN__
66 | #define BE_SYSTEM
67 | #endif
68 |
69 | /* End of __GCC__ */
70 |
71 | #elif __WATCOMC__
72 |
73 | #include
74 |
75 | #define _DLLEXPORT_
76 | #define _FASTCALL_
77 | #define _INLINE_ __inline
78 |
79 | /* End of __WATCOMC__ */
80 |
81 | #elif __DMC__
82 |
83 | #include
84 |
85 | #define _DLLEXPORT_
86 | #define _FASTCALL_
87 | #define _INLINE_ __inline
88 |
89 | /* End of __DMC__ */
90 |
91 | #elif __TINYC__
92 |
93 | #include
94 |
95 | #define _DLLEXPORT_
96 | #define _FASTCALL_
97 | #define _INLINE_
98 |
99 | /* End of __TINYC__ */
100 |
101 | #elif _MSC_VER
102 |
103 | /* stdint alternative is defined in distorm.h */
104 |
105 | #define _DLLEXPORT_ __declspec(dllexport)
106 | #define _FASTCALL_ __fastcall
107 | #define _INLINE_ __inline
108 |
109 | /* Set endianity (supposed to be LE though): */
110 | #if !defined(_M_IX86) && !defined(_M_X64)
111 | #define BE_SYSTEM
112 | #endif
113 |
114 | #endif /* #elif _MSC_VER */
115 |
116 | /* If the library isn't compiled as a dynamic library don't export any functions. */
117 | #ifndef DISTORM_DYNAMIC
118 | #undef _DLLEXPORT_
119 | #define _DLLEXPORT_
120 | #endif
121 |
122 | #ifndef FALSE
123 | #define FALSE 0
124 | #endif
125 | #ifndef TRUE
126 | #define TRUE 1
127 | #endif
128 |
129 | /* Define stream read functions for big endian systems. */
130 | #ifdef BE_SYSTEM
131 | /*
132 | * These functions can read from the stream safely!
133 | * Swap endianity of input to little endian.
134 | */
135 | static _INLINE_ int16_t RSHORT(const uint8_t *s)
136 | {
137 | return s[0] | (s[1] << 8);
138 | }
139 | static _INLINE_ uint16_t RUSHORT(const uint8_t *s)
140 | {
141 | return s[0] | (s[1] << 8);
142 | }
143 | static _INLINE_ int32_t RLONG(const uint8_t *s)
144 | {
145 | return s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24);
146 | }
147 | static _INLINE_ uint32_t RULONG(const uint8_t *s)
148 | {
149 | return s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24);
150 | }
151 | static _INLINE_ int64_t RLLONG(const uint8_t *s)
152 | {
153 | return s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24) | ((uint64_t)s[4] << 32) | ((uint64_t)s[5] << 40) | ((uint64_t)s[6] << 48) | ((uint64_t)s[7] << 56);
154 | }
155 | static _INLINE_ uint64_t RULLONG(const uint8_t *s)
156 | {
157 | return s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24) | ((uint64_t)s[4] << 32) | ((uint64_t)s[5] << 40) | ((uint64_t)s[6] << 48) | ((uint64_t)s[7] << 56);
158 | }
159 | #else
160 | /* Little endian macro's will just make the cast. */
161 | #define RSHORT(x) *(int16_t *)x
162 | #define RUSHORT(x) *(uint16_t *)x
163 | #define RLONG(x) *(int32_t *)x
164 | #define RULONG(x) *(uint32_t *)x
165 | #define RLLONG(x) *(int64_t *)x
166 | #define RULLONG(x) *(uint64_t *)x
167 | #endif
168 |
169 | #endif /* CONFIG_H */
170 |
--------------------------------------------------------------------------------
/distorm/src/decoder.h:
--------------------------------------------------------------------------------
1 | /*
2 | decoder.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2011 Gil Dabah
8 |
9 | This program is free software: you can redistribute it and/or modify
10 | it under the terms of the GNU General Public License as published by
11 | the Free Software Foundation, either version 3 of the License, or
12 | (at your option) any later version.
13 |
14 | This program is distributed in the hope that it will be useful,
15 | but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | GNU General Public License for more details.
18 |
19 | You should have received a copy of the GNU General Public License
20 | along with this program. If not, see
21 | */
22 |
23 |
24 | #ifndef DECODER_H
25 | #define DECODER_H
26 |
27 | #include "config.h"
28 |
29 | typedef unsigned int _iflags;
30 |
31 | _DecodeResult decode_internal(_CodeInfo* ci, int supportOldIntr, _DInst result[], unsigned int maxResultCount, unsigned int* usedInstructionsCount);
32 |
33 | #endif /* DECODER_H */
34 |
--------------------------------------------------------------------------------
/distorm/src/insts.h:
--------------------------------------------------------------------------------
1 | /*
2 | insts.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #ifndef INSTS_H
13 | #define INSTS_H
14 |
15 | #include "instructions.h"
16 |
17 |
18 | /* Flags Table */
19 | extern _iflags FlagsTable[];
20 |
21 | /* Root Trie DB */
22 | extern _InstSharedInfo InstSharedInfoTable[];
23 | extern _InstInfo InstInfos[];
24 | extern _InstInfoEx InstInfosEx[];
25 | extern _InstNode InstructionsTree[];
26 |
27 | /* 3DNow! Trie DB */
28 | extern _InstNode Table_0F_0F;
29 | /* AVX related: */
30 | extern _InstNode Table_0F, Table_0F_38, Table_0F_3A;
31 |
32 | /*
33 | * The inst_lookup will return on of these two instructions according to the specified decoding mode.
34 | * ARPL or MOVSXD on 64 bits is one byte instruction at index 0x63.
35 | */
36 | extern _InstInfo II_MOVSXD;
37 |
38 | /*
39 | * The NOP instruction can be prefixed by REX in 64bits, therefore we have to decide in runtime whether it's an XCHG or NOP instruction.
40 | * If 0x90 is prefixed by a usable REX it will become XCHG, otherwise it will become a NOP.
41 | * Also note that if it's prefixed by 0xf3, it becomes a Pause.
42 | */
43 | extern _InstInfo II_NOP;
44 | extern _InstInfo II_PAUSE;
45 |
46 | /*
47 | * RDRAND and VMPTRLD share same 2.3 bytes opcode, and then alternates on the MOD bits,
48 | * RDRAND is OT_FULL_REG while VMPTRLD is OT_MEM, and there's no such mixed type.
49 | * So a hack into the inst_lookup was added for this decision, the DB isn't flexible enough. :(
50 | */
51 | extern _InstInfo II_RDRAND;
52 |
53 | /*
54 | * Used for letting the extract operand know the type of operands without knowing the
55 | * instruction itself yet, because of the way those instructions work.
56 | * See function instructions.c!inst_lookup_3dnow.
57 | */
58 | extern _InstInfo II_3DNOW;
59 |
60 | /* Helper tables for pseudo compare mnemonics. */
61 | extern uint16_t CmpMnemonicOffsets[8]; /* SSE */
62 | extern uint16_t VCmpMnemonicOffsets[32]; /* AVX */
63 |
64 | #endif /* INSTS_H */
65 |
--------------------------------------------------------------------------------
/distorm/src/operands.h:
--------------------------------------------------------------------------------
1 | /*
2 | operands.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #ifndef OPERANDS_H
13 | #define OPERANDS_H
14 |
15 | #include "config.h"
16 | #include "decoder.h"
17 | #include "prefix.h"
18 | #include "instructions.h"
19 |
20 |
21 | extern uint32_t _REGISTERTORCLASS[];
22 |
23 | int operands_extract(_CodeInfo* ci, _DInst* di, _InstInfo* ii,
24 | _iflags instFlags, _OpType type, _OperandNumberType opNum,
25 | unsigned int modrm, _PrefixState* ps, _DecodeType effOpSz,
26 | _DecodeType effAdrSz, int* lockableInstruction);
27 |
28 | #endif /* OPERANDS_H */
29 |
--------------------------------------------------------------------------------
/distorm/src/prefix.c:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/distorm/src/prefix.c
--------------------------------------------------------------------------------
/distorm/src/prefix.h:
--------------------------------------------------------------------------------
1 | /*
2 | prefix.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #ifndef PREFIX_H
13 | #define PREFIX_H
14 |
15 | #include "config.h"
16 | #include "decoder.h"
17 |
18 |
19 | /* Specifies the type of the extension prefix, such as: REX, 2 bytes VEX, 3 bytes VEX. */
20 | typedef enum {PET_NONE = 0, PET_REX, PET_VEX2BYTES, PET_VEX3BYTES} _PrefixExtType;
21 |
22 | /* Specifies an index into a table of prefixes by their type. */
23 | typedef enum {PFXIDX_NONE = -1, PFXIDX_REX, PFXIDX_LOREP, PFXIDX_SEG, PFXIDX_OP_SIZE, PFXIDX_ADRS, PFXIDX_MAX} _PrefixIndexer;
24 |
25 | /*
26 | * This holds the prefixes state for the current instruction we decode.
27 | * decodedPrefixes includes all specific prefixes that the instruction got.
28 | * start is a pointer to the first prefix to take into account.
29 | * last is a pointer to the last byte we scanned.
30 | * Other pointers are used to keep track of prefixes positions and help us know if they appeared already and where.
31 | */
32 | typedef struct {
33 | _iflags decodedPrefixes, usedPrefixes;
34 | const uint8_t *start, *last, *vexPos, *rexPos;
35 | _PrefixExtType prefixExtType;
36 | uint16_t unusedPrefixesMask;
37 | /* Indicates whether the operand size prefix (0x66) was used as a mandatory prefix. */
38 | int isOpSizeMandatory;
39 | /* If VEX prefix is used, store the VEX.vvvv field. */
40 | unsigned int vexV;
41 | /* The fields B/X/R/W/L of REX and VEX are stored together in this byte. */
42 | unsigned int vrex;
43 |
44 | /* !! Make sure pfxIndexer is LAST! Otherwise memset won't work well with it. !! */
45 |
46 | /* Holds the offset to the prefix byte by its type. */
47 | int pfxIndexer[PFXIDX_MAX];
48 | } _PrefixState;
49 |
50 | /*
51 | * Intel supports 6 types of prefixes, whereas AMD supports 5 types (lock is seperated from rep/nz).
52 | * REX is the fifth prefix type, this time I'm based on AMD64.
53 | * VEX is the 6th, though it can't be repeated.
54 | */
55 | #define MAX_PREFIXES (5)
56 |
57 | int prefixes_is_valid(unsigned int ch, _DecodeType dt);
58 | void prefixes_ignore(_PrefixState* ps, _PrefixIndexer pi);
59 | void prefixes_ignore_all(_PrefixState* ps);
60 | uint16_t prefixes_set_unused_mask(_PrefixState* ps);
61 | void prefixes_decode(const uint8_t* code, int codeLen, _PrefixState* ps, _DecodeType dt);
62 | void prefixes_use_segment(_iflags defaultSeg, _PrefixState* ps, _DecodeType dt, _DInst* di);
63 |
64 | #endif /* PREFIX_H */
65 |
--------------------------------------------------------------------------------
/distorm/src/textdefs.c:
--------------------------------------------------------------------------------
1 | /*
2 | textdefs.c
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #include "textdefs.h"
13 |
14 | #ifndef DISTORM_LIGHT
15 |
16 | static uint8_t Nibble2ChrTable[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
17 | #define NIBBLE_TO_CHR Nibble2ChrTable[t]
18 |
19 | void _FASTCALL_ str_hex_b(_WString* s, unsigned int x)
20 | {
21 | /*
22 | * def prebuilt():
23 | * s = ""
24 | * for i in xrange(256):
25 | * if ((i % 0x10) == 0):
26 | * s += "\r\n"
27 | * s += "\"%02x\", " % (i)
28 | * return s
29 | */
30 | static int8_t TextBTable[256][3] = {
31 | "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
32 | "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
33 | "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
34 | "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
35 | "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
36 | "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
37 | "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
38 | "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
39 | "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
40 | "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
41 | "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
42 | "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
43 | "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
44 | "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
45 | "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
46 | "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"
47 | };
48 |
49 | /*
50 | * Fixed length of 3 including null terminate character.
51 | */
52 | memcpy(&s->p[s->length], TextBTable[x & 255], 3);
53 | s->length += 2;
54 | }
55 |
56 | void _FASTCALL_ str_code_hb(_WString* s, unsigned int x)
57 | {
58 | static int8_t TextHBTable[256][5] = {
59 | /*
60 | * def prebuilt():
61 | * s = ""
62 | * for i in xrange(256):
63 | * if ((i % 0x10) == 0):
64 | * s += "\r\n"
65 | * s += "\"0x%x\", " % (i)
66 | * return s
67 | */
68 | "0x0", "0x1", "0x2", "0x3", "0x4", "0x5", "0x6", "0x7", "0x8", "0x9", "0xa", "0xb", "0xc", "0xd", "0xe", "0xf",
69 | "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1a", "0x1b", "0x1c", "0x1d", "0x1e", "0x1f",
70 | "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2a", "0x2b", "0x2c", "0x2d", "0x2e", "0x2f",
71 | "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3a", "0x3b", "0x3c", "0x3d", "0x3e", "0x3f",
72 | "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4a", "0x4b", "0x4c", "0x4d", "0x4e", "0x4f",
73 | "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5a", "0x5b", "0x5c", "0x5d", "0x5e", "0x5f",
74 | "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6a", "0x6b", "0x6c", "0x6d", "0x6e", "0x6f",
75 | "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7a", "0x7b", "0x7c", "0x7d", "0x7e", "0x7f",
76 | "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8a", "0x8b", "0x8c", "0x8d", "0x8e", "0x8f",
77 | "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9a", "0x9b", "0x9c", "0x9d", "0x9e", "0x9f",
78 | "0xa0", "0xa1", "0xa2", "0xa3", "0xa4", "0xa5", "0xa6", "0xa7", "0xa8", "0xa9", "0xaa", "0xab", "0xac", "0xad", "0xae", "0xaf",
79 | "0xb0", "0xb1", "0xb2", "0xb3", "0xb4", "0xb5", "0xb6", "0xb7", "0xb8", "0xb9", "0xba", "0xbb", "0xbc", "0xbd", "0xbe", "0xbf",
80 | "0xc0", "0xc1", "0xc2", "0xc3", "0xc4", "0xc5", "0xc6", "0xc7", "0xc8", "0xc9", "0xca", "0xcb", "0xcc", "0xcd", "0xce", "0xcf",
81 | "0xd0", "0xd1", "0xd2", "0xd3", "0xd4", "0xd5", "0xd6", "0xd7", "0xd8", "0xd9", "0xda", "0xdb", "0xdc", "0xdd", "0xde", "0xdf",
82 | "0xe0", "0xe1", "0xe2", "0xe3", "0xe4", "0xe5", "0xe6", "0xe7", "0xe8", "0xe9", "0xea", "0xeb", "0xec", "0xed", "0xee", "0xef",
83 | "0xf0", "0xf1", "0xf2", "0xf3", "0xf4", "0xf5", "0xf6", "0xf7", "0xf8", "0xf9", "0xfa", "0xfb", "0xfc", "0xfd", "0xfe", "0xff"
84 | };
85 |
86 | if (x < 0x10) { /* < 0x10 has a fixed length of 4 including null terminate. */
87 | memcpy(&s->p[s->length], TextHBTable[x & 255], 4);
88 | s->length += 3;
89 | } else { /* >= 0x10 has a fixed length of 5 including null terminate. */
90 | memcpy(&s->p[s->length], TextHBTable[x & 255], 5);
91 | s->length += 4;
92 | }
93 | }
94 |
95 | void _FASTCALL_ str_code_hdw(_WString* s, uint32_t x)
96 | {
97 | int8_t* buf;
98 | int i = 0, shift = 0;
99 | unsigned int t = 0;
100 |
101 | buf = (int8_t*)&s->p[s->length];
102 |
103 | buf[0] = '0';
104 | buf[1] = 'x';
105 | buf += 2;
106 |
107 | for (shift = 28; shift != 0; shift -= 4) {
108 | t = (x >> shift) & 0xf;
109 | if (i | t) buf[i++] = NIBBLE_TO_CHR;
110 | }
111 | t = x & 0xf;
112 | buf[i++] = NIBBLE_TO_CHR;
113 |
114 | s->length += i + 2;
115 | buf[i] = '\0';
116 | }
117 |
118 | void _FASTCALL_ str_code_hqw(_WString* s, uint8_t src[8])
119 | {
120 | int8_t* buf;
121 | int i = 0, shift = 0;
122 | uint32_t x = RULONG(&src[sizeof(int32_t)]);
123 | int t;
124 |
125 | buf = (int8_t*)&s->p[s->length];
126 | buf[0] = '0';
127 | buf[1] = 'x';
128 | buf += 2;
129 |
130 | for (shift = 28; shift != -4; shift -= 4) {
131 | t = (x >> shift) & 0xf;
132 | if (i | t) buf[i++] = NIBBLE_TO_CHR;
133 | }
134 |
135 | x = RULONG(src);
136 | for (shift = 28; shift != 0; shift -= 4) {
137 | t = (x >> shift) & 0xf;
138 | if (i | t) buf[i++] = NIBBLE_TO_CHR;
139 | }
140 | t = x & 0xf;
141 | buf[i++] = NIBBLE_TO_CHR;
142 |
143 | s->length += i + 2;
144 | buf[i] = '\0';
145 | }
146 |
147 | #ifdef SUPPORT_64BIT_OFFSET
148 | void _FASTCALL_ str_off64(_WString* s, OFFSET_INTEGER x)
149 | {
150 | int8_t* buf;
151 | int i = 0, shift = 0;
152 | OFFSET_INTEGER t = 0;
153 |
154 | buf = (int8_t*)&s->p[s->length];
155 |
156 | buf[0] = '0';
157 | buf[1] = 'x';
158 | buf += 2;
159 |
160 | for (shift = 60; shift != 0; shift -= 4) {
161 | t = (x >> shift) & 0xf;
162 | if (i | t) buf[i++] = NIBBLE_TO_CHR;
163 | }
164 | t = x & 0xf;
165 | buf[i++] = NIBBLE_TO_CHR;
166 |
167 | s->length += i + 2;
168 | buf[i] = '\0';
169 | }
170 | #endif /* SUPPORT_64BIT_OFFSET */
171 |
172 | #endif /* DISTORM_LIGHT */
173 |
--------------------------------------------------------------------------------
/distorm/src/textdefs.h:
--------------------------------------------------------------------------------
1 | /*
2 | textdefs.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #ifndef TEXTDEFS_H
13 | #define TEXTDEFS_H
14 |
15 | #include "config.h"
16 | #include "wstring.h"
17 |
18 | #ifndef DISTORM_LIGHT
19 |
20 | #define PLUS_DISP_CHR '+'
21 | #define MINUS_DISP_CHR '-'
22 | #define OPEN_CHR '['
23 | #define CLOSE_CHR ']'
24 | #define SP_CHR ' '
25 | #define SEG_OFF_CHR ':'
26 |
27 | /*
28 | Naming Convention:
29 |
30 | * get - returns a pointer to a string.
31 | * str - concatenates to string.
32 |
33 | * hex - means the function is used for hex dump (number is padded to required size) - Little Endian output.
34 | * code - means the function is used for disassembled instruction - Big Endian output.
35 | * off - means the function is used for 64bit offset - Big Endian output.
36 |
37 | * h - '0x' in front of the string.
38 |
39 | * b - byte
40 | * dw - double word (can be used for word also)
41 | * qw - quad word
42 |
43 | * all numbers are in HEX.
44 | */
45 |
46 | void _FASTCALL_ str_hex_b(_WString* s, unsigned int x);
47 | void _FASTCALL_ str_code_hb(_WString* s, unsigned int x);
48 | void _FASTCALL_ str_code_hdw(_WString* s, uint32_t x);
49 | void _FASTCALL_ str_code_hqw(_WString* s, uint8_t src[8]);
50 |
51 | #ifdef SUPPORT_64BIT_OFFSET
52 | void _FASTCALL_ str_off64(_WString* s, OFFSET_INTEGER x);
53 | #endif
54 |
55 | #endif /* DISTORM_LIGHT */
56 |
57 | #endif /* TEXTDEFS_H */
58 |
--------------------------------------------------------------------------------
/distorm/src/wstring.c:
--------------------------------------------------------------------------------
1 | /*
2 | wstring.c
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #include "wstring.h"
13 |
14 | #ifndef DISTORM_LIGHT
15 |
16 | void strclear_WS(_WString* s)
17 | {
18 | s->p[0] = '\0';
19 | s->length = 0;
20 | }
21 |
22 | void chrcat_WS(_WString* s, uint8_t ch)
23 | {
24 | s->p[s->length] = ch;
25 | s->p[s->length + 1] = '\0';
26 | s->length += 1;
27 | }
28 |
29 | void strcpylen_WS(_WString* s, const int8_t* buf, unsigned int len)
30 | {
31 | s->length = len;
32 | memcpy((int8_t*)s->p, buf, len + 1);
33 | }
34 |
35 | void strcatlen_WS(_WString* s, const int8_t* buf, unsigned int len)
36 | {
37 | memcpy((int8_t*)&s->p[s->length], buf, len + 1);
38 | s->length += len;
39 | }
40 |
41 | void strcat_WS(_WString* s, const _WString* s2)
42 | {
43 | memcpy((int8_t*)&s->p[s->length], s2->p, s2->length + 1);
44 | s->length += s2->length;
45 | }
46 |
47 | #endif /* DISTORM_LIGHT */
48 |
--------------------------------------------------------------------------------
/distorm/src/wstring.h:
--------------------------------------------------------------------------------
1 | /*
2 | wstring.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #ifndef WSTRING_H
13 | #define WSTRING_H
14 |
15 | #include "config.h"
16 |
17 | #ifndef DISTORM_LIGHT
18 |
19 | void strclear_WS(_WString* s);
20 | void chrcat_WS(_WString* s, uint8_t ch);
21 | void strcpylen_WS(_WString* s, const int8_t* buf, unsigned int len);
22 | void strcatlen_WS(_WString* s, const int8_t* buf, unsigned int len);
23 | void strcat_WS(_WString* s, const _WString* s2);
24 |
25 | /*
26 | * Warning, this macro should be used only when the compiler knows the size of string in advance!
27 | * This macro is used in order to spare the call to strlen when the strings are known already.
28 | * Note: sizeof includes NULL terminated character.
29 | */
30 | #define strcat_WSN(s, t) strcatlen_WS((s), ((const int8_t*)t), sizeof((t))-1)
31 | #define strcpy_WSN(s, t) strcpylen_WS((s), ((const int8_t*)t), sizeof((t))-1)
32 |
33 | #endif /* DISTORM_LIGHT */
34 |
35 | #endif /* WSTRING_H */
36 |
--------------------------------------------------------------------------------
/distorm/src/x86defs.h:
--------------------------------------------------------------------------------
1 | /*
2 | x86defs.h
3 |
4 | diStorm3 - Powerful disassembler for X86/AMD64
5 | http://ragestorm.net/distorm/
6 | distorm at gmail dot com
7 | Copyright (C) 2003-2016 Gil Dabah
8 | This library is licensed under the BSD license. See the file COPYING.
9 | */
10 |
11 |
12 | #ifndef X86DEFS_H
13 | #define X86DEFS_H
14 |
15 |
16 | #define SEG_REGS_MAX (6)
17 | #define CREGS_MAX (9)
18 | #define DREGS_MAX (8)
19 |
20 | /* Maximum instruction size, including prefixes */
21 | #define INST_MAXIMUM_SIZE (15)
22 |
23 | /* Maximum range of imm8 (comparison type) of special SSE CMP instructions. */
24 | #define INST_CMP_MAX_RANGE (8)
25 |
26 | /* Maximum range of imm8 (comparison type) of special AVX VCMP instructions. */
27 | #define INST_VCMP_MAX_RANGE (32)
28 |
29 | /* Wait instruction byte code. */
30 | #define INST_WAIT_INDEX (0x9b)
31 |
32 | /* Lea instruction byte code. */
33 | #define INST_LEA_INDEX (0x8d)
34 |
35 | /* NOP/XCHG instruction byte code. */
36 | #define INST_NOP_INDEX (0x90)
37 |
38 | /* ARPL/MOVSXD instruction byte code. */
39 | #define INST_ARPL_INDEX (0x63)
40 |
41 | /*
42 | * Minimal MODR/M value of divided instructions.
43 | * It's 0xc0, two MSBs set, which indicates a general purpose register is used too.
44 | */
45 | #define INST_DIVIDED_MODRM (0xc0)
46 |
47 | /* This is the escape byte value used for 3DNow! instructions. */
48 | #define _3DNOW_ESCAPE_BYTE (0x0f)
49 |
50 | #define PREFIX_LOCK (0xf0)
51 | #define PREFIX_REPNZ (0xf2)
52 | #define PREFIX_REP (0xf3)
53 | #define PREFIX_CS (0x2e)
54 | #define PREFIX_SS (0x36)
55 | #define PREFIX_DS (0x3e)
56 | #define PREFIX_ES (0x26)
57 | #define PREFIX_FS (0x64)
58 | #define PREFIX_GS (0x65)
59 | #define PREFIX_OP_SIZE (0x66)
60 | #define PREFIX_ADDR_SIZE (0x67)
61 | #define PREFIX_VEX2b (0xc5)
62 | #define PREFIX_VEX3b (0xc4)
63 |
64 | /* REX prefix value range, 64 bits mode decoding only. */
65 | #define PREFIX_REX_LOW (0x40)
66 | #define PREFIX_REX_HI (0x4f)
67 | /* In order to use the extended GPR's we have to add 8 to the Modr/M info values. */
68 | #define EX_GPR_BASE (8)
69 |
70 | /* Mask for REX and VEX features: */
71 | /* Base */
72 | #define PREFIX_EX_B (1)
73 | /* Index */
74 | #define PREFIX_EX_X (2)
75 | /* Register */
76 | #define PREFIX_EX_R (4)
77 | /* Operand Width */
78 | #define PREFIX_EX_W (8)
79 | /* Vector Lengh */
80 | #define PREFIX_EX_L (0x10)
81 |
82 | #endif /* X86DEFS_H */
83 |
--------------------------------------------------------------------------------
/kext/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | English
7 | CFBundleExecutable
8 | ${EXECUTABLE_NAME}
9 | CFBundleIconFile
10 |
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | ${PRODUCT_NAME}
17 | CFBundlePackageType
18 | KEXT
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 3.0
23 | OSBundleLibraries
24 |
25 | com.apple.kpi.bsd
26 | 9.0.0
27 | com.apple.kpi.libkern
28 | 9.0.0
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/kext/README.md:
--------------------------------------------------------------------------------
1 | Onyx The Black Cat
2 | ==================
3 |
4 | Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
5 | All rights reserved.
6 |
7 | Introduction
8 | -------------------------------------------------------------------------------
9 | A kernel module for Intel Mac OS X that will provide you with some
10 | anti anti-debug protection and other features.
11 |
12 | This module will allow you to debug programs which use these tricks without
13 | need to patch them (no need to patch lots of anti-debug calls and maybe
14 | checksum code).
15 | Compatible with all OS X versions since Snow Leopard (older probably supported!).
16 | Mavericks introduces kernel extension code signing but this still works
17 | if you load it manually.
18 |
19 | Features can be enabled or disabled using the control program. By default
20 | everything is disabled. This util requires root privileges to run. If you
21 | want to run it as normal user you can remove CTL_FLAG_PRIVILEGED from
22 | kernel_control.c source file.
23 |
24 | This code uses diStorm as its disassembler.
25 | Due to licensing differences its files are not included.
26 | You can download diStorm from:
27 | http://code.google.com/p/distorm/ and include the missing files.
28 | The only required change is to define SUPPORT_64BIT_OFFSET. You can do it
29 | either at diStorm's config.h file or at Xcode project settings.
30 |
31 | Included are small test programs to test the anti-debug tricks, and other
32 | features.
33 |
34 | The weird name is based on a big black cat named Onyx who is always hiding and
35 | running from me :).
36 | "I'm gonna hug you and kiss you and love you forever (and never use you up)"
37 | Elmyra Fudd.
38 |
39 | I hope it's useful for you. It is for me.
40 | If you find/know any other gdb anti-debug tricks, please drop me an email with
41 | some details so I can add them to the module.
42 |
43 | Have fun.
44 | fG!
45 |
46 | Installation
47 | -------------------------------------------------------------------------------
48 | Copy onyx-the-black-cat.kext to /System/Library/Extensions
49 | (sudo cp -rf onyx-the-black-cat.kext /System/Library/Extensions)
50 |
51 | and then load the module with kextload
52 | (sudo kextload /System/Library/Extensions/onyx-the-black-cat.kext)
53 |
54 | Unload module with kextunload
55 | (sudo kextunload /System/Library/Extensions/onyx-the-black-cat.kext)
56 |
57 | Use the control program to enable/disable features. Everything is disabled by
58 | default.
59 |
60 | You can check dmesg or /var/log/system.log for debug messages and anti-debug
61 | hits.
62 |
63 | Known Problems
64 | -------------------------------------------------------------------------------
65 | Still some ugly code :-)
66 |
--------------------------------------------------------------------------------
/kext/antidebug.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * antidebug.h
36 | *
37 | */
38 |
39 | #ifndef onyx_antidebug_h
40 | #define onyx_antidebug_h
41 |
42 | #include
43 |
44 | kern_return_t anti_ptrace(int cmd);
45 | kern_return_t anti_sysctl(int cmd);
46 |
47 | #endif
48 |
--------------------------------------------------------------------------------
/kext/cpu_protections.c:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * cpu_protections.c
36 | *
37 | * Functions related to kernel memory protections
38 | *
39 | */
40 |
41 | #include "cpu_protections.h"
42 |
43 | /*
44 | * disable the Write Protection bit in CR0 register
45 | * so we can modify kernel code
46 | */
47 | kern_return_t
48 | disable_wp(void)
49 | {
50 | uintptr_t cr0;
51 | // retrieve current value
52 | cr0 = get_cr0();
53 | // remove the WP bit
54 | cr0 = cr0 & ~CR0_WP;
55 | // and write it back
56 | set_cr0(cr0);
57 | // verify if we were successful
58 | if ((get_cr0() & CR0_WP) == 0)
59 | {
60 | return KERN_SUCCESS;
61 | }
62 | else
63 | {
64 | return KERN_FAILURE;
65 | }
66 | }
67 |
68 | /*
69 | * enable the Write Protection bit in CR0 register
70 | */
71 | kern_return_t
72 | enable_wp(void)
73 | {
74 | uintptr_t cr0;
75 | // retrieve current value
76 | cr0 = get_cr0();
77 | // add the WP bit
78 | cr0 = cr0 | CR0_WP;
79 | // and write it back
80 | set_cr0(cr0);
81 | // verify if we were successful
82 | if ((get_cr0() & CR0_WP) != 0)
83 | {
84 | return KERN_SUCCESS;
85 | }
86 | else
87 | {
88 | return KERN_FAILURE;
89 | }
90 | }
91 |
92 | /*
93 | * check if WP is set or not
94 | * 0 - it's set
95 | * 1 - not set
96 | */
97 | uint8_t
98 | verify_wp(void)
99 | {
100 | uintptr_t cr0;
101 | cr0 = get_cr0();
102 | if (cr0 & CR0_WP)
103 | {
104 | return 0;
105 | }
106 | else
107 | {
108 | return 1;
109 | }
110 | }
111 |
112 | void
113 | enable_kernel_write(void)
114 | {
115 | disable_interrupts();
116 | disable_wp();
117 | }
118 |
119 | void
120 | disable_kernel_write(void)
121 | {
122 | enable_wp();
123 | enable_interrupts();
124 | }
125 |
--------------------------------------------------------------------------------
/kext/cpu_protections.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * cpu_protections.h
36 | *
37 | */
38 |
39 | #ifndef onyx_cpu_protections_h
40 | #define onyx_cpu_protections_h
41 |
42 | #include
43 | #include
44 |
45 | #define enable_interrupts() __asm__ volatile("sti");
46 | #define disable_interrupts() __asm__ volatile("cli");
47 |
48 | kern_return_t disable_wp(void);
49 | kern_return_t enable_wp(void);
50 | uint8_t verify_wp(void);
51 | void enable_kernel_write(void);
52 | void disable_kernel_write(void);
53 |
54 | #endif
--------------------------------------------------------------------------------
/kext/disasm_utils.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * disasm_utils.h
36 | *
37 | */
38 |
39 | #ifndef onyx_disasm_utils_h
40 | #define onyx_disasm_utils_h
41 |
42 | #include "my_data_definitions.h"
43 |
44 | kern_return_t find_resume_flag(mach_vm_address_t start, struct patch_location **patch_locations);
45 | kern_return_t find_task_for_pid(mach_vm_address_t start, struct patch_location *topatch);
46 | kern_return_t find_kauth(mach_vm_address_t start, mach_vm_address_t symbol_addr, struct patch_location *topatch);
47 |
48 | #endif
49 |
--------------------------------------------------------------------------------
/kext/en.lproj/InfoPlist.strings:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/acidanthera/onyx-the-black-cat/80ee927ef864c838488ec31c4cc6a3d2e00e39b9/kext/en.lproj/InfoPlist.strings
--------------------------------------------------------------------------------
/kext/idt.c:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * idt.c
36 | *
37 | * Functions related to the IDT table
38 | *
39 | */
40 |
41 | #include "idt.h"
42 |
43 | /* retrieve the address of the IDT
44 | * should never be a bogus value?
45 | */
46 | void
47 | get_addr_idt(mach_vm_address_t *idt)
48 | {
49 | uint8_t idtr[10];
50 | __asm__ volatile ("sidt %0": "=m" (idtr));
51 | #if __LP64__
52 | *idt = *(mach_vm_address_t *)(idtr+2);
53 | #else
54 | *idt = *(mach_vm_address_t *)(idtr+2);
55 | #endif
56 | // return(idt);
57 | }
58 |
59 | // retrieve the size of the IDT
60 | uint16_t
61 | get_size_idt(void)
62 | {
63 | uint8_t idtr[10];
64 | uint16_t size = 0;
65 | __asm__ volatile ("sidt %0": "=m" (idtr));
66 | size = *((uint16_t *) &idtr[0]);
67 | return(size);
68 | }
69 |
--------------------------------------------------------------------------------
/kext/idt.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * idt.h
36 | *
37 | */
38 |
39 | #ifndef onyx_idt_h
40 | #define onyx_idt_h
41 |
42 | #include
43 | #include
44 |
45 | uint16_t get_size_idt(void);
46 | void get_addr_idt (mach_vm_address_t* idt);
47 |
48 | #endif
49 |
--------------------------------------------------------------------------------
/kext/kernel_control.c:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * kernel_control.c
36 | *
37 | * Implements kernel control socket
38 | *
39 | */
40 |
41 | #include "kernel_control.h"
42 |
43 | #include
44 | #include
45 | #include
46 | #include
47 | #include
48 | #include
49 | #include
50 | #include
51 |
52 | #include "shared_data.h"
53 | #include "my_data_definitions.h"
54 | #include "sysent.h"
55 | #include "patchkernel.h"
56 | #include "antidebug.h"
57 |
58 | // local prototypes
59 | static int ctl_connect(kern_ctl_ref ctl_ref, struct sockaddr_ctl *sac, void **unitinfo);
60 | static errno_t ctl_disconnect(kern_ctl_ref ctl_ref, u_int32_t unit, void *unitinfo);
61 | static int ctl_set(kern_ctl_ref ctl_ref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t len);
62 |
63 | // local globals
64 | static int g_max_clients;
65 | static kern_ctl_ref g_ctl_ref;
66 | static u_int32_t g_client_unit = 0;
67 | static kern_ctl_ref g_client_ctl_ref = NULL;
68 | static boolean_t g_kern_ctl_registered = FALSE;
69 |
70 | #pragma mark Kernel Control struct and handler functions
71 |
72 | // described at Network Kernel Extensions Programming Guide
73 | static struct kern_ctl_reg g_ctl_reg = {
74 | BUNDLE_ID, /* use a reverse dns name which includes a name unique to your comany */
75 | 0, /* set to 0 for dynamically assigned control ID - CTL_FLAG_REG_ID_UNIT not set */
76 | 0, /* ctl_unit - ignored when CTL_FLAG_REG_ID_UNIT not set */
77 | 0, /* no privileged access required to access this filter */
78 | 0, /* use default send size buffer */
79 | 0, /* Override receive buffer size */
80 | ctl_connect, /* Called when a connection request is accepted */
81 | ctl_disconnect, /* called when a connection becomes disconnected */
82 | NULL, /* ctl_send_func - handles data sent from the client to kernel control - not implemented */
83 | ctl_set, /* called when the user process makes the setsockopt call */
84 | NULL /* called when the user process makes the getsockopt call */
85 | };
86 |
87 | #pragma mark The start and stop functions
88 |
89 | kern_return_t
90 | install_kern_control(void)
91 | {
92 | errno_t error = 0;
93 | // register the kernel control
94 | error = ctl_register(&g_ctl_reg, &g_ctl_ref);
95 | if (error == 0)
96 | {
97 | g_kern_ctl_registered = TRUE;
98 | LOG_DEBUG("Onyx kernel control installed successfully!");
99 | return KERN_SUCCESS;
100 | }
101 | else
102 | {
103 | LOG_ERROR("Failed to install Onyx kernel control!");
104 | return KERN_FAILURE;
105 | }
106 | }
107 |
108 | kern_return_t
109 | remove_kern_control(void)
110 | {
111 | errno_t error = 0;
112 | // remove kernel control
113 | error = ctl_deregister(g_ctl_ref);
114 | switch (error)
115 | {
116 | case 0:
117 | {
118 | return KERN_SUCCESS;
119 | }
120 | case EINVAL:
121 | {
122 | LOG_ERROR("The kernel control reference is invalid.");
123 | return KERN_FAILURE;
124 | }
125 | case EBUSY:
126 | {
127 | LOG_ERROR("The kernel control still has clients attached. Please disconnect them first!");
128 | return KERN_FAILURE;
129 | }
130 | default:
131 | return KERN_FAILURE;
132 | }
133 | }
134 |
135 | #pragma mark Kernel Control handler functions
136 |
137 | /*
138 | * called when a client connects to the socket
139 | * we need to store some info to use later
140 | */
141 | static int
142 | ctl_connect(kern_ctl_ref ctl_ref, struct sockaddr_ctl *sac, void **unitinfo)
143 | {
144 | // we only accept a single client
145 | if (g_max_clients > 0)
146 | {
147 | return EBUSY;
148 | }
149 | g_max_clients++;
150 | // store the unit id and ctl_ref of the client that connected
151 | // we will need these to queue data to userland
152 | g_client_unit = sac->sc_unit;
153 | g_client_ctl_ref = ctl_ref;
154 | LOG_DEBUG("Client connected!");
155 | return 0;
156 | }
157 |
158 | /*
159 | * and when client disconnects
160 | */
161 | static errno_t
162 | ctl_disconnect(kern_ctl_ref ctl_ref, u_int32_t unit, void *unitinfo)
163 | {
164 | // reset some vars
165 | g_max_clients = 0;
166 | g_client_unit = 0;
167 | g_client_ctl_ref = NULL;
168 | return 0;
169 | }
170 |
171 | /*
172 | * send data from userland to kernel
173 | * this is how userland apps adds and removes apps to be suspended
174 | */
175 | static int
176 | ctl_set(kern_ctl_ref ctl_ref, u_int32_t unit, void *unitinfo, int opt, void *data, size_t len)
177 | {
178 | int error = 0;
179 | if (len == 0 || data == NULL)
180 | {
181 | LOG_ERROR("Invalid data to command.");
182 | return EINVAL;
183 | }
184 | // XXX: lame authentication :-]
185 | if (strcmp((char*)data, MAGIC) != 0)
186 | {
187 | LOG_ERROR("Invalid spell!");
188 | return EINVAL;
189 | }
190 |
191 | switch (opt)
192 | {
193 | case PATCH_TASK_FOR_PID:
194 | {
195 | LOG_DEBUG("Received request to patch task_for_pid.");
196 | patch_task_for_pid(ENABLE);
197 | break;
198 | }
199 | case UNPATCH_TASK_FOR_PID:
200 | {
201 | LOG_DEBUG("Received request to restore task_for_pid.");
202 | patch_task_for_pid(DISABLE);
203 | break;
204 | }
205 | case ANTI_PTRACE_ON:
206 | {
207 | LOG_DEBUG("Received request to patch ptrace.");
208 | anti_ptrace(ENABLE);
209 | break;
210 | }
211 | case ANTI_PTRACE_OFF:
212 | {
213 | LOG_DEBUG("Received request to restore ptrace.");
214 | anti_ptrace(DISABLE);
215 | break;
216 | }
217 | case ANTI_SYSCTL_ON:
218 | {
219 | LOG_DEBUG("Received request to patch sysctl.");
220 | anti_sysctl(ENABLE);
221 | break;
222 | }
223 | case ANTI_SYSCTL_OFF:
224 | {
225 | LOG_DEBUG("Received request to restore sysctl.");
226 | anti_sysctl(DISABLE);
227 | break;
228 | }
229 | case ANTI_KAUTH_ON:
230 | {
231 | LOG_DEBUG("Received request to patch kauth.");
232 | patch_kauth(ENABLE);
233 | break;
234 | }
235 | case ANTI_KAUTH_OFF:
236 | {
237 | LOG_DEBUG("Received request to restore kauth.");
238 | patch_kauth(DISABLE);
239 | break;
240 | }
241 | case PATCH_RESUME_FLAG:
242 | {
243 | LOG_DEBUG("Received request to patch resume flag.");
244 | patch_resume_flag(ENABLE);
245 | break;
246 | }
247 | case UNPATCH_RESUME_FLAG:
248 | {
249 | LOG_DEBUG("Received request to restore resume flag.");
250 | patch_resume_flag(DISABLE);
251 | break;
252 | }
253 | case PATCH_SINGLESTEP:
254 | {
255 | LOG_DEBUG("Received request to patch single step.");
256 | patch_singlestep(ENABLE);
257 | break;
258 | }
259 | case UNPATCH_SINGLESTEP:
260 | {
261 | LOG_DEBUG("Received request to restore single step.");
262 | patch_singlestep(DISABLE);
263 | break;
264 | }
265 | default:
266 | {
267 | error = ENOTSUP;
268 | break;
269 | }
270 | }
271 | return error;
272 | }
273 |
--------------------------------------------------------------------------------
/kext/kernel_control.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * kernel_control.h
36 | *
37 | */
38 |
39 | #ifndef onyx_kernel_control_h
40 | #define onyx_kernel_control_h
41 |
42 | #include
43 | #include
44 |
45 | kern_return_t install_kern_control(void);
46 | kern_return_t remove_kern_control(void);
47 |
48 | #endif
49 |
--------------------------------------------------------------------------------
/kext/kernel_info.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * kernel_info.h
36 | *
37 | */
38 |
39 | #ifndef onyx_kernel_info_h
40 | #define onyx_kernel_info_h
41 |
42 | #include "my_data_definitions.h"
43 |
44 | kern_return_t init_kernel_info(struct kernel_info *kinfo, mach_vm_address_t kernel_base);
45 | kern_return_t cleanup_kernel_info(struct kernel_info *kinfo);
46 | mach_vm_address_t solve_kernel_symbol(struct kernel_info *kinfo, char *symbol_to_solve);
47 | mach_vm_address_t solve_next_kernel_symbol(const struct kernel_info *kinfo, const char *symbol);
48 |
49 | #endif
50 |
--------------------------------------------------------------------------------
/kext/my_data_definitions.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * my_data_definitions.h
36 | *
37 | */
38 |
39 | #ifndef onyx__my_data_definitions_h
40 | #define onyx__my_data_definitions_h
41 |
42 | #include
43 | #include
44 | #include
45 |
46 | struct kernel_info
47 | {
48 | mach_vm_address_t running_text_addr; // the address of running __TEXT segment
49 | mach_vm_address_t disk_text_addr; // the same address at /mach_kernel in filesystem
50 | mach_vm_address_t kaslr_slide; // the kernel aslr slide, computed as the difference between above's addresses
51 | void *linkedit_buf; // pointer to __LINKEDIT buffer containing symbols to solve
52 | uint64_t linkedit_fileoff; // __LINKEDIT file offset so we can read
53 | uint64_t linkedit_size;
54 | uint32_t symboltable_fileoff; // file offset to symbol table - used to position inside the __LINKEDIT buffer
55 | uint32_t symboltable_nr_symbols;
56 | uint32_t stringtable_fileoff; // file offset to string table
57 | uint32_t stringtable_size;
58 | // other info from the header we might need
59 | uint64_t text_size; // size of __text section to disassemble
60 | struct mach_header_64 *mh; // ptr to mach-o header of running kernel
61 | uint32_t fat_offset; // the file offset inside the fat archive for the active arch
62 | };
63 |
64 | struct patch_location
65 | {
66 | mach_vm_address_t address;
67 | int size;
68 | char orig_bytes[15];
69 | int jmp; // 0 = jz, 1 = jnz
70 | struct patch_location *next;
71 | };
72 |
73 | // sysent definitions
74 | // found in xnu/bsd/sys/sysent.h
75 | typedef int32_t sy_call_t(struct proc *, void *, int *);
76 | typedef void sy_munge_t(const void *, void *);
77 |
78 | /* for all versions before Mavericks, found in bsd/sys/sysent.h */
79 | struct sysent { /* system call table */
80 | int16_t sy_narg; /* number of args */
81 | int8_t sy_resv; /* reserved */
82 | int8_t sy_flags; /* flags */
83 | sy_call_t *sy_call; /* implementing function */
84 | sy_munge_t *sy_arg_munge32; /* system call arguments munger for 32-bit process */
85 | sy_munge_t *sy_arg_munge64; /* system call arguments munger for 64-bit process */
86 | int32_t sy_return_type; /* system call return types */
87 | uint16_t sy_arg_bytes; /* Total size of arguments in bytes for
88 | * 32-bit system calls
89 | */
90 | };
91 |
92 | /* Sysent structure got modified in Mavericks */
93 | struct sysent_mavericks {
94 | sy_call_t *sy_call;
95 | sy_munge_t *sy_arg_munge32;
96 | sy_munge_t *sy_arg_munge64;
97 | int32_t sy_return_type;
98 | int16_t sy_narg;
99 | uint16_t sy_arg_bytes;
100 | };
101 |
102 | /* And again in Yosemite */
103 | struct sysent_yosemite {
104 | sy_call_t *sy_call;
105 | sy_munge_t *sy_arg_munge64;
106 | int32_t sy_return_type;
107 | int16_t sy_narg;
108 | uint16_t sy_arg_bytes;
109 | };
110 |
111 | #define DISABLE 0
112 | #define ENABLE 1
113 |
114 | #define MAVERICKS 13
115 | #define YOSEMITE 14
116 | #define ELCAPITAN 15
117 | #define SIERRA 16
118 | #define HIGH_SIERRA 17
119 | #define MOJAVE 18
120 | #define CATALINA 19
121 |
122 | #if DEBUG
123 | #define LOG_DEBUG(fmt, ...) printf("[DEBUG] " fmt "\n", ## __VA_ARGS__)
124 | #else
125 | #define LOG_DEBUG(fmt, ...) do {} while (0)
126 | #endif
127 |
128 | #define LOG_MSG(...) printf(__VA_ARGS__)
129 | #define LOG_ERROR(fmt, ...) printf("[ERROR] " fmt "\n", ## __VA_ARGS__)
130 | #define LOG_INFO(fmt, ...) printf("[INFO] " fmt "\n", ## __VA_ARGS__)
131 |
132 | #endif
133 |
--------------------------------------------------------------------------------
/kext/onyx-the-black-cat.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/kext/onyx_the_black_cat.c:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Based on original code by Landon J. Fuller
14 | *
15 | * Redistribution and use in source and binary forms, with or without
16 | * modification, are permitted provided that the following conditions
17 | * are met:
18 | * 1. Redistributions of source code must retain the above copyright
19 | * notice, this list of conditions and the following disclaimer.
20 | * 2. Redistributions in binary form must reproduce the above copyright
21 | * notice, this list of conditions and the following disclaimer in the
22 | * documentation and/or other materials provided with the distribution.
23 | * 3. The name of the author may not be used to endorse or promote products
24 | * derived from this software without specific prior written permission.
25 | *
26 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 | *
37 | * onyx_the_black_cat.c
38 | *
39 | */
40 |
41 | #include
42 | #include
43 | #include
44 | #include
45 | #include
46 |
47 | #include "my_data_definitions.h"
48 | #include "kernel_control.h"
49 | #include "sysent.h"
50 | #include "syscall.h"
51 | #include "kernel_info.h"
52 | #include "disasm_utils.h"
53 | #include "patchkernel.h"
54 |
55 | #define VERSION "3.1"
56 |
57 | /* globals */
58 | struct kernel_info g_kernel_info;
59 | extern const int version_major;
60 |
61 | /*
62 | * THE FUN STARTS HERE
63 | */
64 | kern_return_t
65 | onyx_the_black_cat_start (kmod_info_t * ki, void * d)
66 | {
67 | printf(
68 | " _____ \n"
69 | "| |___ _ _ _ _ \n"
70 | "| | | | | |_'_| \n"
71 | "|_____|_|_|_ |_,_| \n"
72 | " |___| \n"
73 | " The Black Cat v%s\n", VERSION);
74 |
75 | /* needs to be updated for every new major version supported */
76 | if (version_major > CATALINA)
77 | {
78 | LOG_ERROR("Only Catalina or lower supported!");
79 | return KERN_FAILURE;
80 | }
81 |
82 | /* install the kernel control so we can enable/disable features */
83 | install_kern_control();
84 | /* locate sysent table */
85 | mach_vm_address_t kernel_base = 0;
86 | if (find_sysent(&kernel_base) != KERN_SUCCESS)
87 | {
88 | return KERN_FAILURE;
89 | }
90 | /* read kernel info from the disk image */
91 | if (init_kernel_info(&g_kernel_info, kernel_base) != KERN_SUCCESS)
92 | {
93 | return KERN_FAILURE;
94 | }
95 |
96 | return KERN_SUCCESS;
97 | }
98 |
99 | /*
100 | * THE FUN ENDS HERE :-(
101 | */
102 | kern_return_t
103 | onyx_the_black_cat_stop (kmod_info_t * ki, void * d)
104 | {
105 | // remove the kernel control socket
106 | if (remove_kern_control() != KERN_SUCCESS)
107 | {
108 | return KERN_FAILURE;
109 | }
110 |
111 | // remove all sysent hijacks
112 | cleanup_sysent();
113 | // remove any patches
114 | patch_resume_flag(DISABLE);
115 | patch_task_for_pid(DISABLE);
116 | patch_kauth(DISABLE);
117 | // ALL DONE
118 | return KERN_SUCCESS;
119 | }
120 |
121 |
--------------------------------------------------------------------------------
/kext/patchkernel.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * patchkernel.h
36 | *
37 | */
38 |
39 | #ifndef onyx_patchkernel_h
40 | #define onyx_patchkernel_h
41 |
42 | #include
43 |
44 | kern_return_t patch_resume_flag(int cmd);
45 | kern_return_t patch_task_for_pid(int cmd);
46 | kern_return_t patch_kauth(int cmd);
47 | kern_return_t patch_singlestep(int cmd);
48 |
49 | #endif
50 |
--------------------------------------------------------------------------------
/kext/shared_data.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * shared_data.h
36 | *
37 | */
38 |
39 | // this file should be shared with the userland client that will connect
40 | // to the kernel control socket
41 |
42 | #ifndef onyx_shared_data_h
43 | #define onyx_shared_data_h
44 |
45 | #define BUNDLE_ID "put.as.onyx_the_black_cat"
46 | #define MAGIC "SpecialisRevelio"
47 | // the supported commands
48 | #define PATCH_TASK_FOR_PID 0x0
49 | #define UNPATCH_TASK_FOR_PID 0x1
50 | #define ANTI_PTRACE_ON 0x2
51 | #define ANTI_PTRACE_OFF 0x3
52 | #define ANTI_SYSCTL_ON 0x4
53 | #define ANTI_SYSCTL_OFF 0x5
54 | #define ANTI_KAUTH_ON 0x6
55 | #define ANTI_KAUTH_OFF 0x7
56 | #define PATCH_RESUME_FLAG 0x8
57 | #define UNPATCH_RESUME_FLAG 0x9
58 | #define PATCH_SINGLESTEP 0xa
59 | #define UNPATCH_SINGLESTEP 0xb
60 |
61 | #endif
62 |
--------------------------------------------------------------------------------
/kext/sysent.h:
--------------------------------------------------------------------------------
1 | /*
2 | * ________
3 | * \_____ \ ____ ___.__.___ ___
4 | * / | \ / < | |\ \/ /
5 | * / | \ | \___ | > <
6 | * \_______ /___| / ____|/__/\_ \
7 | * \/ \/\/ \/
8 | * The Black Cat
9 | *
10 | * Copyright (c) fG!, 2011, 2012, 2013, 2014 - reverser@put.as - http://reverse.put.as
11 | * All rights reserved.
12 | *
13 | * Redistribution and use in source and binary forms, with or without
14 | * modification, are permitted provided that the following conditions
15 | * are met:
16 | * 1. Redistributions of source code must retain the above copyright
17 | * notice, this list of conditions and the following disclaimer.
18 | * 2. Redistributions in binary form must reproduce the above copyright
19 | * notice, this list of conditions and the following disclaimer in the
20 | * documentation and/or other materials provided with the distribution.
21 | * 3. The name of the author may not be used to endorse or promote products
22 | * derived from this software without specific prior written permission.
23 | *
24 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 | *
35 | * sysent.h
36 | *
37 | */
38 |
39 | #ifndef onyx_sysent_h
40 | #define onyx_sysent_h
41 | #include "sysproto.h"
42 | #include "syscall.h"
43 | #include
44 | #include
45 | #include
46 | #include
47 | #include
48 | #include
49 |
50 | kern_return_t find_sysent(mach_vm_address_t *out_kernel_base);
51 | kern_return_t cleanup_sysent(void);
52 | mach_vm_address_t calculate_int80address(const mach_vm_address_t idt_address);
53 | mach_vm_address_t find_kernel_base(const mach_vm_address_t int80_address);
54 |
55 | #endif
56 |
57 |
58 |
--------------------------------------------------------------------------------
/onyx-the-black-cat.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/onyx-the-black-cat.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/tests/sysctlantidebug.c:
--------------------------------------------------------------------------------
1 | /*
2 | * test sysctl anti-debug trick
3 | */
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 |
12 | static bool AmIBeingDebugged(void)
13 | // Returns true if the current process is being debugged (either
14 | // running under the debugger or has a debugger attached post facto).
15 | {
16 | int junk;
17 | int mib[4];
18 | struct kinfo_proc info;
19 | size_t size;
20 |
21 | // Initialize the flags so that, if sysctl fails for some bizarre
22 | // reason, we get a predictable result.
23 |
24 | info.kp_proc.p_flag = 0;
25 |
26 | // Initialize mib, which tells sysctl the info we want, in this case
27 | // we're looking for information about a specific process ID.
28 |
29 | mib[0] = CTL_KERN;
30 | mib[1] = KERN_PROC;
31 | mib[2] = KERN_PROC_PID;
32 | mib[3] = getpid();
33 |
34 | // Call sysctl.
35 |
36 | size = sizeof(info);
37 | junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
38 | assert(junk == 0);
39 |
40 | // We're being debugged if the P_TRACED flag is set.
41 |
42 | if ((info.kp_proc.p_flag & P_TRACED) != 0)
43 | {
44 | printf("ALERT: Debugger is found !!!!\n");
45 | exit(0);
46 | }
47 | else
48 | printf("NO DEBUGGER FOUND\n");
49 | return 0;
50 | }
51 |
52 | int main ()
53 | {
54 | printf("Antidebug test...\n");
55 | AmIBeingDebugged();
56 | printf("End...\n");
57 | return(0);
58 | }
59 |
60 |
--------------------------------------------------------------------------------
/tests/taskforpid.c:
--------------------------------------------------------------------------------
1 | /*
2 | * test if we can task_for_pid(0)
3 | */
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | int main(void)
11 | {
12 | mach_port_t port;
13 | if (task_for_pid(mach_task_self(), 0, &port))
14 | {
15 | printf("[ERRROR] Can't get task_for_pid() for kernel task!\n");
16 | }
17 | else
18 | {
19 | printf("[INFO] task_for_pid(0) works!\n");
20 | }
21 | return 0;
22 | }
23 |
--------------------------------------------------------------------------------
/tests/testptrace.c:
--------------------------------------------------------------------------------
1 | /*
2 | * test PT_DENY_ATTACH
3 | */
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | int main()
10 | {
11 | ptrace(PT_DENY_ATTACH, 0, 0, 0);
12 | sleep(2);
13 | printf("Buh!\n");
14 | }
--------------------------------------------------------------------------------
/tests/testptraceTrap.c:
--------------------------------------------------------------------------------
1 | /*
2 | * test PT_DENY_ATTACH and SIGSEGV
3 | */
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 |
10 | unsigned int trap = 1;
11 |
12 | void signalHandler(int signal)
13 | {
14 | trap = 0;
15 | }
16 |
17 | int main()
18 | {
19 | ptrace(PT_DENY_ATTACH, 0, 0, 0);
20 | signal(11, signalHandler);
21 | ptrace(PT_ATTACH, getpid(), 0, 0);
22 | signal(11, 0);
23 | if(trap)
24 | ((unsigned int*)0)[0] = 0;
25 | sleep(2);
26 | printf("Buh!\n");
27 | }
--------------------------------------------------------------------------------