Path: blob/master/modules/post/windows/gather/ad_to_sqlite.rb
19592 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'sqlite3'6require 'tempfile'78class MetasploitModule < Msf::Post9include Msf::Post::Windows::LDAP1011def initialize(info = {})12super(13update_info(14info,15'Name' => 'AD Computer, Group and Recursive User Membership to Local SQLite DB',16'Description' => %q{17This module will gather a list of AD groups, identify the users (taking into account recursion)18and write this to a SQLite database for offline analysis and query using normal SQL syntax.19},20'License' => MSF_LICENSE,21'Author' => [22'Stuart Morgan <stuart.morgan[at]mwrinfosecurity.com>'23],24'Platform' => [ 'win' ],25'SessionTypes' => [ 'meterpreter' ],26'Notes' => {27'Stability' => [CRASH_SAFE],28'SideEffects' => [],29'Reliability' => []30}31)32)3334register_options([35OptString.new('GROUP_FILTER', [false, 'Additional LDAP filters to use when searching for initial groups', '']),36OptBool.new('SHOW_USERGROUPS', [true, 'Show the user/group membership in a greppable form to the console.', false]),37OptBool.new('SHOW_COMPUTERS', [true, 'Show basic computer information in a greppable form to the console.', false]),38OptInt.new('THREADS', [true, 'Number of threads to spawn to gather membership of each group.', 20])39])40end4142def run43max_search = datastore['MAX_SEARCH']4445db, dbfile = create_sqlite_db46print_status("Temporary database created: #{dbfile.path}")4748# Download the list of groups from Active Directory49vprint_status('Retrieving AD Groups')50begin51group_fields = ['distinguishedName', 'objectSid', 'samAccountType', 'sAMAccountName', 'whenChanged', 'whenCreated', 'description', 'groupType', 'adminCount', 'comment', 'managedBy', 'cn']52if datastore['GROUP_FILTER'].nil? || datastore['GROUP_FILTER'].empty?53group_query = '(objectClass=group)'54else55group_query = "(&(objectClass=group)(#{datastore['GROUP_FILTER']}))"56end57groups = query(group_query, max_search, group_fields)58rescue ::RuntimeError, ::Rex::Post::Meterpreter::RequestError => e59print_error("Error(Group): #{e.message}")60return61end6263# If no groups were downloaded, there's no point carrying on64if groups.nil? || groups[:results].empty?65print_error('No AD groups were discovered')66return67end6869# Go through each of the groups and identify the individual users in each group70vprint_status("Groups retrieval completed: #{groups[:results].size} group(s)")71vprint_status('Retrieving AD Group Membership')72users_fields = ['distinguishedName', 'objectSid', 'sAMAccountType', 'sAMAccountName', 'displayName', 'description', 'logonCount', 'userAccountControl', 'userPrincipalName', 'whenChanged', 'whenCreated', 'primaryGroupID', 'badPwdCount', 'comment', 'title', 'cn', 'adminCount', 'manager']7374remaining_groups = groups[:results]7576# If the number of threads exceeds the number of groups, reduce them down to the correct number77threadcount = remaining_groups.count < datastore['THREADS'] ? remaining_groups.count : datastore['THREADS']7879# Loop through each of the groups, creating threads where necessary80while !remaining_groups.nil? && !remaining_groups.empty?81group_gather = []821.upto(threadcount) do83group_gather << framework.threads.spawn("Module(#{refname})", false, remaining_groups.shift) do |individual_group|84next if !individual_group || individual_group.empty? || individual_group.nil?8586# Get the Group RID87group_rid = get_rid(individual_group[1][:value]).to_i8889# Perform the ADSI query to retrieve the effective users in each group (recursion)90vprint_status "Retrieving members of #{individual_group[3][:value]}"91users_filter = "(&(objectCategory=person)(objectClass=user)(|(memberOf:1.2.840.113556.1.4.1941:=#{individual_group[0][:value]})(primaryGroupID=#{group_rid})))"92users_in_group = query(users_filter, max_search, users_fields)9394grouptype_int = individual_group[7][:value].to_i # Set this here because it is used a lot below95sat_int = individual_group[2][:value].to_i9697# Add the group to the database98# groupType parameter interpretation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675935(v=vs.85).aspx99# Note that the conversions to UTF-8 are necessary because of the way SQLite detects column type affinity100# Turns out that the 'fix' is documented in https://github.com/rails/rails/issues/1965101sql_param_group = {102g_rid: group_rid,103g_distinguishedName: individual_group[0][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),104g_sAMAccountType: sat_int,105g_sAMAccountName: individual_group[3][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),106g_whenChanged: individual_group[4][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),107g_whenCreated: individual_group[5][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),108g_description: individual_group[6][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),109g_groupType: grouptype_int,110g_adminCount: individual_group[8][:value].to_i,111g_comment: individual_group[9][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),112g_managedBy: individual_group[10][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),113g_cn: individual_group[11][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),114# Specifies a group that is created by the system.115g_GT_GROUP_CREATED_BY_SYSTEM: (grouptype_int & 0x00000001).zero? ? 0 : 1,116# Specifies a group with global scope.117g_GT_GROUP_SCOPE_GLOBAL: (grouptype_int & 0x00000002).zero? ? 0 : 1,118# Specifies a group with local scope.119g_GT_GROUP_SCOPE_LOCAL: (grouptype_int & 0x00000004).zero? ? 0 : 1,120# Specifies a group with universal scope.121g_GT_GROUP_SCOPE_UNIVERSAL: (grouptype_int & 0x00000008).zero? ? 0 : 1,122# Specifies an APP_BASIC group for Windows Server Authorization Manager.123g_GT_GROUP_SAM_APP_BASIC: (grouptype_int & 0x00000010).zero? ? 0 : 1,124# Specifies an APP_QUERY group for Windows Server Authorization Manager.125g_GT_GROUP_SAM_APP_QUERY: (grouptype_int & 0x00000020).zero? ? 0 : 1,126# Specifies a security group. If this flag is not set, then the group is a distribution group.127g_GT_GROUP_SECURITY: (grouptype_int & 0x80000000).zero? ? 0 : 1,128# The inverse of the flag above. Technically GT_GROUP_SECURITY=0 makes it a distribution129# group so this is arguably redundant, but I have included it for ease. It makes a lot more sense130# to set DISTRIBUTION=1 in a query when your mind is on other things to remember that131# DISTRIBUTION is in fact the inverse of SECURITY...:)132g_GT_GROUP_DISTRIBUTION: (grouptype_int & 0x80000000).zero? ? 1 : 0,133# Now add sAMAccountType constants134g_SAM_DOMAIN_OBJECT: (sat_int == 0) ? 1 : 0,135g_SAM_GROUP_OBJECT: (sat_int == 0x10000000) ? 1 : 0,136g_SAM_NON_SECURITY_GROUP_OBJECT: (sat_int == 0x10000001) ? 1 : 0,137g_SAM_ALIAS_OBJECT: (sat_int == 0x20000000) ? 1 : 0,138g_SAM_NON_SECURITY_ALIAS_OBJECT: (sat_int == 0x20000001) ? 1 : 0,139g_SAM_NORMAL_USER_ACCOUNT: (sat_int == 0x30000000) ? 1 : 0,140g_SAM_MACHINE_ACCOUNT: (sat_int == 0x30000001) ? 1 : 0,141g_SAM_TRUST_ACCOUNT: (sat_int == 0x30000002) ? 1 : 0,142g_SAM_APP_BASIC_GROUP: (sat_int == 0x40000000) ? 1 : 0,143g_SAM_APP_QUERY_GROUP: (sat_int == 0x40000001) ? 1 : 0,144g_SAM_ACCOUNT_TYPE_MAX: (sat_int == 0x7fffffff) ? 1 : 0145}146run_sqlite_query(db, 'ad_groups', sql_param_group)147148# Go through each group user149next if users_in_group[:results].empty?150151users_in_group[:results].each do |group_user|152user_rid = get_rid(group_user[1][:value]).to_i153print_line "Group [#{individual_group[3][:value]}][#{group_rid}] has member [#{group_user[3][:value]}][#{user_rid}]" if datastore['SHOW_USERGROUPS']154155uac_int = group_user[7][:value].to_i # Set this because it is used so frequently below156sat_int = group_user[2][:value].to_i157158# Add the group to the database159# Also parse the ADF_ flags from userAccountControl: https://msdn.microsoft.com/en-us/library/windows/desktop/ms680832(v=vs.85).aspx160sql_param_user = {161u_rid: user_rid,162u_distinguishedName: group_user[0][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),163u_sAMAccountType: group_user[2][:value].to_i,164u_sAMAccountName: group_user[3][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),165u_displayName: group_user[4][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),166u_description: group_user[5][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),167u_logonCount: group_user[6][:value].to_i,168u_userAccountControl: uac_int,169u_userPrincipalName: group_user[8][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),170u_whenChanged: group_user[9][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),171u_whenCreated: group_user[10][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),172u_primaryGroupID: group_user[11][:value].to_i,173u_badPwdCount: group_user[12][:value].to_i,174u_comment: group_user[13][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),175u_title: group_user[14][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),176u_cn: group_user[15][:value].to_s.encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),177# Indicates that a given object has had its ACLs changed to a more secure value by the178# system because it was a member of one of the administrative groups (directly or transitively).179u_adminCount: group_user[16][:value].to_i,180u_manager: group_user[17][:value].to_s.encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),181# The login script is executed182u_ADS_UF_SCRIPT: (uac_int & 0x00000001).zero? ? 0 : 1,183# The user account is disabled.184u_ADS_UF_ACCOUNTDISABLE: (uac_int & 0x00000002).zero? ? 0 : 1,185# The home directory is required.186u_ADS_UF_HOMEDIR_REQUIRED: (uac_int & 0x00000008).zero? ? 0 : 1,187# The account is currently locked out.188u_ADS_UF_LOCKOUT: (uac_int & 0x00000010).zero? ? 0 : 1,189# No password is required.190u_ADS_UF_PASSWD_NOTREQD: (uac_int & 0x00000020).zero? ? 0 : 1,191# The user cannot change the password.192u_ADS_UF_PASSWD_CANT_CHANGE: (uac_int & 0x00000040).zero? ? 0 : 1,193# The user can send an encrypted password.194u_ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: (uac_int & 0x00000080).zero? ? 0 : 1,195# This is an account for users whose primary account is in another domain. This account196# provides user access to this domain, but not to any domain that trusts this domain.197# Also known as a local user account.198u_ADS_UF_TEMP_DUPLICATE_ACCOUNT: (uac_int & 0x00000100).zero? ? 0 : 1,199# This is a default account type that represents a typical user.200u_ADS_UF_NORMAL_ACCOUNT: (uac_int & 0x00000200).zero? ? 0 : 1,201# This is a permit to trust account for a system domain that trusts other domains.202u_ADS_UF_INTERDOMAIN_TRUST_ACCOUNT: (uac_int & 0x00000800).zero? ? 0 : 1,203# This is a computer account for a computer that is a member of this domain.204u_ADS_UF_WORKSTATION_TRUST_ACCOUNT: (uac_int & 0x00001000).zero? ? 0 : 1,205# This is a computer account for a system backup domain controller that is a member of this domain.206u_ADS_UF_SERVER_TRUST_ACCOUNT: (uac_int & 0x00002000).zero? ? 0 : 1,207# The password for this account will never expire.208u_ADS_UF_DONT_EXPIRE_PASSWD: (uac_int & 0x00010000).zero? ? 0 : 1,209# This is an MNS logon account.210u_ADS_UF_MNS_LOGON_ACCOUNT: (uac_int & 0x00020000).zero? ? 0 : 1,211# The user must log on using a smart card.212u_ADS_UF_SMARTCARD_REQUIRED: (uac_int & 0x00040000).zero? ? 0 : 1,213# The service account (user or computer account), under which a service runs, is trusted for Kerberos delegation.214# Any such service can impersonate a client requesting the service.215u_ADS_UF_TRUSTED_FOR_DELEGATION: (uac_int & 0x00080000).zero? ? 0 : 1,216# The security context of the user will not be delegated to a service even if the service217# account is set as trusted for Kerberos delegation.218u_ADS_UF_NOT_DELEGATED: (uac_int & 0x00100000).zero? ? 0 : 1,219# Restrict this principal to use only Data #Encryption Standard (DES) encryption types for keys.220u_ADS_UF_USE_DES_KEY_ONLY: (uac_int & 0x00200000).zero? ? 0 : 1,221# This account does not require Kerberos pre-authentication for logon.222u_ADS_UF_DONT_REQUIRE_PREAUTH: (uac_int & 0x00400000).zero? ? 0 : 1,223# The password has expired224u_ADS_UF_PASSWORD_EXPIRED: (uac_int & 0x00800000).zero? ? 0 : 1,225# The account is enabled for delegation. This is a security-sensitive setting; accounts with226# this option enabled should be strictly controlled. This setting enables a service running227# under the account to assume a client identity and authenticate as that user to other remote228# servers on the network.229u_ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: (uac_int & 0x01000000).zero? ? 0 : 1,230# Now add sAMAccountType constants231u_SAM_DOMAIN_OBJECT: (sat_int == 0) ? 1 : 0,232u_SAM_GROUP_OBJECT: (sat_int == 0x10000000) ? 1 : 0,233u_SAM_NON_SECURITY_GROUP_OBJECT: (sat_int == 0x10000001) ? 1 : 0,234u_SAM_ALIAS_OBJECT: (sat_int == 0x20000000) ? 1 : 0,235u_SAM_NON_SECURITY_ALIAS_OBJECT: (sat_int == 0x20000001) ? 1 : 0,236u_SAM_NORMAL_USER_ACCOUNT: (sat_int == 0x30000000) ? 1 : 0,237u_SAM_MACHINE_ACCOUNT: (sat_int == 0x30000001) ? 1 : 0,238u_SAM_TRUST_ACCOUNT: (sat_int == 0x30000002) ? 1 : 0,239u_SAM_APP_BASIC_GROUP: (sat_int == 0x40000000) ? 1 : 0,240u_SAM_APP_QUERY_GROUP: (sat_int == 0x40000001) ? 1 : 0,241u_SAM_ACCOUNT_TYPE_MAX: (sat_int == 0x7fffffff) ? 1 : 0242}243run_sqlite_query(db, 'ad_users', sql_param_user)244245# Now associate the user with the group246sql_param_mapping = {247user_rid: user_rid,248group_rid: group_rid249}250run_sqlite_query(db, 'ad_mapping', sql_param_mapping)251end252rescue ::RuntimeError, ::Rex::Post::Meterpreter::RequestError => e253print_error("Error(Users): #{e.message}")254next255end256end257group_gather.map(&:join)258end259260vprint_status('Retrieving computers')261begin262computer_filter = '(objectClass=computer)'263computer_fields = ['distinguishedName', 'objectSid', 'cn', 'dNSHostName', 'sAMAccountType', 'sAMAccountName', 'displayName', 'logonCount', 'userAccountControl', 'whenChanged', 'whenCreated', 'primaryGroupID', 'badPwdCount', 'operatingSystem', 'operatingSystemServicePack', 'operatingSystemVersion', 'description', 'comment']264computers = query(computer_filter, max_search, computer_fields)265266computers[:results].each do |comp|267computer_rid = get_rid(comp[1][:value]).to_i268269uac_int = comp[8][:value].to_i # Set this because it is used so frequently below270sat_int = comp[4][:value].to_i271272# Add the group to the database273# Also parse the ADF_ flags from userAccountControl: https://msdn.microsoft.com/en-us/library/windows/desktop/ms680832(v=vs.85).aspx274# Note that userAccountControl is basically the same for a computer as a user; this is because a computer account is derived from a user account275# (if you look at the objectClass for a computer account, it includes 'user') and, for efficiency, we should really store it all in one276# table. However, the reality is that it will get annoying for users to have to remember to use the userAccountControl flags to work out whether277# its a user or a computer and so, for convenience and ease of use, I have put them in completely separate tables.278# Also add the sAMAccount type flags from https://msdn.microsoft.com/en-us/library/windows/desktop/ms679637(v=vs.85).aspx279sql_param_computer = {280c_rid: computer_rid,281c_distinguishedName: comp[0][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),282c_cn: comp[2][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),283c_dNSHostName: comp[3][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),284c_sAMAccountType: sat_int,285c_sAMAccountName: comp[5][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),286c_displayName: comp[6][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),287c_logonCount: comp[7][:value].to_i,288c_userAccountControl: uac_int,289c_whenChanged: comp[9][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),290c_whenCreated: comp[10][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),291c_primaryGroupID: comp[11][:value].to_i,292c_badPwdCount: comp[12][:value].to_i,293c_operatingSystem: comp[13][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),294c_operatingSystemServicePack: comp[14][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),295c_operatingSystemVersion: comp[15][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),296c_description: comp[16][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),297c_comment: comp[17][:value].encode('UTF-16be', invalid: :replace, undef: :replace, replace: '?').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?'),298# The login script is executed299c_ADS_UF_SCRIPT: (uac_int & 0x00000001).zero? ? 0 : 1,300# The user account is disabled.301c_ADS_UF_ACCOUNTDISABLE: (uac_int & 0x00000002).zero? ? 0 : 1,302# The home directory is required.303c_ADS_UF_HOMEDIR_REQUIRED: (uac_int & 0x00000008).zero? ? 0 : 1,304# The account is currently locked out.305c_ADS_UF_LOCKOUT: (uac_int & 0x00000010).zero? ? 0 : 1,306# No password is required.307c_ADS_UF_PASSWD_NOTREQD: (uac_int & 0x00000020).zero? ? 0 : 1,308# The user cannot change the password.309c_ADS_UF_PASSWD_CANT_CHANGE: (uac_int & 0x00000040).zero? ? 0 : 1,310# The user can send an encrypted password.311c_ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: (uac_int & 0x00000080).zero? ? 0 : 1,312# This is an account for users whose primary account is in another domain. This account313# provides user access to this domain, but not to any domain that trusts this domain.314# Also known as a local user account.315c_ADS_UF_TEMP_DUPLICATE_ACCOUNT: (uac_int & 0x00000100).zero? ? 0 : 1,316# This is a default account type that represents a typical user.317c_ADS_UF_NORMAL_ACCOUNT: (uac_int & 0x00000200).zero? ? 0 : 1,318# This is a permit to trust account for a system domain that trusts other domains.319c_ADS_UF_INTERDOMAIN_TRUST_ACCOUNT: (uac_int & 0x00000800).zero? ? 0 : 1,320# This is a computer account for a computer that is a member of this domain.321c_ADS_UF_WORKSTATION_TRUST_ACCOUNT: (uac_int & 0x00001000).zero? ? 0 : 1,322# This is a computer account for a system backup domain controller that is a member of this domain.323c_ADS_UF_SERVER_TRUST_ACCOUNT: (uac_int & 0x00002000).zero? ? 0 : 1,324# The password for this account will never expire.325c_ADS_UF_DONT_EXPIRE_PASSWD: (uac_int & 0x00010000).zero? ? 0 : 1,326# This is an MNS logon account.327c_ADS_UF_MNS_LOGON_ACCOUNT: (uac_int & 0x00020000).zero? ? 0 : 1,328# The user must log on using a smart card.329c_ADS_UF_SMARTCARD_REQUIRED: (uac_int & 0x00040000).zero? ? 0 : 1,330# The service account (user or computer account), under which a service runs, is trusted for Kerberos delegation.331# Any such service can impersonate a client requesting the service.332c_ADS_UF_TRUSTED_FOR_DELEGATION: (uac_int & 0x00080000).zero? ? 0 : 1,333# The security context of the user will not be delegated to a service even if the service334# account is set as trusted for Kerberos delegation.335c_ADS_UF_NOT_DELEGATED: (uac_int & 0x00100000).zero? ? 0 : 1,336# Restrict this principal to use only Data #Encryption Standard (DES) encryption types for keys.337c_ADS_UF_USE_DES_KEY_ONLY: (uac_int & 0x00200000).zero? ? 0 : 1,338# This account does not require Kerberos pre-authentication for logon.339c_ADS_UF_DONT_REQUIRE_PREAUTH: (uac_int & 0x00400000).zero? ? 0 : 1,340# The password has expired341c_ADS_UF_PASSWORD_EXPIRED: (uac_int & 0x00800000).zero? ? 0 : 1,342# The account is enabled for delegation. This is a security-sensitive setting; accounts with343# this option enabled should be strictly controlled. This setting enables a service running344# under the account to assume a client identity and authenticate as that user to other remote345# servers on the network.346c_ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: (uac_int & 0x01000000).zero? ? 0 : 1,347# Now add the sAMAccountType objects348c_SAM_DOMAIN_OBJECT: (sat_int == 0) ? 1 : 0,349c_SAM_GROUP_OBJECT: (sat_int == 0x10000000) ? 1 : 0,350c_SAM_NON_SECURITY_GROUP_OBJECT: (sat_int == 0x10000001) ? 1 : 0,351c_SAM_ALIAS_OBJECT: (sat_int == 0x20000000) ? 1 : 0,352c_SAM_NON_SECURITY_ALIAS_OBJECT: (sat_int == 0x20000001) ? 1 : 0,353c_SAM_NORMAL_USER_ACCOUNT: (sat_int == 0x30000000) ? 1 : 0,354c_SAM_MACHINE_ACCOUNT: (sat_int == 0x30000001) ? 1 : 0,355c_SAM_TRUST_ACCOUNT: (sat_int == 0x30000002) ? 1 : 0,356c_SAM_APP_BASIC_GROUP: (sat_int == 0x40000000) ? 1 : 0,357c_SAM_APP_QUERY_GROUP: (sat_int == 0x40000001) ? 1 : 0,358c_SAM_ACCOUNT_TYPE_MAX: (sat_int == 0x7fffffff) ? 1 : 0359}360run_sqlite_query(db, 'ad_computers', sql_param_computer)361print_line "Computer [#{sql_param_computer[:c_cn]}][#{sql_param_computer[:c_dNSHostName]}][#{sql_param_computer[:c_rid]}]" if datastore['SHOW_COMPUTERS']362end363rescue ::RuntimeError, ::Rex::Post::Meterpreter::RequestError => e364print_error("Error(Computers): #{e.message}")365return366end367368loot_path = store_loot(369'host.ad_to_sqlite',370'application/x-sqlite3',371session,372File.binread(dbfile.path),373'ad_to_sqlite.db',374'AD Computer, Group and Recursive User Membership'375)376377print_good("Sqlite extraction stored in file: #{loot_path}")378ensure379# Finished enumeration, cleanup resources380if db381db.close382end383384if dbfile385dbfile.close386dbfile.unlink387end388end389390# Run the parameterised SQL query391def run_sqlite_query(db, table_name, values)392sql_param_columns = values.keys393sql_param_bind_params = values.keys.map { |k| ":#{k}" }394db.execute("replace into #{table_name} (#{sql_param_columns.join(',')}) VALUES (#{sql_param_bind_params.join(',')})", values)395end396397# Creat the SQLite Database398def create_sqlite_db399dbfile = Tempfile.new('ad_to_sqlite')400db = SQLite3::Database.new(dbfile.path)401db.type_translation = true402403# Create the table for the AD Computers404db.execute('DROP TABLE IF EXISTS ad_computers')405sql_table_computers = 'CREATE TABLE ad_computers ('\406'c_rid INTEGER PRIMARY KEY NOT NULL,'\407'c_distinguishedName TEXT UNIQUE NOT NULL,'\408'c_cn TEXT,'\409'c_sAMAccountType INTEGER,'\410'c_sAMAccountName TEXT UNIQUE NOT NULL,'\411'c_dNSHostName TEXT,'\412'c_displayName TEXT,'\413'c_logonCount INTEGER,'\414'c_userAccountControl INTEGER,'\415'c_primaryGroupID INTEGER,'\416'c_badPwdCount INTEGER,'\417'c_description TEXT,'\418'c_comment TEXT,'\419'c_operatingSystem TEXT,'\420'c_operatingSystemServicePack TEXT,'\421'c_operatingSystemVersion TEXT,'\422'c_whenChanged TEXT,'\423'c_whenCreated TEXT,'\424'c_ADS_UF_SCRIPT INTEGER,'\425'c_ADS_UF_ACCOUNTDISABLE INTEGER,'\426'c_ADS_UF_HOMEDIR_REQUIRED INTEGER,'\427'c_ADS_UF_LOCKOUT INTEGER,'\428'c_ADS_UF_PASSWD_NOTREQD INTEGER,'\429'c_ADS_UF_PASSWD_CANT_CHANGE INTEGER,'\430'c_ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED INTEGER,'\431'c_ADS_UF_TEMP_DUPLICATE_ACCOUNT INTEGER,'\432'c_ADS_UF_NORMAL_ACCOUNT INTEGER,'\433'c_ADS_UF_INTERDOMAIN_TRUST_ACCOUNT INTEGER,'\434'c_ADS_UF_WORKSTATION_TRUST_ACCOUNT INTEGER,'\435'c_ADS_UF_SERVER_TRUST_ACCOUNT INTEGER,'\436'c_ADS_UF_DONT_EXPIRE_PASSWD INTEGER,'\437'c_ADS_UF_MNS_LOGON_ACCOUNT INTEGER,'\438'c_ADS_UF_SMARTCARD_REQUIRED INTEGER,'\439'c_ADS_UF_TRUSTED_FOR_DELEGATION INTEGER,'\440'c_ADS_UF_NOT_DELEGATED INTEGER,'\441'c_ADS_UF_USE_DES_KEY_ONLY INTEGER,'\442'c_ADS_UF_DONT_REQUIRE_PREAUTH INTEGER,'\443'c_ADS_UF_PASSWORD_EXPIRED INTEGER,'\444'c_ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION INTEGER,'\445'c_SAM_DOMAIN_OBJECT INTEGER,'\446'c_SAM_GROUP_OBJECT INTEGER,'\447'c_SAM_NON_SECURITY_GROUP_OBJECT INTEGER,'\448'c_SAM_ALIAS_OBJECT INTEGER,'\449'c_SAM_NON_SECURITY_ALIAS_OBJECT INTEGER,'\450'c_SAM_NORMAL_USER_ACCOUNT INTEGER,'\451'c_SAM_MACHINE_ACCOUNT INTEGER,'\452'c_SAM_TRUST_ACCOUNT INTEGER,'\453'c_SAM_APP_BASIC_GROUP INTEGER,'\454'c_SAM_APP_QUERY_GROUP INTEGER,'\455'c_SAM_ACCOUNT_TYPE_MAX INTEGER)'456db.execute(sql_table_computers)457458# Create the table for the AD Groups459db.execute('DROP TABLE IF EXISTS ad_groups')460sql_table_group = 'CREATE TABLE ad_groups ('\461'g_rid INTEGER PRIMARY KEY NOT NULL,'\462'g_distinguishedName TEXT UNIQUE NOT NULL,'\463'g_sAMAccountType INTEGER,'\464'g_sAMAccountName TEXT UNIQUE NOT NULL,'\465'g_groupType INTEGER,'\466'g_adminCount INTEGER,'\467'g_description TEXT,'\468'g_comment TEXT,'\469'g_cn TEXT,'\470'g_managedBy TEXT,'\471'g_whenChanged TEXT,'\472'g_whenCreated TEXT,'\473'g_GT_GROUP_CREATED_BY_SYSTEM INTEGER,'\474'g_GT_GROUP_SCOPE_GLOBAL INTEGER,'\475'g_GT_GROUP_SCOPE_LOCAL INTEGER,'\476'g_GT_GROUP_SCOPE_UNIVERSAL INTEGER,'\477'g_GT_GROUP_SAM_APP_BASIC INTEGER,'\478'g_GT_GROUP_SAM_APP_QUERY INTEGER,'\479'g_GT_GROUP_SECURITY INTEGER,'\480'g_GT_GROUP_DISTRIBUTION INTEGER,'\481'g_SAM_DOMAIN_OBJECT INTEGER,'\482'g_SAM_GROUP_OBJECT INTEGER,'\483'g_SAM_NON_SECURITY_GROUP_OBJECT INTEGER,'\484'g_SAM_ALIAS_OBJECT INTEGER,'\485'g_SAM_NON_SECURITY_ALIAS_OBJECT INTEGER,'\486'g_SAM_NORMAL_USER_ACCOUNT INTEGER,'\487'g_SAM_MACHINE_ACCOUNT INTEGER,'\488'g_SAM_TRUST_ACCOUNT INTEGER,'\489'g_SAM_APP_BASIC_GROUP INTEGER,'\490'g_SAM_APP_QUERY_GROUP INTEGER,'\491'g_SAM_ACCOUNT_TYPE_MAX INTEGER)'492db.execute(sql_table_group)493494# Create the table for the AD Users495db.execute('DROP TABLE IF EXISTS ad_users')496sql_table_users = 'CREATE TABLE ad_users ('\497'u_rid INTEGER PRIMARY KEY NOT NULL,'\498'u_distinguishedName TEXT UNIQUE NOT NULL,'\499'u_description TEXT,'\500'u_displayName TEXT,'\501'u_sAMAccountType INTEGER,'\502'u_sAMAccountName TEXT,'\503'u_logonCount INTEGER,'\504'u_userAccountControl INTEGER,'\505'u_primaryGroupID INTEGER,'\506'u_cn TEXT,'\507'u_adminCount INTEGER,'\508'u_badPwdCount INTEGER,'\509'u_userPrincipalName TEXT UNIQUE,'\510'u_comment TEXT,'\511'u_title TEXT,'\512'u_manager TEXT,'\513'u_whenCreated TEXT,'\514'u_whenChanged TEXT,'\515'u_ADS_UF_SCRIPT INTEGER,'\516'u_ADS_UF_ACCOUNTDISABLE INTEGER,'\517'u_ADS_UF_HOMEDIR_REQUIRED INTEGER,'\518'u_ADS_UF_LOCKOUT INTEGER,'\519'u_ADS_UF_PASSWD_NOTREQD INTEGER,'\520'u_ADS_UF_PASSWD_CANT_CHANGE INTEGER,'\521'u_ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED INTEGER,'\522'u_ADS_UF_TEMP_DUPLICATE_ACCOUNT INTEGER,'\523'u_ADS_UF_NORMAL_ACCOUNT INTEGER,'\524'u_ADS_UF_INTERDOMAIN_TRUST_ACCOUNT INTEGER,'\525'u_ADS_UF_WORKSTATION_TRUST_ACCOUNT INTEGER,'\526'u_ADS_UF_SERVER_TRUST_ACCOUNT INTEGER,'\527'u_ADS_UF_DONT_EXPIRE_PASSWD INTEGER,'\528'u_ADS_UF_MNS_LOGON_ACCOUNT INTEGER,'\529'u_ADS_UF_SMARTCARD_REQUIRED INTEGER,'\530'u_ADS_UF_TRUSTED_FOR_DELEGATION INTEGER,'\531'u_ADS_UF_NOT_DELEGATED INTEGER,'\532'u_ADS_UF_USE_DES_KEY_ONLY INTEGER,'\533'u_ADS_UF_DONT_REQUIRE_PREAUTH INTEGER,'\534'u_ADS_UF_PASSWORD_EXPIRED INTEGER,'\535'u_ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION INTEGER,'\536'u_SAM_DOMAIN_OBJECT INTEGER,'\537'u_SAM_GROUP_OBJECT INTEGER,'\538'u_SAM_NON_SECURITY_GROUP_OBJECT INTEGER,'\539'u_SAM_ALIAS_OBJECT INTEGER,'\540'u_SAM_NON_SECURITY_ALIAS_OBJECT INTEGER,'\541'u_SAM_NORMAL_USER_ACCOUNT INTEGER,'\542'u_SAM_MACHINE_ACCOUNT INTEGER,'\543'u_SAM_TRUST_ACCOUNT INTEGER,'\544'u_SAM_APP_BASIC_GROUP INTEGER,'\545'u_SAM_APP_QUERY_GROUP INTEGER,'\546'u_SAM_ACCOUNT_TYPE_MAX INTEGER)'547db.execute(sql_table_users)548549# Create the table for the mapping between the two (membership)550db.execute('DROP TABLE IF EXISTS ad_mapping')551sql_table_mapping = 'CREATE TABLE ad_mapping ('\552'user_rid INTEGER NOT NULL,' \553'group_rid INTEGER NOT NULL,'\554'PRIMARY KEY (user_rid, group_rid),'\555'FOREIGN KEY(user_rid) REFERENCES ad_users(u_rid)'\556'FOREIGN KEY(group_rid) REFERENCES ad_groups(g_rid))'557db.execute(sql_table_mapping)558559# Create the view for the AD User/Group membership560db.execute('DROP VIEW IF EXISTS view_mapping')561sql_view_mapping = 'CREATE VIEW view_mapping AS SELECT ad_groups.*,ad_users.* FROM ad_mapping '\562'INNER JOIN ad_groups ON ad_groups.g_rid = ad_mapping.group_rid '\563'INNER JOIN ad_users ON ad_users.u_rid = ad_mapping.user_rid'564db.execute(sql_view_mapping)565566return db, dbfile567rescue SQLite3::Exception => e568print_error("Error(Database): #{e.message}")569return570end571572def get_rid(data)573sid = data.unpack('bbbbbbbbV*')[8..]574sid[-1]575end576end577578579