Security hardening and release readiness
ober
759ef88f4b4c079c4e56147164449bc6eafa66e6
new file mode 100644 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,35 @@ +name: CI + +on: + push: + branches: [main, master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +env: + JERBOA_VERSION: v0.2.3 + JERBUILD: ${{ github.workspace }}/.jerboa/bin/jerbuild + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install system tools + run: | + set -eu + sudo apt-get update + sudo apt-get install -y --no-install-recommends build-essential curl ca-certificates + + - name: Install Jerboa toolchain + run: sh support/ensure-jerboa.sh "$JERBOA_VERSION" .jerboa/bin + + - name: Verify + run: make verify + + - name: Release evidence + run: make release-evidence new file mode 100644 --- /dev/null +++ b/.github/workflows/security-baseline.yml @@ -0,0 +1,35 @@ +name: Security Baseline + +on: + push: + branches: [main, master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + baseline: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Required release files + run: | + set -eu + test -f LICENSE + test -f SECURITY.md + test -f .gitignore + find . -maxdepth 1 -iname "README*" -type f | grep -q . + + - name: High-confidence secret scan + run: | + set -eu + pattern="(BEGIN (RSA|OPENSSH|EC|DSA|PRIVATE) KEY|ghp_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-(ant-api03|proj|svcacct)-[A-Za-z0-9_-]{30,}|AKIA[0-9A-Z]{16})" + matches="$(git grep -n -I -E "$pattern" -- . ":!*.png" ":!*.jpg" ":!*.jpeg" ":!*.gif" ":!*.so" ":!*.dylib" ":!*.o" ":!*.a" ":!*.boot" ":!*.tar.gz" || true)" + if [ -n "$matches" ]; then + echo "$matches" + echo "High-confidence secret pattern found." + exit 1 + fi --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,6 @@ *.wpo *.boot *.log +.jerboa/bin/ +dist/ tmp/ new file mode 100644 --- /dev/null +++ b/.jerboa/security.json @@ -0,0 +1,35 @@ +{ + "project": "jerboa-mail", + "status": "private-experimental", + "profile": "hostile-input-parser", + "runtime_capabilities": { + "filesystem": "none in parser library", + "network": "none", + "shell": "none", + "ffi": "none", + "credentials": "none" + }, + "caller_output_policy": { + "html": "hostile-text-only unless caller applies a reviewed sanitizer", + "urls": "caller-validated-before-linking", + "attachment_filenames": "caller-validated-before-use", + "logging": "body-redaction-required" + }, + "required_release_gates": [ + "make security", + "make test", + "make verify", + "make release-evidence" + ], + "default_parser_limits": { + "mail-max-message-chars": 26214400, + "mail-max-header-chars": 262144, + "mail-max-header-lines": 4096, + "mail-max-line-chars": 65536, + "mail-max-transfer-encoded-chars": 26214400, + "mail-max-encoded-word-chars": 65536, + "mail-max-mime-depth": 16, + "mail-max-mime-parts": 1024, + "mail-max-boundary-chars": 200 + } +} new file mode 100644 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. --- a/Makefile +++ b/Makefile @@ -1,24 +1,118 @@ +JERBOA_VERSION ?= v0.2.3 +JERBOA_TOOL_DIR ?= $(CURDIR)/.jerboa/bin +JERBUILD ?= $(if $(wildcard $(JERBOA_TOOL_DIR)/jerbuild),$(JERBOA_TOOL_DIR)/jerbuild,jerbuild) +JH := $(shell $(JERBUILD) --jerboa-home 2>/dev/null) +ifeq ($(JH),) JERBOA_HOME ?= $(realpath $(CURDIR)/../jerboa) +else +JERBOA_HOME ?= $(JH) +endif SCHEME ?= $(JERBOA_HOME)/.chez/bin/scheme LIBDIRS := $(CURDIR):$(JERBOA_HOME)/lib +DIST_DIR ?= dist/release-evidence +SBOM_DIR ?= dist/sbom +REPRO_DIR ?= dist/reproducibility -.PHONY: help test clean +.PHONY: help ensure-jerboa-tools test corpus-smoke fuzz-evidence security audit verify sbom reproducibility-report release-evidence clean .DEFAULT_GOAL := help help: @echo "jerboa-mail" @echo "" @echo "Development:" - @echo " make test Run smoke tests" - @echo " make clean Remove local generated files" + @echo " make ensure-jerboa-tools Install project-local Jerboa tools" + @echo " make test Run parser and resource-limit tests" + @echo " make corpus-smoke Run safe malformed-message corpus smoke" + @echo " make fuzz-evidence Run deterministic parser fuzz/property evidence" + @echo " make security Run local release security checks" + @echo " make verify Run security, tests, and dependency audit" + @echo " make sbom Write SBOM/provenance evidence" + @echo " make reproducibility-report" + @echo " Compare repeated local parser evidence" + @echo " make release-evidence Write release evidence under dist/" + @echo " make clean Remove local generated files" @echo "" @echo "Environment:" + @echo " JERBOA_VERSION = $(JERBOA_VERSION)" + @echo " JERBUILD = $(JERBUILD)" @echo " JERBOA_HOME = $(JERBOA_HOME)" @echo " SCHEME = $(SCHEME)" -test: - JERBOA_HOME=$(JERBOA_HOME) \ - $(SCHEME) -q --libdirs $(LIBDIRS) --script test/test-all.ss +ensure-jerboa-tools: + @if [ -x "$(JERBUILD)" ] && "$(JERBUILD)" --jerboa-home >/dev/null 2>&1; then \ + echo "Jerboa toolchain available: $(JERBUILD)"; \ + elif [ -x "$(SCHEME)" ]; then \ + echo "Using adjacent Jerboa checkout: $(JERBOA_HOME)"; \ + else \ + echo "=== Fetching Jerboa $(JERBOA_VERSION) release tools into $(JERBOA_TOOL_DIR) ==="; \ + sh support/ensure-jerboa.sh "$(JERBOA_VERSION)" "$(JERBOA_TOOL_DIR)"; \ + fi + +test: ensure-jerboa-tools + @jh="$$("$(JERBUILD)" --jerboa-home 2>/dev/null || true)"; \ + if [ -n "$$jh" ]; then \ + libdirs="$(CURDIR):$$jh/lib"; \ + JERBOA_HOME="$$jh" "$(JERBUILD)" exec --libdirs "$$libdirs" test/test-all.ss; \ + else \ + JERBOA_HOME="$(JERBOA_HOME)" "$(SCHEME)" -q --libdirs "$(LIBDIRS)" --script test/test-all.ss; \ + fi + +corpus-smoke: ensure-jerboa-tools + @jh="$$("$(JERBUILD)" --jerboa-home 2>/dev/null || true)"; \ + if [ -n "$$jh" ]; then \ + libdirs="$(CURDIR):$$jh/lib"; \ + JERBOA_HOME="$$jh" "$(JERBUILD)" exec --libdirs "$$libdirs" support/corpus-smoke.ss; \ + else \ + JERBOA_HOME="$(JERBOA_HOME)" "$(SCHEME)" -q --libdirs "$(LIBDIRS)" --script support/corpus-smoke.ss; \ + fi + +fuzz-evidence: ensure-jerboa-tools + @jh="$$("$(JERBUILD)" --jerboa-home 2>/dev/null || true)"; \ + if [ -n "$$jh" ]; then \ + libdirs="$(CURDIR):$$jh/lib"; \ + JERBOA_HOME="$$jh" "$(JERBUILD)" exec --libdirs "$$libdirs" support/fuzz-evidence.ss; \ + else \ + JERBOA_HOME="$(JERBOA_HOME)" "$(SCHEME)" -q --libdirs "$(LIBDIRS)" --script support/fuzz-evidence.ss; \ + fi + +security: + scripts/security-check.sh + +audit: + @echo "No native, Rust, or external package dependencies to audit." + +verify: security test corpus-smoke fuzz-evidence audit + +sbom: + JERBUILD="$(JERBUILD)" JERBOA_HOME="$(JERBOA_HOME)" JERBOA_MAIL_SBOM_DIR="$(SBOM_DIR)" scripts/sbom.sh + +reproducibility-report: + JERBUILD="$(JERBUILD)" JERBOA_HOME="$(JERBOA_HOME)" JERBOA_MAIL_REPRO_DIR="$(REPRO_DIR)" scripts/reproducibility-report.sh + +release-evidence: verify reproducibility-report sbom + rm -rf "$(DIST_DIR)" + mkdir -p "$(DIST_DIR)" + git rev-parse HEAD > "$(DIST_DIR)/git-commit.txt" + git status --short > "$(DIST_DIR)/git-status.txt" + uname -a > "$(DIST_DIR)/build-environment.txt" + @if [ -x "$(JERBUILD)" ]; then \ + "$(JERBUILD)" --version >> "$(DIST_DIR)/build-environment.txt" 2>/dev/null || true; \ + "$(JERBUILD)" --jerboa-home >> "$(DIST_DIR)/build-environment.txt" 2>/dev/null || true; \ + fi + @printf '%s\n' "jerboa-mail has no native/Rust/external package dependencies." > "$(DIST_DIR)/dependency-audit.txt" + shasum -a 256 Makefile .jerboa/security.json SECURITY.md docs/threat-model.md docs/parser-hardening.md docs/rendering-policy.md docs/release-evidence.md scripts/security-check.sh support/corpus-smoke.ss support/fuzz-evidence.ss > "$(DIST_DIR)/release-inputs-sha256.txt" + find jerboa-mail test -type f -name '*.ss' -print | sort | xargs shasum -a 256 > "$(DIST_DIR)/source-sha256.txt" + $(MAKE) corpus-smoke > "$(DIST_DIR)/corpus-smoke.txt" 2>&1 + $(MAKE) fuzz-evidence > "$(DIST_DIR)/fuzz-evidence.txt" 2>&1 + @{ \ + echo "rendering_policy_status=present"; \ + grep -E 'rendering_policy_status: documented|html_rendering_status: hostile-text-only|sanitizer_status: caller-required-before-html-rendering|url_policy_status: caller-validated-before-linking|attachment_filename_status: caller-validated-before-use|logging_status: body-redaction-required' docs/rendering-policy.md; \ + } > "$(DIST_DIR)/rendering-policy.txt" + grep -q 'rendering_policy_status: documented' "$(DIST_DIR)/rendering-policy.txt" + grep -q 'html_rendering_status: hostile-text-only' "$(DIST_DIR)/rendering-policy.txt" + grep -q 'sanitizer_status: caller-required-before-html-rendering' "$(DIST_DIR)/rendering-policy.txt" + cp -R "$(SBOM_DIR)" "$(DIST_DIR)/sbom" + cp -R "$(REPRO_DIR)" "$(DIST_DIR)/reproducibility" clean: - rm -rf tmp + rm -rf tmp dist --- a/README.md +++ b/README.md @@ -14,8 +14,40 @@ The initial scope is read-oriented: Sending helpers can be added later, but this first version is intentionally small and fixture-driven. +## Security posture + +`jerboa-mail` parses hostile mail input and remains private/experimental until +the release gates in `SECURITY.md`, `docs/threat-model.md`, and +`docs/release-evidence.md` are complete. + +The parser library is capability-free by design: it does not open files, call +the shell, use the network, load dynamic libraries, use FFI, or handle +credentials. The local security gate enforces that parser and test source keep +that shape. + +Default parser limits are exported as parameters for callers that need tighter +deployment budgets: + +Decoded HTML and MIME metadata are still hostile data. Callers that display +mail must follow `docs/rendering-policy.md`; this library does not sanitize HTML +or make body text safe for browser rendering. + +- `mail-max-message-chars`: 25 MiB. +- `mail-max-header-chars`: 256 KiB. +- `mail-max-header-lines`: 4096. +- `mail-max-line-chars`: 64 KiB. +- `mail-max-transfer-encoded-chars`: 25 MiB. +- `mail-max-encoded-word-chars`: 64 KiB. +- `mail-max-mime-depth`: 16. +- `mail-max-mime-parts`: 1024. +- `mail-max-boundary-chars`: 200. + ## Development ```sh make test +make corpus-smoke +make fuzz-evidence +make verify +make release-evidence ``` new file mode 100644 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,39 @@ +# Security Policy + +`jerboa-mail` is a hostile-input parser library for mail headers, common +content-transfer encodings, and simple MIME trees. It remains +private/experimental until the parser release gates are complete. + +## Supported Status + +No public production-support commitment exists yet. Security-sensitive releases +must be cut from a clean checkout after: + +- `make security` +- `make test` +- `make verify` +- `make release-evidence` + +## Hardening Expectations + +- The parser threat model is tracked in `docs/threat-model.md`. +- Parser limits and caller guidance are tracked in `docs/parser-hardening.md`. +- Caller-specific display and HTML handling policy is tracked in + `docs/rendering-policy.md`. +- Parser and test source must not import `(chezscheme)` directly. +- Parser and test source must remain free of shell/process execution, + filesystem sinks, network access, FFI, and dynamic-library loading. +- Oversized messages, headers, lines, encoded payloads, MIME part counts, MIME + nesting, and invalid boundaries must fail closed. +- Parsed HTML, subjects, display names, attachment names, and body text remain + hostile strings for downstream renderers and indexers. +- This library never makes decoded HTML safe for browser rendering. Callers + must render it as inert text or apply a reviewed sanitizer for their own UI. +- Do not log message bodies, private addresses, operational paths, credentials, + or parser payloads from inside this library. + +## Reporting + +Before public release, report issues privately to the repository owner. After a +public release, add a dedicated advisory contact, supported versions, and +disclosure window here. new file mode 100644 --- /dev/null +++ b/corpus/mail/accept/folded-header.eml @@ -0,0 +1,6 @@ +From: Alice Example <alice@example.invalid> +Subject: This header + continues on the next line +Content-Type: text/plain + +Folded header body. new file mode 100644 --- /dev/null +++ b/corpus/mail/accept/multipart-alternative.eml @@ -0,0 +1,13 @@ +From: Alice Example <alice@example.invalid> +Subject: Multipart +Content-Type: multipart/alternative; boundary="safe-boundary" + +--safe-boundary +Content-Type: text/plain + +Plain body. +--safe-boundary +Content-Type: text/html + +<p>HTML body.</p> +--safe-boundary-- new file mode 100644 --- /dev/null +++ b/corpus/mail/accept/simple.eml @@ -0,0 +1,6 @@ +From: Alice Example <alice@example.invalid> +To: Bob Example <bob@example.invalid> +Subject: Plain message +Content-Type: text/plain; charset=utf-8 + +Hello from the safe public corpus. new file mode 100644 --- /dev/null +++ b/corpus/mail/reject/empty-boundary.eml @@ -0,0 +1,8 @@ +From: Alice Example <alice@example.invalid> +Subject: Empty boundary +Content-Type: multipart/mixed; boundary="" + +--unused +Content-Type: text/plain + +This message must be rejected because the declared boundary is empty. new file mode 100644 --- /dev/null +++ b/docs/parser-hardening.md @@ -0,0 +1,57 @@ +# jerboa-mail Parser Hardening + +`jerboa-mail` is deliberately capability-free. The release gate requires parser +and test source to avoid direct Chez imports, shell/process primitives, +filesystem sinks, dynamic loading, and FFI. + +## Default Limits + +The parser exports these parameters so callers can tighten limits per +deployment: + +- `mail-max-message-chars`: 25 MiB. +- `mail-max-header-chars`: 256 KiB. +- `mail-max-header-lines`: 4096. +- `mail-max-line-chars`: 64 KiB. +- `mail-max-transfer-encoded-chars`: 25 MiB. +- `mail-max-encoded-word-chars`: 64 KiB. +- `mail-max-mime-depth`: 16. +- `mail-max-mime-parts`: 1024. +- `mail-max-boundary-chars`: 200. + +Set a parameter to `#f` only in controlled offline tooling that already applies +stronger outer resource controls. + +## Regression Coverage + +`make test` exercises: + +- Header/body splitting and unfolded headers. +- Base64, quoted-printable, and encoded-word decoding. +- Plain-text and multipart/alternative body selection. +- Over-limit message, header, header-line-count, line, transfer-payload, + encoded-word, MIME-part-count, MIME-depth, boundary-length, and empty-boundary + failures. + +`make fuzz-evidence` adds deterministic hostile-input property coverage: + +- `fuzz_property_status: documented` +- `fuzz_cases_minimum: 2048` +- `fuzz_scope_status: headers-transfer-multipart-limits` + +The harness generates 2048 stable cases across header parsing, encoded words, +content-transfer decoding, multipart boundaries and nesting, accepted-message +invariants, malformed input rejection, and parser limit policy. Conditions from +malformed mail are counted as rejections; accepted messages must keep headers, +bodies, content types, best-text output, and part lists structurally valid. + +## Caller Rules + +- Treat parsed HTML as text output from `mail-best-text-body`; do not render it + as trusted browser HTML. The required caller policy is in + `docs/rendering-policy.md`. +- Treat attachment filenames, address display names, and subjects as hostile + strings in downstream code. +- Keep message-body logging disabled by default in mail readers and daemons. +- Use process, queue, and memory limits around bulk importers that parse + untrusted mail archives. new file mode 100644 --- /dev/null +++ b/docs/release-evidence.md @@ -0,0 +1,41 @@ +# jerboa-mail Release Evidence + +`jerboa-mail` stays private until a release candidate has current evidence for +parser hardening, regression coverage, reproducibility, and external review. + +Run from a clean checkout: + +```sh +make clean +make release-evidence JERBUILD=/path/to/jerbuild +``` + +The `release-evidence` target runs `make verify` first, then writes untracked +artifacts under `dist/release-evidence/`: + +- `git-commit.txt` and `git-status.txt`. +- `build-environment.txt` with OS and Jerboa toolchain identity when available. +- `dependency-audit.txt` documenting the absence of native, Rust, or external + package dependencies. +- `release-inputs-sha256.txt` for the release gate, security profile, policy, + and hardening documentation. +- `source-sha256.txt` for parser and test source. +- `corpus-smoke.txt` with safe public malformed-message corpus results. +- `fuzz-evidence.txt` with deterministic hostile-input parser property results. +- `rendering-policy.txt` with required caller HTML/rendering policy markers. +- `sbom/` with source, corpus, release-input, and no-native-dependency + provenance. +- `reproducibility/` with two repeated local parser evidence passes and + `result.txt`. + +For a release candidate, archive those files with the exact Jerboa toolchain +used to run the tests. Reproducibility is claimed only when +`reproducibility/result.txt` records matching `source_status`, +`corpus_status`, `release_inputs_status`, `test_output_status`, +`corpus_smoke_status`, `fuzz_evidence_status`, and overall `status`. + +The external review packet must include this file, `SECURITY.md`, +`docs/threat-model.md`, `docs/parser-hardening.md`, +`docs/rendering-policy.md`, the safe malformed-message corpus under +`corpus/mail/`, `dist/release-evidence/fuzz-evidence.txt`, and any accepted +parser-limit or rendering risks. new file mode 100644 --- /dev/null +++ b/docs/rendering-policy.md @@ -0,0 +1,56 @@ +# jerboa-mail Rendering Policy + +`jerboa-mail` parses mail. It does not sanitize, render, trust, rewrite, or +store message content for user interfaces. Every caller that displays parser +output must choose a rendering policy for its own sink before treating decoded +headers, bodies, filenames, links, or MIME metadata as displayable content. + +Required release markers: + +- `rendering_policy_status: documented` +- `html_rendering_status: hostile-text-only` +- `sanitizer_status: caller-required-before-html-rendering` +- `url_policy_status: caller-validated-before-linking` +- `attachment_filename_status: caller-validated-before-use` +- `logging_status: body-redaction-required` + +## Parser Output + +The following values are hostile strings even after successful parsing: + +- HTML MIME bodies and any text returned by `mail-best-text-body`. +- Subjects, display names, addresses, and message IDs. +- Attachment filenames, MIME boundary strings, content descriptions, and media + type parameters. +- Links, image sources, forms, CSS, scripts, inline event handlers, and + `cid:` references found inside body text. + +The parser may decode transfer encodings and MIME structure, but decoding is +not validation. Parsed output must remain data until a caller escapes or +sanitizes it for a specific destination. + +## Caller Rules + +- Text UI and terminal callers must escape or strip control characters before + display. +- HTML/browser callers must either render parsed HTML as inert text or pass it + through a reviewed sanitizer that removes active content, remote loads, + unsafe URLs, forms, scripts, styles, event handlers, and dangerous attributes. +- Indexers must store raw and rendered text in separate fields so search output + cannot accidentally become trusted HTML. +- Mail daemons and background importers must not log message bodies or full + header values by default. Diagnostic logging must redact body text, private + addresses, and operational paths. +- Attachment filenames must be treated as labels only. Filesystem callers must + replace or validate names against their own path policy before writing files. +- URL extraction callers must reject unsupported schemes, local/private network + targets where applicable, userinfo, embedded credentials, and rewritten or + redirected destinations that do not pass the same policy. + +## Release Use + +Any `jerboa*` app that renders mail content must name its concrete rendering +sink and sanitizer/escaping policy in its own security docs. A library release +of `jerboa-mail` may ship with this policy as caller guidance, but an +application release cannot claim safe HTML rendering based on this parser +alone. new file mode 100644 --- /dev/null +++ b/docs/threat-model.md @@ -0,0 +1,75 @@ +# jerboa-mail Threat Model + +Status: private/experimental until the parser release gates in +`~/Release-plan.md` and `~/mine/jerboa-production-readiness.md` are complete. + +## Scope + +`jerboa-mail` is a pure Scheme library for RFC 5322 header/body splitting, +header unfolding, RFC 2047 encoded-word decoding, content-transfer decoding, +simple MIME tree construction, and best-effort text body selection. It does not +open files, make network connections, invoke shell commands, load dynamic +libraries, or store credentials. + +## Assets + +- Message bodies, headers, addresses, subjects, and attachment metadata passed + in by callers. +- Availability of mail readers, importers, indexers, and daemons that call the + parser on hostile mail. +- Parser configuration limits used by those callers. + +## Trust Boundaries + +- Raw message strings are hostile input. +- Header, MIME boundary, encoded-word, base64, and quoted-printable payloads + cross parser boundaries. +- Callers decide how parsed text is stored, logged, rendered, or indexed. + +## Threat Actors + +- Remote senders attempting parser crashes, CPU exhaustion, memory exhaustion, + pathological multipart nesting, unbounded header unfolding, oversized encoded + payloads, or malformed boundary handling. +- Local operators accidentally using parser output as trusted HTML, a trusted + filename, or a safe log string. + +## Security Objectives + +- Keep the parser capability-free: no shell, filesystem, network, credential, + or FFI access in parser/test source. +- Fail closed on over-limit messages, headers, lines, encoded payloads, MIME + part counts, MIME nesting, and boundary values. +- Treat decoded HTML as text only. This library does not sanitize HTML for + browser display. +- Do not log message contents, private addresses, deployment paths, or parser + payloads from inside the library. + +## Required Controls + +- `make verify` must pass before release. +- `scripts/security-check.sh` must remain clean for direct Chez imports, + shell/process primitives, filesystem sinks, generated artifacts, FFI, stale + license text, and high-confidence secrets. +- Regression tests must cover successful parsing and limit-triggering failure + paths for messages, headers, lines, transfer payloads, encoded-word headers, + MIME part counts, MIME nesting, and boundaries. +- `make fuzz-evidence` must pass with at least 512 deterministic hostile-input + cases covering headers, transfer encodings, multipart handling, encoded words, + structural invariants, malformed input rejection, and limit policy. +- Applications that accept arbitrary mail should lower the exported parser + limit parameters to match their queue and memory budgets. +- Applications that display mail must follow `docs/rendering-policy.md`; this + parser does not sanitize HTML or make decoded content safe for a browser. + +## Open Release Gates + +- Extend the safe public malformed-message corpus beyond the current smoke set. +- Keep deterministic fuzz/property evidence current, and add longer external + fuzzing before widening supported MIME features. +- Keep caller-specific rendering rules current before using parsed HTML in a + UI. +- Keep SBOM and repeated reproducibility evidence current for release bundles + that include this library. +- Replace private reporting instructions in `SECURITY.md` with a public + advisory contact before public release. --- a/jerboa-mail/encoding.ss +++ b/jerboa-mail/encoding.ss @@ -3,22 +3,37 @@ (library (jerboa-mail encoding) (export + mail-max-transfer-encoded-chars + mail-max-encoded-word-chars mail-base64-decode-string mail-quoted-printable-decode-string mail-transfer-decode-string mail-decode-encoded-words) - (import (except (chezscheme) - make-hash-table hash-table? - sort sort! - printf fprintf - path-extension path-absolute? - with-input-from-string with-output-to-string - iota 1+ 1- - partition - make-date make-time) + (import (scheme) (only (std text base64) base64-string->u8vector)) + (define mail-max-transfer-encoded-chars (make-parameter (* 25 1024 1024))) + (define mail-max-encoded-word-chars (make-parameter 65536)) + + (define (limit-value who param label) + (let ([limit (param)]) + (cond + [(not limit) #f] + [(and (integer? limit) (>= limit 0)) limit] + [else (error who + (string-append label " limit must be a nonnegative integer or #f") + limit)]))) + + (define (check-string-limit who label s param) + (let ([limit (limit-value who param label)] + [count (string-length s)]) + (when (and limit (> count limit)) + (error who + (string-append label " exceeds jerboa-mail parser limit") + count + limit)))) + (define (ascii-whitespace? ch) (or (char=? ch #\space) (char=? ch #\tab) @@ -36,6 +51,10 @@ (get-output-string out))) (define (mail-base64-decode-string s) + (check-string-limit 'mail-base64-decode-string + "base64 payload" + s + mail-max-transfer-encoded-chars) (utf8->string (base64-string->u8vector (strip-ascii-whitespace s)))) (define (hex-value ch) @@ -49,6 +68,10 @@ [else #f])) (define (mail-quoted-printable-decode-string s) + (check-string-limit 'mail-quoted-printable-decode-string + "quoted-printable payload" + s + mail-max-transfer-encoded-chars) (let ([out (open-output-string)]) (let loop ([i 0]) (cond @@ -139,6 +162,10 @@ (values #f start))) (define (mail-decode-encoded-words s) + (check-string-limit 'mail-decode-encoded-words + "encoded-word header" + s + mail-max-encoded-word-chars) (let ([out (open-output-string)]) (let loop ([i 0]) (cond --- a/jerboa-mail/header.ss +++ b/jerboa-mail/header.ss @@ -3,6 +3,10 @@ (library (jerboa-mail header) (export + mail-max-message-chars + mail-max-header-chars + mail-max-header-lines + mail-max-line-chars mail-split-header-body mail-headers-parse mail-header-ref @@ -10,15 +14,56 @@ mail-string-trim mail-split-lines) - (import (except (chezscheme) - make-hash-table hash-table? - sort sort! - printf fprintf - path-extension path-absolute? - with-input-from-string with-output-to-string - iota 1+ 1- - partition - make-date make-time)) + (import (scheme)) + + (define mail-max-message-chars (make-parameter (* 25 1024 1024))) + (define mail-max-header-chars (make-parameter (* 256 1024))) + (define mail-max-header-lines (make-parameter 4096)) + (define mail-max-line-chars (make-parameter 65536)) + + (define (mail-limit who label count limit) + (when (and limit (> count limit)) + (error who + (string-append label " exceeds jerboa-mail parser limit") + count + limit))) + + (define (limit-value who param label) + (let ([limit (param)]) + (cond + [(not limit) #f] + [(and (integer? limit) (>= limit 0)) limit] + [else (error who + (string-append label " limit must be a nonnegative integer or #f") + limit)]))) + + (define (check-message-size who s) + (mail-limit who + "message" + (string-length s) + (limit-value who mail-max-message-chars "message"))) + + (define (check-header-size who n) + (mail-limit who + "header" + n + (limit-value who mail-max-header-chars "header"))) + + (define (check-line-size who n) + (mail-limit who + "line" + n + (limit-value who mail-max-line-chars "line"))) + + (define (check-header-line-count who n) + (mail-limit who + "header line count" + n + (limit-value who mail-max-header-lines "header line count"))) + + (define (checked-substring-line who s start end) + (check-line-size who (- end start)) + (substring s start end)) (define (mail-string-trim s) (let* ([n (string-length s)] @@ -50,10 +95,10 @@ (let loop ([i 0] [start 0] [acc '()]) (cond [(= i (string-length s)) - (reverse (cons (trim-cr (substring s start i)) acc))] + (reverse (cons (trim-cr (checked-substring-line 'mail-split-lines s start i)) acc))] [(char=? (string-ref s i) #\newline) (loop (+ i 1) (+ i 1) - (cons (trim-cr (substring s start i)) acc))] + (cons (trim-cr (checked-substring-line 'mail-split-lines s start i)) acc))] [else (loop (+ i 1) start acc)]))) @@ -68,19 +113,24 @@ (char=? (string-ref s (+ i 1)) #\newline)))) (define (mail-split-header-body raw) + (check-message-size 'mail-split-header-body raw) (let loop ([i 0]) (cond - [(>= i (string-length raw)) (values raw "")] + [(>= i (string-length raw)) + (check-header-size 'mail-split-header-body (string-length raw)) + (values raw "")] [(and (< (+ i 3) (string-length raw)) (char=? (string-ref raw i) #\return) (char=? (string-ref raw (+ i 1)) #\newline) (char=? (string-ref raw (+ i 2)) #\return) (char=? (string-ref raw (+ i 3)) #\newline)) + (check-header-size 'mail-split-header-body i)