Path: blob/master/modules/auxiliary/scanner/ldap/ldap_login.rb
28052 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'metasploit/framework/credential_collection'6require 'metasploit/framework/login_scanner/ldap'78class MetasploitModule < Msf::Auxiliary9include Msf::Auxiliary::Report10include Msf::Auxiliary::AuthBrute11include Msf::Auxiliary::Scanner12include Msf::Exploit::Remote::LDAP13include Msf::Sessions::CreateSessionOptions14include Msf::Auxiliary::CommandShell15include Msf::Auxiliary::ReportSummary1617def initialize(info = {})18super(19update_info(20info,21'Name' => 'LDAP Login Scanner',22'Description' => 'This module attempts to login to the LDAP service.',23'Author' => [ 'Dean Welch' ],24'License' => MSF_LICENSE,25'Notes' => {26'Stability' => [CRASH_SAFE],27'Reliability' => [],28'SideEffects' => []29}30)31)3233register_options(34[35OptBool.new(36'APPEND_DOMAIN', [true, 'Appends `@<DOMAIN> to the username for authentication`', false],37conditions: ['LDAP::Auth', 'in', [Msf::Exploit::Remote::AuthOption::AUTO, Msf::Exploit::Remote::AuthOption::PLAINTEXT]]38),39Msf::OptString.new('LDAPDomain', [false, 'The domain to authenticate to'], fallbacks: ['DOMAIN']),40Msf::OptString.new('LDAPUsername', [false, 'The username to authenticate with'], fallbacks: ['USERNAME'], aliases: ['BIND_DN']),41Msf::OptString.new('LDAPPassword', [false, 'The password to authenticate with'], fallbacks: ['PASSWORD'], aliases: ['BIND_PW']),42OptInt.new('SessionKeepalive', [true, 'Time (in seconds) for sending protocol-level keepalive messages', 10 * 60])43]44)4546# A password must be supplied unless doing anonymous login47# De-registering USERNAME and PASSWORD as they are pulled in via the Msf::Auxiliary::AuthBrute mixin48options_to_deregister = %w[USERNAME PASSWORD BLANK_PASSWORDS]4950if framework.features.enabled?(Msf::FeatureManager::LDAP_SESSION_TYPE)51add_info('The %grnCreateSession%clr option within this module can open an interactive session')52else53# Don't give the option to create a session unless ldap sessions are enabled54options_to_deregister << 'CreateSession'55options_to_deregister << 'SessionKeepalive'56end5758deregister_options(*options_to_deregister)59end6061def create_session?62# The CreateSession option is de-registered if LDAP_SESSION_TYPE is not enabled63# but the option can still be set/saved so check to see if we should use it64if framework.features.enabled?(Msf::FeatureManager::LDAP_SESSION_TYPE)65datastore['CreateSession']66else67false68end69end7071def run72validate_connect_options!73results = super || {}74logins = results.flat_map { |_k, v| v[:successful_logins] }75sessions = results.flat_map { |_k, v| v[:successful_sessions] }76print_status("Bruteforce completed, #{logins.size} #{logins.size == 1 ? 'credential was' : 'credentials were'} successful.")77return results unless framework.features.enabled?(Msf::FeatureManager::LDAP_SESSION_TYPE)7879if create_session?80print_status("#{sessions.size} LDAP #{sessions.size == 1 ? 'session was' : 'sessions were'} opened successfully.")81else82print_status('You can open an LDAP session with these credentials and %grnCreateSession%clr set to true')83end84results85end8687def validate_connect_options!88# Verify we can create arbitrary connect opts, this won't make a connection out to the real host - but will verify the values are valid89get_connect_opts90rescue Msf::ValidationError => e91fail_with(Msf::Exploit::Remote::Failure::BadConfig, "Invalid datastore options for chosen auth type: #{e.message}")92end9394def run_host(ip)95cred_collection = build_specific_credential_collection(96void_login: datastore['LDAP::Auth'] == Msf::Exploit::Remote::AuthOption::SCHANNEL,97no_password_login: datastore['LDAP::Auth'] == Msf::Exploit::Remote::AuthOption::KERBEROS && !datastore['ANONYMOUS_LOGIN'] && !datastore['LDAPPassword']98)99100pkcs12_storage = Msf::Exploit::Remote::Pkcs12::Storage.new(framework: framework, framework_module: self)101opts = {102domain: datastore['LDAPDomain'],103append_domain: datastore['APPEND_DOMAIN'],104ssl: datastore['SSL'],105proxies: datastore['PROXIES'],106domain_controller_rhost: datastore['DomainControllerRhost'],107ldap_auth: datastore['LDAP::Auth'],108ldap_pkcs12: datastore['LDAP::CertFile'] ? pkcs12_storage.read_pkcs12_cert_path(datastore['LDAP::CertFile']) : nil,109ldap_rhostname: datastore['Ldap::Rhostname'],110ldap_krb_offered_enc_types: datastore['Ldap::KrbOfferedEncryptionTypes'],111ldap_krb5_cname: datastore['Ldap::Krb5Ccname']112}113114realm_key = nil115if opts[:ldap_auth] == Msf::Exploit::Remote::AuthOption::KERBEROS116realm_key = Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN117if !datastore['ANONYMOUS_LOGIN'] && !datastore['LDAPPassword']118# In case no password has been provided, we assume the user wants to use Kerberos tickets stored in cache119# Write mode is still enable in case new TGS tickets are retrieved.120opts[:kerberos_ticket_storage] = kerberos_ticket_storage({ read: true, write: true })121else122# Write only cache so we keep all gathered tickets but don't reuse them for auth while running the module123opts[:kerberos_ticket_storage] = kerberos_ticket_storage({ read: false, write: true })124end125end126127scanner = Metasploit::Framework::LoginScanner::LDAP.new(128configure_login_scanner(129host: ip,130port: rport,131cred_details: cred_collection,132stop_on_success: datastore['STOP_ON_SUCCESS'],133bruteforce_speed: datastore['BRUTEFORCE_SPEED'],134connection_timeout: datastore['LDAP::ConnectTimeout'].to_i,135framework: framework,136framework_module: self,137realm_key: realm_key,138opts: opts,139use_client_as_proof: create_session?140)141)142143successful_logins = []144successful_sessions = []145scanner.scan! do |result|146credential_data = result.to_h147credential_data.merge!(148module_fullname: fullname,149workspace_id: myworkspace_id,150service_name: 'ldap',151protocol: 'tcp'152)153if result.success?154successful_logins << result155if opts[:ldap_auth] == Msf::Exploit::Remote::AuthOption::SCHANNEL156# Schannel auth has no meaningful credential information to store in the DB157msg = opts[:ldap_pkcs12].nil? ? 'Using stored certificate' : "Cert File #{opts[:ldap_pkcs12][:path]} (#{opts[:ldap_pkcs12][:value].certificate.subject})"158report_successful_login(159public: opts[:ldap_pkcs12][:value].certificate.subject.to_s,160private: opts[:ldap_pkcs12][:path]161)162print_brute level: :good, ip: ip, msg: "Success: '#{msg}'"163else164create_credential_and_login(credential_data) if result.credential.private165print_brute level: :good, ip: ip, msg: "Success: '#{result.credential}'"166end167successful_sessions << create_session(result, ip) if create_session?168else169invalidate_login(credential_data)170vprint_error "#{ip}:#{rport} - LOGIN FAILED: #{result.credential} (#{result.status}: #{result.proof})"171end172end173{ successful_logins: successful_logins, successful_sessions: successful_sessions }174end175176private177178def create_session(result, ip)179session_setup(result)180rescue StandardError => e181elog('Failed to setup the session', error: e)182print_brute level: :error, ip: ip, msg: "Failed to setup the session - #{e.class} #{e.message}"183result.connection.close unless result.connection.nil?184end185186# @param [Metasploit::Framework::LoginScanner::Result] result187# @return [Msf::Sessions::LDAP]188def session_setup(result)189return unless result.connection && result.proof190191# Create a new session192my_session = Msf::Sessions::LDAP.new(result.connection, { client: result.proof, keepalive_seconds: datastore['SessionKeepalive'] })193194merge_me = {195'USERPASS_FILE' => nil,196'USER_FILE' => nil,197'PASS_FILE' => nil,198'USERNAME' => result.credential.public,199'PASSWORD' => result.credential.private200}201202start_session(self, nil, merge_me, false, my_session.rstream, my_session)203end204205def build_specific_credential_collection(void_login:, no_password_login:)206if void_login207Metasploit::Framework::PrivateCredentialCollection.new({208nil_passwords: true209})210elsif no_password_login211Metasploit::Framework::CredentialCollection.new({212username: datastore['LDAPUsername'],213nil_passwords: true214})215else216build_credential_collection(217username: datastore['LDAPUsername'],218password: datastore['LDAPPassword'],219realm: datastore['DOMAIN'],220anonymous_login: datastore['ANONYMOUS_LOGIN'],221blank_passwords: false222)223end224end225end226227228