Path: blob/master/modules/post/windows/gather/enum_ad_users.rb
19778 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Post6include Msf::Auxiliary::Report7include Msf::Post::Windows::LDAP8include Msf::Post::Windows::Accounts910UAC_DISABLED = 0x0211USER_FIELDS = [12'sAMAccountName',13'name',14'userPrincipalName',15'userAccountControl',16'lockoutTime',17'mail',18'primarygroupid',19'description'20].freeze2122def initialize(info = {})23super(24update_info(25info,26'Name' => 'Windows Gather Active Directory Users',27'Description' => %q{28This module will enumerate user accounts in the default Active Domain (AD) directory and stores29them in the database. If GROUP_MEMBER is set to the DN of a group, this will list the members of30that group by performing a recursive/nested search (i.e. it will list users who are members of31groups that are members of groups that are members of groups (etc) which eventually include the32target group DN.33},34'License' => MSF_LICENSE,35'Author' => [36'Ben Campbell',37'Carlos Perez <carlos_perez[at]darkoperator.com>',38'Stuart Morgan <stuart.morgan[at]mwrinfosecurity.com>'39],40'Platform' => [ 'win' ],41'SessionTypes' => [ 'meterpreter' ],42'Notes' => {43'Stability' => [CRASH_SAFE],44'SideEffects' => [],45'Reliability' => []46},47'Compat' => {48'Meterpreter' => {49'Commands' => %w[50stdapi_net_resolve_host51]52}53}54)55)5657register_options([58OptBool.new('STORE_LOOT', [true, 'Store file in loot.', false]),59OptBool.new('EXCLUDE_LOCKED', [true, 'Exclude in search locked accounts..', false]),60OptBool.new('EXCLUDE_DISABLED', [true, 'Exclude from search disabled accounts.', false]),61OptString.new('ADDITIONAL_FIELDS', [false, 'Additional fields to retrieve, comma separated', nil]),62OptString.new('FILTER', [false, 'Customised LDAP filter', nil]),63OptString.new('GROUP_MEMBER', [false, 'Recursively list users that are effectve members of the group DN specified.', nil]),64OptEnum.new('UAC', [65true, 'Filter on User Account Control Setting.', 'ANY',66[67'ANY',68'NO_PASSWORD',69'CHANGE_PASSWORD',70'NEVER_EXPIRES',71'SMARTCARD_REQUIRED',72'NEVER_LOGGEDON'73]74])75])76end7778def run79@user_fields = USER_FIELDS.dup8081if datastore['ADDITIONAL_FIELDS']82additional_fields = datastore['ADDITIONAL_FIELDS'].gsub(/\s+/, '').split(',')83@user_fields.push(*additional_fields)84end8586max_search = datastore['MAX_SEARCH']8788begin89q = query(query_filter, max_search, @user_fields)90rescue ::RuntimeError, ::Rex::Post::Meterpreter::RequestError => e91# Can't bind or in a network w/ limited accounts92print_error(e.message)93return94end9596if q.nil? || q[:results].empty?97print_status('No results returned.')98else99results_table = parse_results(q[:results])100print_line results_table.to_s101102if datastore['STORE_LOOT']103stored_path = store_loot('ad.users', 'text/plain', session, results_table.to_csv)104print_good("Results saved to: #{stored_path}")105end106end107end108109def account_disabled?(uac)110(uac & UAC_DISABLED) > 0111end112113def account_locked?(lockout_time)114lockout_time > 0115end116117# Takes the results of LDAP query, parses them into a table118# and records and usernames as {Metasploit::Credential::Core}s in119# the database.120#121# @param results [Array<Array<Hash>>] The LDAP query results to parse122# @return [Rex::Text::Table] the table containing all the result data123def parse_results(results)124domain = datastore['DOMAIN'] || get_domain125domain_ip = client.net.resolve.resolve_host(domain)[:ip]126# Results table holds raw string data127results_table = Rex::Text::Table.new(128'Header' => 'Domain Users',129'Indent' => 1,130'SortIndex' => -1,131'Columns' => @user_fields132)133134results.each do |result|135row = []136137result.each do |field|138if field.nil?139row << ''140else141row << field[:value]142end143end144145username = result[@user_fields.index('sAMAccountName')][:value]146uac = result[@user_fields.index('userAccountControl')][:value]147lockout_time = result[@user_fields.index('lockoutTime')][:value]148store_username(username, uac, lockout_time, domain, domain_ip)149150results_table << row151end152results_table153end154155# Builds the LDAP query 'filter' used to find our User Accounts based on156# criteria set by user in the Datastore.157#158# @return [String] the LDAP query string159def query_filter160inner_filter = '(objectCategory=person)(objectClass=user)'161inner_filter << '(!(lockoutTime>=1))' if datastore['EXCLUDE_LOCKED']162inner_filter << '(!(userAccountControl:1.2.840.113556.1.4.803:=2))' if datastore['EXCLUDE_DISABLED']163inner_filter << "(memberof:1.2.840.113556.1.4.1941:=#{datastore['GROUP_MEMBER']})" if datastore['GROUP_MEMBER']164inner_filter << "(#{datastore['FILTER']})" unless datastore['FILTER'].blank?165case datastore['UAC']166when 'ANY'167# no filter168when 'NO_PASSWORD'169inner_filter << '(userAccountControl:1.2.840.113556.1.4.803:=32)'170when 'CHANGE_PASSWORD'171inner_filter << '(!sAMAccountType=805306370)(pwdlastset=0)'172when 'NEVER_EXPIRES'173inner_filter << '(userAccountControl:1.2.840.113556.1.4.803:=65536)'174when 'SMARTCARD_REQUIRED'175inner_filter << '(userAccountControl:1.2.840.113556.1.4.803:=262144)'176when 'NEVER_LOGGEDON'177inner_filter << '(|(lastlogon=0)(!lastlogon=*))'178end179"(&#{inner_filter})"180end181182def store_username(username, uac, lockout_time, realm, domain_ip)183service_data = {184address: domain_ip,185port: 445,186service_name: 'smb',187protocol: 'tcp',188workspace_id: myworkspace_id189}190191credential_data = {192origin_type: :session,193session_id: session_db_id,194post_reference_name: refname,195username: username,196realm_value: realm,197realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN198}199200credential_data.merge!(service_data)201202# Create the Metasploit::Credential::Core object203credential_core = create_credential(credential_data)204205if account_disabled?(uac.to_i)206status = Metasploit::Model::Login::Status::DISABLED207elsif account_locked?(lockout_time.to_i)208status = Metasploit::Model::Login::Status::LOCKED_OUT209else210status = Metasploit::Model::Login::Status::UNTRIED211end212213# Assemble the options hash for creating the Metasploit::Credential::Login object214login_data = {215core: credential_core,216status: status217}218219login_data[:last_attempted_at] = DateTime.now unless (status == Metasploit::Model::Login::Status::UNTRIED)220221# Merge in the service data and create our Login222login_data.merge!(service_data)223create_credential_login(login_data)224end225end226227228