diff --git a/changelog.d/6637-dicom-slow-link-and-log-values.added.md b/changelog.d/6637-dicom-slow-link-and-log-values.added.md index c826afee4c..cbdde788bb 100644 --- a/changelog.d/6637-dicom-slow-link-and-log-values.added.md +++ b/changelog.d/6637-dicom-slow-link-and-log-values.added.md @@ -3,6 +3,5 @@ than that would have an object over a size set by the link cut at the same point on every attempt. On a link at or above 16 KiB a second, set the rate at or under the link's. The least it takes is 16 KiB a second, and no value turns the per-message deadline off, so a slower link - also needs `timeout_seconds` raised. It is refused on an outbound connection. The DICOM log filter also redacts more - peer values, and the C-STORE client dead-letters an object it can never propose instead of - retrying it. (`BACKLOG #6637`) + also needs `timeout_seconds` raised. It is refused on an outbound connection. The C-STORE client + also dead-letters an object it can never propose instead of retrying it. (`BACKLOG #6637`) diff --git a/changelog.d/6637.security.md b/changelog.d/6637.security.md new file mode 100644 index 0000000000..6bc99799f4 --- /dev/null +++ b/changelog.d/6637.security.md @@ -0,0 +1,6 @@ +- **pynetdicom's and pydicom's log lines are now default-deny.** Where the screen applies, a line + from either library is written only if it is one of the value-free lines or fully matches one of + the templates pinned in `messagefoundry/transports/_dicom_log_lines.py`; a line that matches none + is withheld. See + [DICOM.md](../docs/DICOM.md) section 5 for what stays and what is lost. Its limits are in + DICOM.md section 5. (`BACKLOG #6637`) diff --git a/docs/DICOM.md b/docs/DICOM.md index 7b376613ad..a3a4a27249 100644 --- a/docs/DICOM.md +++ b/docs/DICOM.md @@ -338,53 +338,83 @@ numpy**), lazily imported so a SQLite-only install and a console peek-import sta class/instance UID, AE title, peer host) or a redacted URL — never the dataset, an element value, or pixel data. The rule holds for pynetdicom's and pydicom's own loggers too (owner ruling 2026-11-03, BACKLOG #5081). A UID or AE title a peer sent that either library refuses or flags as non-conformant is not a routing-safe - identifier. The DICOM transport applies that rule through a log filter on those libraries' loggers, which - meets it only for the line shapes the filter knows. The filter is installed when the transport is imported - and again at each SCP start, so it reads the SCU's lines as well as the SCP's. It redacts the value from at - least these lines, which stay with the element's name and the reason while the value reads `[redacted]`: - pynetdicom's non-conformant and refused value lines; its non-conformant transfer syntax and related SOP - class lines, and its line naming a transfer syntax under the DICOM root that is no transfer syntax; the - refusal in an exception logged by any pynetdicom module that logs one, such as its DUL when a received PDU - does not decode or its DIMSE provider when a received message does not convert, in the record's message - and in each link of its traceback's chain; pydicom's invalid value, Specific Character Set, VR IS and - DS, and invalid private creator lines, as lines and as refusals inside such an exception; pynetdicom's `No presentation context for` - line, which keeps its SOP class and transfer syntax only when both are conformant or named in pydicom's - UID dictionary; its `No supported service class` line, which keeps a SOP class on the same terms; the - UID and AE title fields of pynetdicom's DEBUG dumps of an association request, an - association acceptance and a DIMSE message; and the username and password of a user identity and the - hex of an extended negotiation item's application information in those dumps, which are never kept. A - dump field otherwise keeps at - least these values: an empty one; a - conformant UID; a name in pydicom's UID dictionary, on a field that is no instance UID; and, on the AE title - fields and on Their Implementation Version Name, a value that passes pynetdicom's AE title check, which an - empty or all-space value does. `_kept` in `messagefoundry/transports/dicom.py` is the source of record. - pynetdicom runs no AE title check on the two titles of an association acceptance, only `decode_bytes` on - their bytes, and the filter applies the title check to them anyway. The dump's `unknown` for a missing implementation class - UID is redacted too, since a peer can send that word itself. The lines are a list of the known pynetdicom - 3.0.4 and pydicom 3.0.2 shapes. A line of another shape, or on another logger, passes whole, so a new shape - that a library upgrade adds reaches the log until it is added to the list. The pin tests in + identifier. The DICOM transport applies that rule by default-deny on + every `pynetdicom.*` and `pydicom` logger, at every level (BACKLOG #6637). A line is written only if it is one of + the value-free lines or fully matches one of the templates pinned in + `messagefoundry/transports/_dicom_log_lines.py`. Anything else is withheld: the record then names its logger, + its level and any exception class, with a fixed note, and none of its message or arguments. On a pinned line + the fixed text stays and the value reads `[redacted]` where the library is refusing or flagging it. The UID and AE + title fields of pynetdicom's DEBUG dumps stay only where they pass `_kept` in + `messagefoundry/transports/dicom.py`, the source of record: at least an empty value; a conformant UID; a name in + pydicom's UID dictionary, on a field that is no instance UID; and, on the AE title fields and on Their + Implementation Version Name, a value that passes pynetdicom's AE title check, which an empty or all-space value + does. pynetdicom runs no AE title check on the two titles of an association acceptance, and the screen applies + it to them anyway. The dump's `unknown` for a missing implementation class UID is redacted, since a peer can + send that word itself. A user identity's username and password, and the hex of an extended negotiation item's + application information, are never kept. + + **What an operator still reads and what is lost.** Association requested, accepted, rejected with its result + and reason, released and aborted, the send and receive lines for C-STORE and C-ECHO with their status, and the + library's fixed protocol error lines stay, at least those for a malformed PDU or association field. Lost, at least: the C-FIND, C-GET and C-MOVE progress lines and + identifier dumps, which this engine does not serve; the text of a library exception that matches no template, + including an operating system's socket error text; and every note and group member of an exception. + + Where the engine quotes such an exception, in its own C-STORE line or a delivery error, it keeps the class + and reads `[message withheld]` with the file, line and function that raised it. pynetdicom's own + `TCP Initialisation Error: {exc}` line is different. It has no `exc_info`, so its withheld line keeps + neither the class nor the raising place, and an operator cannot tell a refused connection from a timeout or + a DNS failure from the log. + + **How far it reaches.** A filter on each logger the libraries create, and a log record factory for any other + logger under those names, so a logger created later, one that does not propagate, and a host with no + `logging_setup` handler are all covered. A host that replaces the record factory without calling the one it + found leaves a logger outside the named list unscreened until the next SCP start, C-STORE or SCU association puts + the factory back. A record built by hand and given straight to a handler passes neither. Neither library sets + `propagate = False` on a logger of its own. A traceback's frames and exception class names are written, since + they are code. An `Exception` raised while the screen reads a line withholds that line, and one raised while it + renders the traceback withholds the traceback. Matching is linear in the line's length. + + A delivery error raised while the SCU stores an object holds, on its chain, at most an engine exception that + names the library exception's class, with none of its text. + + **A failed association release does not change the outcome.** The peer's status decides it. After a C-STORE, a + Success or Warning stays delivered and is not sent again, any other status keeps its own outcome, and a send + with no status stays a failure. After a C-ECHO, the test passes only on Success. The release failure is logged + through the screen and the association is aborted. If the abort raises too, that is logged the same way and + the engine makes no further attempt to end the association. + + **The screen assumes a library exception's class behaves as ordinary Python.** A class with hostile attribute, + `__str__` or metaclass code is outside it and can still get text past it, and an ordinary class's name is + written, so a name carrying a value would be written too. + + **A library exception the SCU does not wrap keeps its text.** At least one raised while the SCU opens the + association does. The delivery worker logs only its class, but the text would reach the row's `last_error` + through `safe_exc`, which does not recognise a refused UID. If the worker's write of that error to the store + then fails with an error that is not a database driver's, its fault log prints the text as well. Test + Connection has the same limit: an exception raised while it opens the association or sends the C-ECHO would + reach the result's detail through `safe_exc`. + + `tests/_dicom_log_census.py` scans both installed libraries' log and `warn_and_log` calls against a pinned + census, so a call it can read that a library adds or rewords fails a test until it is read: at least a + literal, an f-string, and text assigned to a local variable it then logs. A line built some other way, such as + a dataset dump's loop variable, is in the census only by that variable's name. The pin tests in `tests/test_dicom_peer_value_logs.py` fail when either library's version changes in the environment they - run in, and when a line they read changes, so a change to the lock has to re-read the shapes. They do not - reach a site's own install: the `[dicom]` extra pins pynetdicom exactly but lets pydicom resolve to any - release from 3.0.2 below 3.1, and the tests run only the release the lock names. Known shapes not covered - yet, at least: a flagged UID that spells a name in pydicom's UID dictionary, which a dump field, the - `No presentation context for` line and the `No supported service class` line keep; and pydicom's - `Unknown VR` line, which names two bytes of an object and is written only with pydicom's own debug - switched on. The SCP reads each association - request and command set once before pynetdicom does. What that read writes on the loggers the SCP filters is + run in. They do not reach a site's own install: the `[dicom]` extra pins pynetdicom exactly but lets pydicom + resolve to any release from 3.0.2 below 3.1. Known limits, at least: a flagged UID that spells a name in pydicom's UID + dictionary is kept by a dump field, the `No presentation context for` line and the `No supported service + class` line. The SCP reads each association + request and command set once before pynetdicom does. What that read writes on the named loggers is written only where the command set itself ends the association. Where a later PDU ends it, before pynetdicom reads the message, that read's lines are written nowhere. A line on any other logger is written - twice. pydicom also raises each of its lines above as a `UserWarning`, which would carry the value to - stderr. A warnings filter, installed at import, at each SCP start, at each C-STORE the SCP serves and - before each SCU read and association, ignores those copies and no other pydicom warning; a host that resets - the process's warnings filters between those points brings the copy back until the next one, and the SCP's - pre-read of a command set is not one of them. Under context-aware warnings, the free-threaded default, the - filter is installed at every one of those points, which also repeats another library's once-per-location - warning. The filter also renders a codec error on these loggers - without the byte it failed on, for a host whose handlers lack the engine's log chain. The engine's - own C-STORE lines name an object's SOP class and instance UIDs only when they are conformant, and `[redacted]` - otherwise, and redact a refused value of a shape the filter knows from a library error they quote; a - library error of another shape is quoted through `safe_exc` alone. + twice, screened. pydicom also raises each of its lines as a warning, which would carry the value to + stderr. One warnings filter, scoped to pydicom's modules so that no other library's warning is silenced, is + installed at import, at each SCP start, at each C-STORE the SCP serves and before each SCU read and + association. A host that resets the process's warnings filters between those points brings the copy back + until the next one, and the SCP's pre-read of a command set is not one of them. Under context-aware warnings, + the free-threaded default, the filter is installed at every one of those points, which also repeats another + library's once-per-location warning. The engine's own C-STORE lines name an object's SOP class and instance + UIDs only when they are conformant, and `[redacted]` otherwise, and quote a library error only through the + same screen. - **Egress is fail-closed.** A DIMSE destination is gated by `[egress].allowed_tcp`; a DICOMweb destination by `[egress].allowed_http` — both enforced at load/reload/start. diff --git a/docs/PHI.md b/docs/PHI.md index f9e82dc1bb..fa2d1ee588 100644 --- a/docs/PHI.md +++ b/docs/PHI.md @@ -362,15 +362,16 @@ path** (no separate at-rest tier): - **DICOM objects `[BUILT]` (ADR 0025).** A received DICOM object is **PHI** — the header carries PatientName / MRN / DOB — and is stored through the store cipher like any other body, never logged at INFO+, egress-allowlisted, and TLS off-loopback. Logs/errors carry only **routing-safe identifiers** - (SOPClassUID / Modality / UIDs / AE title), never the dataset or element values. That rule covers + (SOPClassUID / Modality / UIDs / AE title), never the dataset or element values, except as + [DICOM.md](DICOM.md) section 5's limits state. That rule covers third-party library loggers too, such as pynetdicom's and pydicom's, and a peer-sent value either library refuses or flags as non-conformant must never be logged verbatim (owner ruling 2026-11-03, - BACKLOG #5081). The DICOM transport applies that rule through a log filter that redacts the value - from at least a list of known pynetdicom and pydicom line shapes, so it meets the rule only for - those shapes. A line of a new shape, such as a library upgrade could add, passes whole until it is - added. The pin tests fail when either library's version changes in the environment they run in, - which is not a site's own install. The list, and what it does not cover, is in - [DICOM.md](DICOM.md) section 5. (Pixel data can carry + BACKLOG #5081). The DICOM transport applies that rule by default-deny on those libraries' loggers + (BACKLOG #6637): a line that is neither a pinned value-free line nor a full match of a pinned + template is withheld. + The pin tests fail when either library's version changes in the environment they run in, + which is not a site's own install. What a withheld library line keeps, what stays, what an + operator loses and the limits are in [DICOM.md](DICOM.md) section 5. (Pixel data can carry *burned-in* PHI, but **pixel-data handling is out of scope.**) - **Base64-carried binary bodies `[BUILT]` (ADR 0028).** A base64-encoded body is **still PHI** — encoding is not obfuscation — so the never-log rules (§7) apply unchanged. Base64 inflates size by diff --git a/messagefoundry/transports/_dicom_log_lines.py b/messagefoundry/transports/_dicom_log_lines.py new file mode 100644 index 0000000000..255d93fa9a --- /dev/null +++ b/messagefoundry/transports/_dicom_log_lines.py @@ -0,0 +1,570 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""The pynetdicom and pydicom log lines an operator may read (vault BACKLOG #6637 item 10). + +Everything else those libraries log is withheld by :mod:`messagefoundry.transports.dicom`, so this +file is an allowlist: a line missing from it costs an operator a line of diagnosis, and a line wrongly +in it is a leak. Read from pynetdicom 3.0.4 and pydicom 3.0.2. ``tests/_dicom_log_census.py`` pins what +those libraries can log, so an upgrade that adds or rewords a line fails a test. + +:data:`VALUE_FREE_LINES` holds whole lines with nothing interpolated. :data:`TEMPLATES` holds lines +with fields, written with ``{kind}`` slots. A slot's kind decides what happens to its text: + +* ``uid``, ``quoted_uid``, ``instance``, ``title``, ``version``, ``move``: the value a peer sent. It + stays only where the engine's check on that kind of value passes, and otherwise reads + ``[redacted]``. +* ``name``, ``keyword``, ``codecs``: a word the library supplies, which stays only if it is in a + closed list: :data:`ELEMENT_NAMES`, pydicom's keyword dictionary, or Python's codec names. Anything + else reads ``[redacted]``. +* ``value``, ``hex_dump``: a value the library is refusing or flagging, or bytes it dumps. It always + reads ``[redacted]``. +* Every other kind matches only a number or a word from the library's own fixed vocabulary, so what + it matches stays. A field outside its pattern makes the line match no template, and so withholds it. + +Matching stays linear on a peer's text: a template has at most one unbounded run that can overlap +what follows it. ``quoted_uid`` stops at a quote, and ``{indent}{hex_dump}`` is two runs over +characters neither shares. +""" + +from __future__ import annotations + +import functools +import re +from typing import NamedTuple + +#: An unbounded run. It stops at a line break, so a value holding one matches no template and its +#: line is withheld. +_TO_LINE_END = r"[^\r\n]*" + +#: The text each kind of slot may match. +_SLOT_PATTERNS = { + "uid": _TO_LINE_END, + "instance": _TO_LINE_END, + "title": _TO_LINE_END, + "version": _TO_LINE_END, + "move": _TO_LINE_END, + "value": _TO_LINE_END, + "quoted_uid": r"[^'\r\n]*", + "int": r"[0-9]{1,10}", + "number": r"[0-9]{1,10}|None", + "hex": r"[0-9A-Fa-f]{1,8}", + "vr": r"[A-Z]{2}", + "tag": r"[0-9A-F]{4},[0-9A-F]{4}", + "name": r"[A-Za-z][A-Za-z_ /-]{0,63}", + "keyword": r"[A-Za-z0-9]{1,64}", + "message_type": r"[CN][-_][A-Z_-]{2,24}", + "role": r"SCU|SCP", + "roles": r"SCP/SCU|SCP|SCU|Default|", + "codecs": r"[A-Za-z0-9_, -]{1,64}", + "struct_format": r"[<>=!@]?[A-Za-z0-9]{1,8}", + "see_url": r"https://dicom\.nema\.org/[A-Za-z0-9/._#-]{0,120}", + "indent": r" +", + "hex_dump": r"[0-9a-f]{2}(?: [0-9a-f]{2})*", + "status_word": r"Success|Failure|Warning|Cancel|Pending|Unknown", + "presence": r"Present|None", + "yes_none": r"Yes|None", + "priority": r"Low|Medium|High", + "standalone_charset": r"ISO_IR 192|GBK|GB18030", + "refusal_reason": ( + r"must be str|must not exceed 16 characters|must only contain ASCII characters" + r"|must not contain control characters or backslashes|must be pydicom\.uid\.UID" + r"|UID is non-conformant|must not be an empty str|must not exceed 64 characters" + ), + "assoc_result": ( + r"Accepted|Rejected Permanent|Rejected Transient|Rejected \(Permanent\)" + r"|Rejected \(Transient\)|\(no value available\)" + ), + "assoc_source": ( + r"Service User|Service Provider \(ACSE\)|Service Provider \(Presentation\)" + r"|DUL service-user|DUL service-provider \(ACSE related\)" + r"|DUL service-provider \(presentation related\)|DUL service-provider|Reserved" + r"|\(no value available\)" + ), + "assoc_reason": ( + r"No reason given|Application context name not supported" + r"|Calling AE title not recognised|Called AE title not recognised" + r"|Protocol version not supported|Temporary congestion|Local limit exceeded|Reserved" + r"|Unrecognised PDU|Unexpected PDU|Unrecognised PDU parameter|Unexpected PDU parameter" + r"|Invalid PDU parameter value|\(no value available\)" + ), + "context_result": ( + r"Accepted|User Rejection|Provider Rejection|Rejected - Abstract Syntax Not Supported" + r"|Rejected - Transfer Syntax Not Supported|\(no value available\)" + ), + "identity_type": ( + r"Username/Password|Username|Kerberos|SAML|JSON Web Token|\(no value available\)" + ), + "type_name": ( + r"str|bytes|bytearray|int|float|list|tuple|dict|NoneType|Decimal|UID|MultiValue" + r"|DSfloat|DSdecimal|IS|PersonName" + ), + "dataset_encoding": r"(?:Deflated )?(?:Little|Big) Endian (?:Implicit|Explicit)", +} + +#: The slots whose text is never kept. +ALWAYS_REDACTED_KINDS = frozenset({"value", "hex_dump"}) +#: The slots whose text is a peer's value: each is checked, or never kept. +PEER_VALUE_KINDS = ALWAYS_REDACTED_KINDS | { + "uid", + "quoted_uid", + "instance", + "title", + "version", + "move", + "name", + "keyword", + "codecs", +} + +#: The element names pynetdicom passes to ``set_uid`` and ``set_ae``, and the two it names in its own +#: non-conformant lines. A test pins them against the library. +ELEMENT_NAMES = frozenset( + { + "Abstract Syntax Name", + "Affected SOP Class UID", + "Affected SOP Instance UID", + "Application Context Name", + "Called AE Title", + "Calling AE Title", + "Implementation Class UID", + "Implementation Version Name", + "Move Destination", + "Move Originator AE Title", + "Related General SOP Class UID", + "Requested SOP Instance UID", + "SOP Class UID", + "Service Class UID", + "Transfer Syntax Name", + "abstract_syntax", + "ae_title", + "implementation_class_uid", + "implementation_version_name", + "require_calling_aet", + } +) + +_SLOT = re.compile(r"\{([a-z_]+)\}") + +#: Lines with fields, tried in order, so a line's longer form comes before the one with its tail cut. +TEMPLATES: tuple[str, ...] = ( + # --- Association and message progress, the lines an operator reads first --- + "Sending Store Request: MsgID {int}", + "Sending Store Request: MsgID {int}, (CT)", + "Sending Store Request: MsgID {int}, (MR)", + "Sending Echo Request: MsgID {int}", + "Received Echo Request (MsgID {int})", + "Received Echo Response (Status: 0x{hex} - {status_word})", + "Received Store Response (Status: 0x{hex} - {status_word})", + "Received DIMSE message with invalid or rejected context ID: {int}", + "Result: {assoc_result}, Source: {assoc_source}", + "Reason: {assoc_reason}", + # --- Protocol errors, each naming a number or a fixed word --- + "Received an invalid {message_type} response from the peer", + "Received an unexpected {message_type} message from the peer", + "Received unexpected {message_type} service message", + "{message_type} message received during association release, ignoring", + "Unknown status value returned by the EVT_C_STORE handler: 0x{hex}", + "The received PDU is shorter than expected ({int} of {int} bytes received)", + "Unknown PDU type received '0x{hex}'", + "A-ASSOCIATE-RQ: Unsupported protocol version '0x{hex}'", + "Invalid A-ABORT-RQ 'Source' {number}", + "Invalid A-ABORT 'Source' value '{number}'", + "Invalid A-ABORT-RQ 'Reason/Diagnostic' {number}", + "Invalid A-ASSOCIATE 'Result' {number}", + "Invalid A-ASSOCIATE 'Result Source' {number}", + "Invalid A-ASSOCIATE 'Result Source' {number} and/or 'Diagnostic' {number} values", + "Invalid Presentation Context Item 'Result' {number}", + "Invalid 'User Identity Type' {number}", + "Non-conformant VM {int} for '{keyword}', taking the first value", + "maximum_pdu_size set to {int}", + 'pydicom.read_dataset() TransferSyntax="{dataset_encoding}"', + # --- A SOP class or transfer syntax the peer named --- + "No presentation context for '{quoted_uid}' has been accepted by the peer for the {role} role", + "No presentation context for '{quoted_uid}' has been accepted by the peer with " + "'{quoted_uid}' transfer syntax for the {role} role", + "No presentation context for '{value}", + "No supported service class available for the SOP Class UID '{quoted_uid}', please see the " + "pynetdicom.sop_class.register_uid() function if you need to add support for a private, " + "retired or otherwise unknown SOP Class UID", + "No supported service class available for the SOP Class UID '{value}", + # --- What pynetdicom says as it refuses or flags a value --- + "Invalid '{name}' value - must not consist entirely of spaces", + "Invalid '{name}' value - must not be an empty str", + "Invalid '{name}' value '{value}' - {refusal_reason}", + "Invalid '{name}' value '{value}", + "Non-conformant '{name}' value '{value}'", + "Non-conformant '{name}' value '{value}", + "The {name} '{value}' is non-conformant", + "A UID has been added to 'transfer_syntax' that is not a transfer syntax: '{value}'", + "A UID has been added to 'transfer_syntax' that is not a transfer syntax: '{value}", + "Unable to decode '{value}' using the {codecs} codec(s)", + "Unable to decode '{value}", + # --- What pydicom says as it refuses or flags a value --- + "The value length ({int}) exceeds the maximum length of {int} allowed for VR {vr}.", + "The value length ({int}) exceeds the maximum length of {int} allowed for VR {vr}. Please " + "see <{see_url}> for allowed values for each VR.", + "The PN component length ({int}) exceeds the maximum allowed length of {int}.", + "A value of type '{type_name}' cannot be assigned to a tag with VR {vr}.", + "The value length ({int}) exceeds the maximum length of {int} allowed for VR {vr}. Invalid " + "value for VR {vr}: {value}. Please see <{see_url}> for allowed values for each VR.", + "The value length ({int}) exceeds the maximum length of {int} allowed for VR {vr}. Invalid " + "value for VR {vr}: {value}", + "Invalid value for VR {vr}: {value}. Please see <{see_url}> for allowed values for each VR.", + "Invalid value for VR {vr}: {value}", + "Incorrect value for Specific Character Set '{value}", + "Unknown encoding '{value}' - using default encoding instead", + "Unknown encoding '{value}", + "Value '{standalone_charset}' for Specific Character Set does not allow code extensions, " + "ignoring: {value}", + 'Value "{value}" is not valid for elements with a VR of {vr}\n' + "Set reading_validation_mode to WARN or IGNORE to bypass", + 'Value "{value}" is not valid for elements with a VR of {vr}', + "Expected total bytes to be an even multiple of bytes per value. Instead received {value} " + "with length {int} and struct format '{struct_format}' which corresponds to bytes per value " + "of {int}.", + "could not convert string to float: {value}", + "invalid literal for int() with base {int}: {value}", + "({tag}) '{value}' is not a valid private creator", + "'({tag}) \\'{value}\\' is not a valid private creator'", + "\"({tag}) '{value}' is not a valid private creator\"", + # --- pynetdicom's DEBUG dumps, by label --- + "{indent}{hex_dump}", + "Their Implementation Class UID: {uid}", + "Their Implementation Class UID: {uid}", + "Our Implementation Class UID: {uid}", + "Their Implementation Version Name: {version}", + "Their Implementation Version Name: {version}", + "Our Implementation Version Name: {version}", + "Application Context Name: {uid}", + "Calling Application Name: {title}", + "Called Application Name: {title}", + "Responding Application Name: {title}", + "Their Max PDU Receive Size: {int}", + "Our Max PDU Receive Size: {int}", + " Context ID: {int} (Proposed)", + " Context ID: {int} ({context_result})", + " Context ID: {int}", + " Abstract Syntax: ={uid}", + " Abstract Syntax: ={uid}", + " Accepted Transfer Syntax: ={uid}", + " ={uid}", + " Service Class: ={uid}", + " SOP Class: ={uid}", + " Accepted SCP/SCU Role: {roles}", + " Proposed SCP/SCU Role: {roles}", + " Maximum Invoked Operations: {int}", + " Maximum Performed Operations: {int}", + " Authentication Mode: {int} - {identity_type}", + " Username: {value}", + " Password: {value}", + " Kerberos Service Ticket (not dumped) length: {int}", + " SAML Assertion (not dumped) length: {int}", + " JSON Web Token (not dumped) length: {int}", + "User Identity Negotiation Response: {yes_none}", + "Abort Source: {assoc_source}", + "Abort Reason: {assoc_reason}", + "Result: {assoc_result}", + "Source: {assoc_source}", + "Reason: {assoc_reason}", + "Message ID : {int}", + "Message ID Being Responded To : {int}", + "Presentation Context ID : {int}", + "Affected SOP Class UID : {uid}", + "Affected SOP Class UID : {uid}", + "Requested SOP Class UID : {uid}", + "Affected SOP Instance UID : {instance}", + "Requested SOP Instance UID : {instance}", + "Move Originator : {move}", + "Move Destination : {move}", + "Priority : {priority}", + "Data Set : {presence}", + "Identifier : {presence}", + "Attribute List : {presence}", + "Attribute Identifier List : {presence}", + "Modification List : {presence}", + "Action Information : {presence}", + "Action Reply : {presence}", + "Event Information : {presence}", + "Event Reply : {presence}", + "Action Type ID : {number}", + "Event Type ID : {number}", + "Remaining Sub-operations : {number}", + "Completed Sub-operations : {number}", + "Failed Sub-operations : {number}", + "Warning Sub-operations : {number}", + "Status : 0x{hex}", + "Status : 0x{hex} - {status_word}", +) + + +class Template(NamedTuple): + """One entry of :data:`TEMPLATES`, compiled. Group ``n + 1`` is the text of ``kinds[n]``.""" + + pattern: re.Pattern[str] + kinds: tuple[str, ...] + + +def compile_template(text: str) -> Template: + """``text`` with each ``{kind}`` slot turned into a capturing group and all else literal.""" + parts: list[str] = [] + kinds: list[str] = [] + position = 0 + for slot in _SLOT.finditer(text): + parts.append(re.escape(text[position : slot.start()])) + kind = slot.group(1) + kinds.append(kind) + parts.append(f"({_SLOT_PATTERNS[kind]})") + position = slot.end() + parts.append(re.escape(text[position:])) + return Template(re.compile("".join(parts)), tuple(kinds)) + + +@functools.cache +def compiled_templates() -> tuple[Template, ...]: + """:data:`TEMPLATES`, compiled once, on the first line a library logs.""" + return tuple(compile_template(text) for text in TEMPLATES) + + +#: Whole lines with nothing interpolated, from the census. Generated: see tests/_dicom_log_census.py. +VALUE_FREE_LINES: frozenset[str] = frozenset( + { + # BEGIN GENERATED + "", + " Proposed Transfer Syntax:", + " Proposed Transfer Syntaxes:", + " Related General SOP Class(es):", + " Related General SOP Classes: None", + " Positive Response Requested: No", + " Positive Response Requested: None", + " Positive Response Requested: Yes", + "# DICOM Dataset", + "# Request Identifier", + "# Response Identifier", + "'A_ASSOCIATE.called_presentation_address' must be an AddressInformation instance or None", + "'datetime.datetime' doesn't allow a value of '60' for the seconds component, changing to '59'", + "'datetime.time' doesn't allow a value of '60' for the seconds component, changing to '59'", + "'dtype_corrected_for_endianness' is deprecated and will be removed in v4.0", + "'pydicom.dataelem.DataElement_from_raw' is deprecated and will be removed in v4.0, please use 'pydicom.dataelem.convert_raw_data_element' instead", + "'sop_class_uid' must be set prior to Association", + "'transfer_syntax' contains an invalid UID", + "'write_like_original' is deprecated and will be removed in v4.0, please use 'enforce_file_format' instead", + "======================= INCOMING A-ASSOCIATE-AC PDU ========================", + "======================= INCOMING A-ASSOCIATE-RJ PDU ========================", + "======================= INCOMING A-ASSOCIATE-RQ PDU ========================", + "======================= OUTGOING A-ASSOCIATE-AC PDU ========================", + "======================= OUTGOING A-ASSOCIATE-RJ PDU ========================", + "======================= OUTGOING A-ASSOCIATE-RQ PDU ========================", + "========================== END A-ASSOCIATE-AC PDU ==========================", + "========================== END A-ASSOCIATE-RJ PDU ==========================", + "========================== END A-ASSOCIATE-RQ PDU ==========================", + "========================== INCOMING DIMSE MESSAGE ==========================", + "========================== OUTGOING DIMSE MESSAGE ==========================", + "=========================== DEBUG - ENCODED PDU ============================", + "=========================== DEBUG - PDU SUMMARY ============================", + "=========================== INCOMING A-ABORT PDU ===========================", + "=========================== OUTGOING A-ABORT PDU ===========================", + "============================ END DIMSE MESSAGE =============================", + "============================= END A-ABORT PDU ==============================", + "============================= END ENCODED PDU ==============================", + "============================= END PDU SUMMARY ==============================", + "A non-conformant UID has been added to 'transfer_syntax'", + "A-ABORT or A-RELEASE-RQ received during Q/R sub-operations", + "ACSE timeout reached while waiting for response to association request", + "ACSE timeout set to 30 seconds", + "A_ABORT.abort_source value not set", + "A_ABORT.provider_reason parameter not set", + "A_ASSOCIATE.diagnostic set to an unknown value", + "A_ASSOCIATE.presentation_context_definition_list must be a list", + "A_ASSOCIATE.presentation_context_definition_results_list must be a list", + "A_ASSOCIATE.result set to an unknown value", + "A_ASSOCIATE.result_source set to an unknown value", + "A_ASSOCIATE.user_information must be a list", + "A_RELEASE.result must be None or 'affirmative'", + "Abort Parameters:", + "Aborting Association", + "Accept Parameters:", + "Accepted Asynchronous Operations Window Negotiation:", + "Accepted Asynchronous Operations Window Negotiation: None", + "Accepted Extended Negotiation:", + "Accepted Extended Negotiation: None", + "Accepting Association", + "An A-RELEASE collision has occurred", + "Applying a VOI LUT on a float input array may give incorrect results", + "Association Aborted", + "Association Aborted (A-P-ABORT)", + "Association Accepted", + "Association Rejected", + "Association Released", + "Association request failed: unable to connect to remote", + "AssociationSocket instantiated with both a 'client_socket' and bind 'address'. The original socket will not be rebound", + "Attempted to add an invalid transfer syntax", + "Attempted to send data over closed connection", + "Attempted to set A_ASSOCIATE.presentation_context_definition_list to a list which includes an invalid items", + "Attempted to set A_ASSOCIATE.presentation_context_definition_results_list to a list which includes one or more invalid items", + "Attempted to set A_ASSOCIATE.user_information to a list which includes an unsupported item", + "Attempted to set A_P_ABORT.provider_reason to an invalid value", + "Attempted to set Priority parameter to an invalid value", + "C-STORE sub-operation failed.", + "Call to dcmread()", + "Caller passed file name", + "Caller passed file object", + "Connection closed before the entire PDU was received", + "Connection closed while waiting for DIMSE message", + "DIMSE timeout reached while waiting for message response", + "Data Set : None", + "Deferred read warning -- file modification time has changed", + "Exception in DUL.run(), aborting association", + "Exception in handler bound to 'evt.EVT_C_FIND'", + "Exception in handler bound to 'evt.EVT_C_GET'", + "Exception in handler bound to 'evt.EVT_C_MOVE'", + "Exception in handler bound to 'evt.EVT_USER_ID'", + "Exception in the handler bound to 'evt.EVT_C_ECHO', responding with a default 'Status' value of 0x0000 (Success)", + "Exception in the handler bound to 'evt.EVT_C_STORE'", + "Exception raised by pixel data handler", + "Exception raised in handler bound to 'evt.EVT_ASYNC_OPS'", + "Exception raised in handler bound to 'evt.EVT_SOP_COMMON'", + "Exception raised in handler bound to 'evt.EVT_SOP_EXTENDED'", + "Failed encoding the response 'Action Reply' dataset", + "Failed encoding the response 'Attribute List' dataset", + "Failed encoding the response 'Event Reply' dataset", + "Failed encoding the response 'Identifier' dataset", + "Failed to decode the received Identifier dataset", + "Failed to encode the supplied 'Action Information' dataset", + "Failed to encode the supplied 'Attribute List' dataset", + "Failed to encode the supplied 'Modification List' dataset", + "Failed to encode the supplied Dataset", + "Failed to encode the supplied Identifier dataset", + "Failed to encode the supplied dataset", + "File is not conformant with the DICOM File Format: 'DICM' prefix is missing from the File Meta Information header or the header itself is missing. Assuming no header and continuing.", + "Find SCP Request Identifier:", + "Find SCP Response Identifier:", + "Find SCP Response: 0x0000 (Success)", + "Get SCP Request Identifier:", + "Handler bound to 'evt.EVT_C_MOVE' yielded further (status, dataset) results but these will be ignored as the sub-operations are complete", + "Hash not found in hashes.json. File will be updated.", + "Implementation Class UID has not been set", + "Invalid 'Move Originator AE Title' in C-STORE request", + "Invalid element tag value used with the 'in' operator: tags have a maximum value of (0xFFFF, 0xFFFF)", + "Invalid status returned by callback", + "Invalid status returned by the EVT_C_STORE handler", + "Invalid type returned by handler bound to 'evt.EVT_SOP_COMMON'", + "Invalid type returned by handler bound to 'evt.EVT_SOP_EXTENDED'", + "Invalid value in Reason field in A-ASSOCIATE-RJ PDU", + "Invalid value in Result field in A-ASSOCIATE-RJ PDU", + "Invalid value in Source field in A-ASSOCIATE-RJ PDU", + "Maximum Length Received must be greater than 0", + "Maximum Length Received must be numerical", + "Maximum Number Operations Invoked must be an int", + "Maximum Number Operations Performed must be an int", + "Message Type : C-CANCEL RQ", + "Message Type : C-ECHO RQ", + "Message Type : C-FIND RQ", + "Message Type : C-FIND RSP", + "Message Type : C-GET RQ", + "Message Type : C-GET RSP", + "Message Type : C-MOVE RQ", + "Message Type : C-MOVE RSP", + "Message Type : C-STORE RQ", + "Message Type : C-STORE RSP", + "Message Type : N-ACTION RQ", + "Message Type : N-ACTION RSP", + "Message Type : N-CREATE RQ", + "Message Type : N-CREATE RSP", + "Message Type : N-DELETE RQ", + "Message Type : N-DELETE RSP", + "Message Type : N-EVENT-REPORT RQ", + "Message Type : N-EVENT-REPORT RSP", + "Message Type : N-GET RQ", + "Message Type : N-GET RSP", + "Message Type : N-SET RQ", + "Message Type : N-SET RSP", + "Move SCP Request Identifier:", + "Move SCP: Unable to associate with destination AE", + "Network timeout reached", + "No accepted presentation contexts", + "No exact matching context found for 'Unified Procedure Step - Push SOP Class', checking accepted contexts for other UPS SOP classes", + "No supported Presentation Contexts have been defined", + "None of the records in the DICOMDIR dataset contain all the query elements, consider using the 'load' parameter to expand the search to the corresponding SOP instances", + "One or more download failures occurred, the list of matching file paths may be incomplete", + "One or more requested presentation contexts must be set prior to association negotiation", + "Positive Response Requested must be boolean", + "Presentation Context:", + "Presentation Contexts:", + "Presentation Contexts: None", + "Primary Field must be bytes if requesting Association, None otherwise", + "Reading File Meta Information preamble...", + "Reading File Meta Information prefix...", + "Received C-CANCEL-FIND RQ from peer", + "Received C-CANCEL-GET RQ from peer", + "Received C-CANCEL-MOVE RQ from peer", + "Received Get Response", + "Received Store Request", + "Received an invalid A-ASSOCIATE response from the peer", + "Received an invalid C-FIND response from the peer", + "Received an invalid DIMSE message", + "Received invalid dataset from callback", + "Reject Parameters:", + "Rejecting Association", + "Related General SOP Class Identification contains an invalid UID", + "Related General SOP Class Identification must be a list of pydicom.uid.UID, str or bytes", + "Releasing Association", + "Request Parameters:", + "Requested Asynchronous Operations Window Negotiation:", + "Requested Asynchronous Operations Window Negotiation: None", + "Requested Common Extended Negotiation:", + "Requested Common Extended Negotiation: None", + "Requested Extended Negotiation:", + "Requested Extended Negotiation: None", + "Requested User Identity Negotiation:", + "Requested User Identity Negotiation: None", + "Requesting Association", + "SCP Role must be boolean", + "SCU Role must be boolean", + "SOP Class UID and Service Class Application Information must be set prior to Association negotiation", + "SOP Class UID and Service Class UID must be set prior to Association negotiation", + "Secondary Field must be bytes if requesting Association with User Identity Type equal to 2, None otherwise", + "Secondary Field must be set when User Identity is 2", + "Sending C-CANCEL request", + "Server Response must be bytes or None", + "Service Class Application Information should be a bytes object", + "The C-GET request handler yielded more than 65535 matches", + "The C-MOVE request handler yielded more than 65535 matches", + "The EVT_C_STORE handler returned a Dataset without a 'Status' element", + "The Implementation Class UID must be set prior to requesting Association", + "The N-CREATE-RQ has no 'Affected SOP Instance UID' value and the 'evt.EVT_N_CREATE' handler doesn't include one in the 'Attribute List' dataset", + "The end of the encapsulated pixel data has been reached but fewer frames than expected have been found", + "The end of the encapsulated pixel data has been reached but fewer frames than expected have been found. Please confirm that the generated frame data is correct", + "The end of the encapsulated pixel data has been reached but no JPEG EOI/EOC marker was found, the final frame may be be invalid", + "The end of the encapsulated pixel data has been reached but no JPEG EOI/EOC marker was found, the returned frame data may be invalid", + "The following presentation contexts have inconsistent scu_role/scp_role values (if one is None, both must be):\n ", + "The number of bytes of compressed pixel data matches the expected number for uncompressed data - check that the transfer syntax has been set correctly", + "The number of items in (7FE0,0001) 'Extended Offset Table' and (7FE0,0002) 'Extended Offset Table Lengths' don't match - the extended offset table will be ignored", + "The odd length pixel data is missing a trailing padding byte", + "The overlay data length is odd and misses a padding byte.", + "Unable to decode the received 'Action Reply' dataset", + "Unable to decode the received 'Attribute List' dataset", + "Unable to decode the received 'Event Reply' dataset", + "Unable to decode the received PDU data", + "Unable to encode the supplied 'Event Information' dataset", + "Unable to return an ndarray that's a view on the original buffer for 8-bit pixel data encoded as OW with 'Explicit VR Big Endian'", + "Unable to return an ndarray that's a view on the original buffer for bit-packed pixel data", + "Unable to return an ndarray that's a view on the original buffer for uncompressed pixel data with a photometric interpretation of 'YBR_FULL_422'", + "Unable to return an ndarray that's a view on the original buffer if applying a color space conversion", + "Unable to return an ndarray that's a view on the original buffer when (0028,0101) 'Bits Stored' doesn't equal (0028,0100) 'Bits Allocated' and 'correct_unused_bits=True'. In most cases you can pass 'correct_unused_bits=False' instead to get a view if the uncorrected array is equivalent to the corrected one.", + "Unable to set the User Identity Negotiation's 'server_response'", + "User Identity Type and Primary Field must be set prior to Association negotiation", + "User Identity Type must be 1, 2, 3, 4 or 5 if requesting Association, None otherwise", + "User Identity Type must be an int or None", + "User callback returned a `Dataset` without a Status element", + "User identity failed verification", + "User's C-GET generator yielded further (status, dataset) results but these will be ignored as the sub-operations are complete", + "Using Presentation Context:", + "Values for elements with a VR of 'DS' values must be <= 16 characters long. Use a smaller string, set 'config.settings.reading_validation_mode' to 'WARN' to override the length check, use 'Decimal.quantize()' and initialize with a 'Decimal' instance, or explicitly construct a DS instance with 'auto_format' set to True", + "connection_timeout set to None", + "dimse_timeout set to 30 s", + "maximum_associations set to 1", + "network_timeout set to 60 s", + "pydicom.write_dataset() failed:", + # END GENERATED + } +) diff --git a/messagefoundry/transports/dicom.py b/messagefoundry/transports/dicom.py index 50d5969118..a19454e024 100644 --- a/messagefoundry/transports/dicom.py +++ b/messagefoundry/transports/dicom.py @@ -71,12 +71,14 @@ import sys import threading import time +import traceback import warnings import zlib from collections.abc import Callable, Coroutine, Iterator, Mapping from concurrent.futures import TimeoutError as FutureTimeoutError +from encodings.aliases import aliases from io import BytesIO -from typing import Any, ClassVar, NamedTuple, assert_never, cast +from typing import Any, ClassVar, assert_never, cast from messagefoundry.auth.trust_anchors import inbound_ca_cadata, refuse_an_unread_ca_pin from messagefoundry.config.models import ( @@ -100,6 +102,7 @@ resolve_trust_anchor, skips_validity_period, ) +from messagefoundry.config.wiring import _type_name from messagefoundry.keywrap import load_connection_cert_chain from messagefoundry.netaddr import ALLOWLIST_RULE_TEXT, allowlist_restricts, allowlist_shortfall from messagefoundry.parsing.binary import BinaryCarriageError @@ -113,15 +116,15 @@ ) from messagefoundry.parsing.dicom.errors import DicomBombError from messagefoundry.parsing.peek import DEFAULT_MAX_MESSAGE_BYTES -from messagefoundry.redaction import ( - _REDACTED, - prepare_log_record, - prints_a_codec_error, - safe_exc, - safe_text, - safe_traceback, -) +from messagefoundry.redaction import _REDACTED, prints_a_codec_error, safe_exc, safe_text from messagefoundry.tls_handshake_failures import HUNG_UP, HandshakeFailures, handshake_cause +from messagefoundry.transports._dicom_log_lines import ( + ALWAYS_REDACTED_KINDS, + ELEMENT_NAMES, + PEER_VALUE_KINDS, + VALUE_FREE_LINES, + compiled_templates, +) from messagefoundry.transports.admission import ( REFUSAL_LOG_MAX_PER_WINDOW, REFUSAL_LOG_WINDOW_SECONDS, @@ -495,245 +498,38 @@ def _drain_readable(sock: socket.socket) -> None: _SERVED_COMMANDS = frozenset({0x0001, 0x0030}) -class _Shape(NamedTuple): - """One kind of log line that names a peer's value. ``head`` is matched at the start of the line, - or found anywhere in it where ``anywhere`` is set; the value runs from there to ``tail``, the - fixed text the line ends with, found from its last ``anchor``. A line whose end is not ``tail`` - loses everything after its head. ``whole`` is for a line with more than one value: it stays as - it is where it matches whole and :func:`_kept` keeps each group, and otherwise loses everything - after its head. ``warning`` is the pattern of the ``UserWarning`` pydicom raises beside the line, - with the same value in it. ``anchor_required`` is for a head this general: it counts only in a - line that holds ``anchor``. In ``head``, ``tail`` and ``whole``, each unbounded run stops at the literal after - it, so a long value costs one pass, on whatever thread logged it. A ``warning`` pattern can - backtrack over the value: ``.*`` gives text back one character at a time. Each holds at most - one such run, and ``warnings`` tries each only from the start of the warning (``re.match``), - so there its cost stays linear in the text. That rests on ``re.match``: under ``re.search`` - at least three of them are quadratic. The test that guards these patterns, - ``test_no_warning_filter_nests_an_unbounded_scan_inside_a_leading_one``, reads the pattern's - characters, not its structure: it flags one that starts with the two characters ``.*`` and - holds another ``*`` after them. It misses at least a leading run spelled ``.+``, ``.{0,}``, - ``(?s).*``, ``(?s:.*)`` or ``[\\s\\S]*``, and a second run spelled ``+`` or ``{n,}``, and it - does not check the one-run rule as a whole. - CORRECTED 2026-11-23 (BACKLOG #8348 item 8): this read "Each is matched from the start of the - warning with at most one such run, so its cost stays linear in the text", which named neither - the ``re.match`` it rests on nor how little the test checks.""" - - head: re.Pattern[str] - anchor: str | None = None - tail: re.Pattern[str] | None = None - anywhere: bool = False - whole: re.Pattern[str] | None = None - warning: str | None = None - anchor_required: bool = False - - -#: The lines, by logger, that name a value a peer sent which pynetdicom or pydicom refuses or flags -#: (owner ruling 2026-11-03, vault BACKLOG #5081). Each keeps its head and tail and puts -#: :data:`_REDACTED` where the value was. ``pynetdicom.utils`` writes ``set_uid`` and ``set_ae``: -#: ``Non-conformant '' value ''`` at WARNING, and ``Invalid '' value '' - -#: `` at ERROR, whose reasons are fixed strings in ``pynetdicom._validators``. -#: ``pynetdicom.presentation`` and ``pynetdicom.pdu_primitives`` write ``The '' is -#: non-conformant``, and ``pynetdicom.presentation`` names a proposed or accepted transfer syntax -#: again when it is under the DICOM root and no transfer syntax. ``pynetdicom._handlers`` writes -#: ``