Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 14 min read

UD50 file handoff: review ZIP member names as a namespace before extraction

A document bundle can contain two individually ordinary names that cannot coexist in the intended destination. One entry names a file docs; another names docs/manual.pdf. The second needs docs to be a directory. Checking

UD50 file handoff: review ZIP member names as a namespace before extraction

A document bundle can contain two individually ordinary names that cannot coexist in the intended destination. One entry names a file docs; another names docs/manual.pdf. The second needs docs to be a directory. Checking each string independently misses the contradiction.

Commercial disclosure: UNITED UAV sells the UD50 delivery aircraft. Its current product listing supplies the aircraft context and photograph below. The scenario here is a hypothetical ground-side integration package containing technical documents and review files. It does not describe a native UD50 archive format or export feature.

UD50 delivery aircraft shown in the UNITED UAV product catalog

The deliverable is a pure Python review function for a complete list of decoded member names. It rejects unsupported spellings, case aliases, duplicate entries and file/directory conflicts before a separate extraction stage does any work. It neither opens an archive nor writes files, and a passing result is deliberately narrower than approval to extract an untrusted package.

Choose a naming contract for the receiving application

An archive records member names, while the receiving environment interprets paths. Those are different boundaries. A name that an archive reader accepts can still be outside the application's intended directory structure or collide with another name under the chosen destination rules.

For this example, the receiving application defines a conservative ASCII profile. It uses relative forward-slash paths, preserves one spelling for every path prefix and treats case variants as conflicting names. The function does not inspect the operating system on which it runs. Review behavior therefore comes from the declared profile rather than an accidental property of the developer's laptop.

This is an application contract, not a claim that all other filenames are invalid. A project that needs internationalized filenames should establish a different reviewed profile with explicit normalization and collision semantics. Silently converting the current profile into a general Unicode validator would require decisions this example has not made.

The input boundary also matters. The names must be the unmodified decoded names supplied by a reviewed archive adapter. A value that has already been truncated, cleaned or renamed cannot reveal the evidence that was removed. Preserve the original package and the adapter's decoding context independently of this name review.

Make the component rules small enough to explain

The profile permits letters, digits and underscore at the start of each component, followed by letters, digits, underscore, period or hyphen. Each component is at most sixty-four characters. Empty components, leading periods, trailing periods and spaces are outside this profile. An optional final slash denotes a directory entry.

The whole member name is limited to two hundred forty characters, the path to eight components and the batch to two hundred fifty-six entries. These are example workload and interchange limits. They are not Windows path-length guarantees, ZIP-format limits or aircraft specifications.

Microsoft's naming documentation describes case considerations, reserved device names and trailing-character restrictions. The example rejects the listed ASCII device stems such as CON and numbered COM/LPT names, including when followed by an extension. Its narrower ASCII grammar also excludes the non-ASCII spellings outside this profile.

Backslash and colon are rejected instead of being converted into another separator or prefix. Leading slash and repeated slash produce unsupported empty components. Parent-directory references do not pass the component grammar. Rejecting these spellings keeps review focused on the supplied name rather than a repaired substitute.

Review every prefix, including directories that are not listed

A member docs/manual.pdf creates two namespace requirements: docs must be a directory, and docs/manual.pdf must be a file under the profile's trailing-slash convention. The archive does not need to contain an explicit docs/ entry for that first requirement to exist.

The review function records those implicit directories as it examines the batch. If another entry later names docs as a file, the required kinds disagree. Reversing the entries produces the same rejection: a file already occupying docs cannot also become a parent directory.

An explicit docs/ entry may appear before or after docs/manual.pdf. Both orders are accepted because the directory requirement is consistent. However, repeating the explicit docs/ entry is rejected as a duplicate member. The implementation therefore keeps explicit entries separate from inferred parent nodes.

Case handling applies to every prefix. The pair docs/a.txt and DOCS/b.txt contains different leaf names, but their parent spellings conflict under the declared namespace. Checking only complete filenames would miss that alias.

These rules explain why a complete batch review is useful. A per-entry predicate can check a component grammar, but it cannot decide whether another entry has already required an incompatible role or spelling for the same logical path.

Implement the batch review without filesystem side effects

The implementation maintains a map from lowercase path prefixes to their original spelling and required kind. A separate set records which logical paths appeared as explicit members. It returns an immutable tuple containing the original accepted names; it does not return renamed paths.

If any condition fails, the function raises ValueError and returns no partial review result. The mutable map is local to the call. No directories have been created and no member content has been decompressed by this function.

Paste the following block into a Python file. Its final assertion checks a small document-package example with an explicit directory and two files.

import re

COMPONENT = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}")
RESERVED = {"CON", "PRN", "AUX", "NUL"}
RESERVED |= {"COM%d" % n for n in range(1, 10)}
RESERVED |= {"LPT%d" % n for n in range(1, 10)}


def parse_name(name):
    if type(name) is not str or not 1 <= len(name) <= 240:
        raise ValueError("invalid member name type or length")
    if "\\" in name:
        raise ValueError("backslash is outside this naming profile")
    directory = name.endswith("/")
    path = name[:-1] if directory else name
    parts = path.split("/")
    if not 1 <= len(parts) <= 8:
        raise ValueError("too many path components")
    for part in parts:
        if not COMPONENT.fullmatch(part) or part.endswith("."):
            raise ValueError("unsupported path component")
        if part.split(".", 1)[0].upper() in RESERVED:
            raise ValueError("reserved component stem")
    return parts, directory


def review_names(names):
    if not isinstance(names, (list, tuple)) or len(names) > 256:
        raise ValueError("expected at most 256 member names")
    names = tuple(names)
    nodes = {}
    explicit = set()
    for name in names:
        parts, directory = parse_name(name)
        for length in range(1, len(parts) + 1):
            spelling = "/".join(parts[:length])
            key = spelling.lower()
            leaf = length == len(parts)
            kind = "directory" if not leaf or directory else "file"
            previous = nodes.get(key)
            if previous is not None:
                if previous[0] != spelling:
                    raise ValueError("case alias in namespace")
                if previous[1] != kind:
                    raise ValueError("file/directory conflict")
            if leaf:
                if key in explicit:
                    raise ValueError("duplicate explicit member")
                explicit.add(key)
            nodes[key] = (spelling, kind)
    return names


example = ["docs/", "docs/manual.pdf", "manifest.json"]
assert review_names(example) == tuple(example)

Keep duplicate detection separate from case matching

Two identical member names are still two entries. Converting the input list into a set before review would erase that evidence and could make the outcome depend on which duplicate a later reader selects. Preserve the ordered member list until the duplicate check has been completed.

The lowercase key serves only for conflict detection. It is not a proposed output path. If Report.pdf and report.pdf occur together, the function rejects the batch instead of choosing one spelling. Both original member references should remain available in the review report.

The same distinction applies to directory prefixes. A shared docs prefix is normal when several files belong to that directory. A shared lowercase prefix with inconsistent original spellings is rejected by this profile. Explicitness determines whether an otherwise consistent repeated node represents a duplicate entry or an ordinary shared parent.

A file/directory conflict is another independent reason to reject. Even exact spelling does not make docs and docs/ compatible. The profile requires one logical path to have one role.

The first reported failure may depend on entry order when a batch contains several problems. The property tested here is that acceptance or rejection stays consistent, not that every permutation reports the same first diagnostic message.

Reject unsupported names rather than laundering them

A cleanup step can make a rejected name appear acceptable while changing its meaning. Removing parent components, replacing punctuation or trimming trailing characters may also make two distinct entries collapse onto the same resulting path.

For this review stage, an unsupported name remains a failed input. Do not repair it inside the validator and then attach the old approval to the changed result. If the producer issues a corrected package, review that package as a new artifact and retain the previous failure evidence.

The Python ZIP documentation calls for inspecting untrusted archives and documents normalization behavior in extraction APIs. That is a reason to understand the chosen API, not evidence that an application-specific namespace review has already happened.

In particular, test the adapter's handling of original names. A decoder or helper that silently loses characters before this function runs has changed the evidence boundary. The function cannot reconstruct an original name from a cleaned string.

The published tests supply strings directly so that rejected NUL, separator and character cases actually reach the reviewer. They are not a demonstration that any particular ZIP parser preserves every malformed archive field unchanged.

Test the namespace using a different representation

The reference function builds one mutable node map. An independent test can instead flatten the namespace requirements of every generated member and compare those requirements pairwise. Requirements for the same lowercase prefix must agree in spelling and kind, and two explicit members must not occupy that prefix.

That oracle has a different control structure and no incremental node updates. It is deliberately inefficient, but the synthetic batches are small. Agreement with it provides more useful evidence than a second function that repeats the implementation's dictionary logic.

The generated population uses the components a, A and b, paths one or two components deep, and both file and directory forms. This produces twenty-four candidate names. Enumerating every ordered batch of zero through three entries yields fourteen thousand four hundred twenty-five cases.

The explicit checks separately exercise names outside that generated grammar, length and depth limits, reserved stems, unsupported types, hierarchy conflicts and result preservation. Append the following block to the first and run the combined file. It uses only the standard library.

import json
from itertools import combinations, product


def accepted(names):
    try:
        review_names(names)
    except ValueError:
        return False
    return True


def pairwise_oracle(names):
    # Generated test names already satisfy the individual component grammar.
    requirements = []
    for name in names:
        directory = name.endswith("/")
        parts = (name[:-1] if directory else name).split("/")
        for length in range(1, len(parts) + 1):
            spelling = "/".join(parts[:length])
            leaf = length == len(parts)
            kind = "directory" if directory or not leaf else "file"
            requirements.append((spelling.lower(), spelling, kind, leaf))
    for left, right in combinations(requirements, 2):
        if left[0] == right[0]:
            if left[1:3] != right[1:3] or (left[3] and right[3]):
                return False
    return True


explicit_checks = 0


def check(condition):
    global explicit_checks
    assert condition
    explicit_checks += 1


for names in [
    [], ["docs/manual.pdf"], ["docs/", "docs/manual.pdf"],
    ["docs/manual.pdf", "docs/"], ["a/b", "a/c"],
    ["_manifest.json"], ["a" * 64],
    ["/".join(["a" * 29] * 8) + "/"],
]:
    check(accepted(names))

for names in [
    [""], ["/manual.pdf"], ["//server/a"], ["C:/a"],
    [r"docs\manual.pdf"], ["../a"], ["a/../b"], ["./a"],
    ["a//b"], ["a//"], ["/"], ["a/./b"],
    ["a."], ["a "], ["a:name"], ["a?b"], ["a*b"],
    ["a\x00b"], ["cafΓ©.pdf"], ["a%2fb"], ["CON"],
    ["nul.txt"], ["COM9.log"], ["lpt1/report.txt"],
    ["a" * 65], ["/".join(["a"] * 9)],
    ["/".join(["a" * 29] * 7 + ["a" * 30]) + "/"],
    [None], [b"manual.pdf"], [True],
    ["a", "a"], ["a/", "a/"], ["docs", "docs/a"],
    ["docs/a", "docs"], ["docs", "docs/"],
    ["Report.pdf", "report.pdf"], ["docs/a", "DOCS/b"],
    ["docs/a", "docs/a/"], ["a"] * 257,
]:
    check(not accepted(names))
check(not accepted("a"))
check(not accepted(iter(["a"])))

names = ["docs/a", "docs/b", "manifest.json"]
check(accepted(names) == accepted(list(reversed(names))))
check(review_names(names) == tuple(names))
copy_result = review_names(names)
names.append("new.txt")
check(copy_result == ("docs/a", "docs/b", "manifest.json"))

components = ("a", "A", "b")
candidates = []
for depth in (1, 2):
    for parts in product(components, repeat=depth):
        path = "/".join(parts)
        candidates.extend((path, path + "/"))

cases = accepted_cases = 0
for size in range(4):
    for names in product(candidates, repeat=size):
        observed = accepted(names)
        assert observed == pairwise_oracle(names)
        cases += 1
        accepted_cases += observed

print(json.dumps({
    "explicit_boundary_invalid_and_invariant_checks": explicit_checks,
    "independent_pairwise_namespace_cases": cases,
    "accepted_in_exhaustive_population": accepted_cases,
    "worked_example_assertions": 1,
}))

Interpret the results within their stated population

The complete published code passed on Python 3.9.6. The pairwise oracle agreed on all fourteen thousand four hundred twenty-five generated batches. Three thousand one hundred ninety-seven of those batches were accepted under the profile. The remainder were rejected for namespace contradictions.

Fifty-two explicit checks cover selected valid inputs, rejected individual names, duplicate and prefix conflicts, ordering behavior, collection limits and preservation of the returned tuple. The worked document-package example adds another assertion.

Those numbers describe executed synthetic inputs. They are not a claim that every ZIP encoding, destination filesystem or malformed archive structure has been tested. The pairwise oracle assumes its generated individual components are valid; it checks the namespace relations. The separate explicit cases exercise the individual-name boundary.

The implementation tracks at most eight prefixes per member under the declared depth cap. That makes this review stage bounded by the profile, but it says nothing about the cost of reading an actual archive directory or decompressing its contents.

Keep the test population with the source revision when integrating the helper. If the grammar or collision policy changes, update the expected contract and review the affected cases instead of merely increasing a test count.

Bind a review to the exact archive inventory

The surrounding application should identify the package artifact and the exact member inventory that was reviewed. A later extraction stage needs to operate on the same artifact and interpretation, rather than reopening a mutable path and assuming it still contains the earlier package.

Retain the original member position or other unambiguous entry reference alongside its name. Names alone are insufficient identifiers when the failure itself involves duplicate entries. A report that says only β€œmanual.pdf was rejected” may leave the receiving team unable to identify which source entry caused the conflict.

The adapter also needs a documented decoding policy and agreement about directory/type metadata. This helper interprets a trailing slash as the naming profile's directory form; it does not verify the archive's external attributes or prove that a member is an ordinary file.

Record the profile revision with the result. A package accepted by a later, broader naming profile should not inherit an earlier review silently. The application can compare the inventories and explain which rule changed.

For the hypothetical UD50 handoff, these records organize a developer's document-import decision. They do not establish that the files are manufacturer-issued, applicable to a particular aircraft configuration or approved for operational use.

Treat content and extraction controls as separate decisions

A passing namespace contains no detected conflict under this profile. It does not establish that extracting the package is appropriate. The code has not checked member content, encryption, compression methods, declared sizes, actual decompressed output or nested archives.

It also has not checked links or special file types. A real extraction design must establish which member types it accepts and how it handles the destination environment. Existing filesystem objects and changes made by another process can invalidate assumptions that a name-only review cannot observe.

Apply suitable input and output resource limits in the actual archive-processing stage. A bounded list of short names is not a decompression budget. Reading an archive directory may itself require controls before its entries can be handed to this function.

Likewise, do not treat an empty, newly allocated destination name as a proof of containment or race resistance. The selected extraction implementation and filesystem operations need their own reviewed design.

These are distinct engineering responsibilities. Keeping them separate allows the name-review function to make a useful, testable claim without presenting a short regular expression and namespace map as a complete archive-security solution.

Preserve useful failure evidence for the sender

A rejected package should produce a review result that identifies the profile, original entry reference, relevant name or names and failed rule. Escape control characters in diagnostic displays so that a rejected field does not become an instruction to a terminal or an ambiguous line in a report.

For a prefix conflict, include the parent requirement as well as the leaf. A sender can then see why docs/a.txt conflicts with an existing file called docs, even though the two complete strings differ. For a case alias, show both preserved spellings rather than only the lowercase comparison key.

Keep the original package available under the application's retention rules. The receiving tool should not rename files in place and send that altered package back as if it were the producer's original submission.

A corrected handoff can use the same agreed naming profile and a new artifact identity. Rerunning the same pure review against that new inventory gives the sender a concrete acceptance result for the namespace, while content approval and extraction remain separately recorded decisions.

No actual customer package is included in this article. All names and conflicts are authored examples, so the discussion does not disclose a client's documents or imply that a supplied UD50 package contained these defects.

Make the boundary visible in the integration interface

An upload interface can label the outcome β€œmember-name review passed” and identify the naming-profile revision. That communicates the stage actually completed. Calling the same result β€œarchive approved” would imply decisions about content, provenance and extraction that the function never made.

For rejected input, provide enough context for a producer to correct the source package. Avoid offering automatic renaming as a default response to a namespace conflict. The sender may need to decide which document is authoritative or how the intended directory structure should be represented.

The practical result is a small reusable boundary between an archive adapter and subsequent processing: a complete batch of preserved names has either satisfied a declared namespace contract or produced a reviewable failure. That is useful ground-side tooling for technical-document exchange associated with delivery-aircraft projects such as UD50.

AI assisted drafting and code review. The frozen implementation was executed against the explicit checks and independent synthetic population described above. No archive was extracted, no UD50 device interface was exercised, and no hardware, flight or document-authenticity test was performed for this article.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.