Skip to content

Add LCP encryption/decryption implementation - #342

Merged
chocolatkey merged 2 commits into
developfrom
feat/lcp-implementation
Nov 25, 2026
Merged

chocolatkey merged 2 commits into
developfrom
feat/lcp-implementation

Conversation

@chocolatkey

@chocolatkey chocolatkey commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

LCP encryption/decryption implementation (based on the existing Go code), and a lot of other minor hardening-adjacent changes in the toolkit. What follows is an AI-generated changelog:


Added

  • New protection/lcp package with the content-level building blocks of Readium LCP: encrypting and decrypting publication resources with a content key (AES-256-CBC, interoperable with readium-lcp-server's lcpencrypt and LCP reading systems), derived from readium-lcp-server and rewritten to stream resources
    • EncryptEPUB/DecryptEPUB and EncryptRWP/DecryptRWP protect or unprotect an EPUB or a Readium Web Publication package in place, copying everything else byte for byte. They read the declarations of the package from its encryption.xml or raw manifest, including links without a media type, which the parsed manifest drops, and merge every declaration of a resource before selecting the LCP-encrypted ones, so that a resource declared both LCP-encrypted and otherwise is an error. Options.Encrypt is asked about each resource once, and its answer is what both the checks and the writing use. Decryption refuses packages declaring remote resources LCP-encrypted, which it can't decrypt, rather than deliver their ciphertext without the license, and so does encryption for remote resources already protected. Every local resource declared LCP-encrypted must be an entry the decryption decrypts: one missing, e.g. named differently on a case-insensitive file system, is an error rather than left encrypted without its declaration. So is a resource declared with the LCP scheme but an algorithm other than AES-256-CBC, everywhere, and a resource selected for encryption at the path of an LCP license, which isn't carried over. Decrypted publications don't serve their license, even through a URL template, so that packagers don't write it in the clear publication, with the identifier and passphrase hint of its recipient, and encrypted publications don't include one either. Other names of the file of a license, such as hard links, or another spelling on a case-insensitive file system, are an error in every remux, injection and EncryptPublication, rather than carried over, and decrypted publications don't serve them. The files checked are the ones read: every remux, injection, encrypted and decrypted publication reads a file pinned to the one checked, so that a file replaced meanwhile, e.g. by the license, fails to be read, and a file which can't be identified isn't read. Resources read over HTTP are compared by the URL they are read from, so that another spelling of the license's URL, such as a root-absolute or network-path reference, isn't served either. DecryptPublication refuses remote resources declared LCP-encrypted, which a packager would leave encrypted. EncryptEPUB leaves the package documents of every rendition in the clear, and the resources any rendition presents as its cover or navigation document. The streamer takes a Readium Web Publication package whose only LCP-encrypted resources are remote for a protected one, and decrypts remote resources requested by their href alone, whatever their fragment, including those only the raw manifest or encryption.xml declares, whose declarations are merged before the LCP-encrypted ones are selected, as for the resources of the package. Font obfuscation declared with the LCP scheme, as older producers did, is taken for font obfuscation. The remuxes require the asset's files to be listed exhaustively (fetcher.Exhaustive), rather than leave out those a fetcher can't list. EncryptPublication serializes its reads of Options.Random, as the resources of the publication it returns may be fetched concurrently, and keeps a copy of the content key, as NewDecryptor does, so that the caller may clear its own
    • EncryptPublication/DecryptPublication (and DecryptBuilder for streamer.Config.OnCreatePublication) encrypt or decrypt a parsed publication, to be written by a packager such as packager/epub. As in the remuxes, a resource several links point to is encrypted and compressed as the first of them says (Options.Encrypt, Options.Compress), and every link to it declares the same encryption
    • Decryptor is a resource transformer serving decrypted resources, with efficient random access to those that weren't compressed before encryption
    • EncryptContent/DecryptContent and lower-level streaming primitives
    • License models an LCP License Document (ParseLicense, and ReadLicense, which reads the license of a package given as an asset, telling its format as the streamer does), whose fields are decoded from the canonical form its signature covers. Its encryption profile is a Profile, the basic one or a production one (1.0, and 2.0 to 2.9): licenses of other profiles are refused with ErrUnknownProfile. It is unlocked with a user key (UserKeyFromHex) or, for the basic profile, a passphrase (ContentKeyFromPassphrase, which returns ErrUnsupportedProfile for production profiles), and validated with VerifySignature (provider certificate chain, and RSA, ECDSA or Ed25519 signature over the canonical form of the specification, or the one readium-lcp-server produces) and CheckRights, or all at once with a Verifier, which checks the revocation of provider certificates as well. Provider certificates whose key usage doesn't allow signatures are refused, e.g. against certificate revocation lists with RevokedBy, which reports ErrNoRevocationList rather than "not revoked" when none of its lists covers the issuer of a provider certificate. Issuers are identified by their key, from the verified certificate chain, rather than by name: a list only applies when the issuer signed it. Only the lists it fully processes apply, to revoke a certificate or to tell it isn't revoked: complete lists without critical extensions, rather than delta or scoped lists, as RFC 5280 requires. The lists are copied, so that refreshing them afterwards doesn't affect the function. Verifier.StrictProfile requires licenses to declare the algorithms of their encryption profile, as the LCP specification does (RSA with SHA-256 signatures for the Basic profile). The signature of a parsed license must be the one of its document, which is what InjectLicense delivers, rather than one attached afterwards. Decoding a license with encoding/json parses it as ParseLicense does, keeping the document its signature covers, and refuses null, rather than keeping a previously decoded license. Verifying or injecting a nil license is an error
    • ContentProtection opens LCP-protected publications in the streamer, given their user passphrase or user key. It requires a Verify function to validate licenses, or InsecureSkipVerify to explicitly skip their validation. It decrypts the resources the package declares LCP-encrypted, in its encryption.xml or raw manifest, as the remuxes do: the parsed manifest leaves out resources missing from the EPUB package document, and links without a media type. The format of the package is told once, by its META-INF/container.xml or manifest.json, for the license, the detection of the protection and the declarations, so that a file at the path of the other format's license is ignored. The format is the one the media type of the asset names, as the streamer parses it, or else the one its files tell, META-INF/container.xml taking precedence over manifest.json; InjectLicense applies the same rule, and EncryptRWP refuses packages holding a META-INF/container.xml, which would be taken for EPUBs
    • Publications are handled as untrusted input: a deflated resource can't be read into memory, whole or in part, beyond DefaultMaxInflatedLength (256 MiB, adjustable with ContentProtection.MaxInflatedLength), whatever length it declares, while streaming it isn't limited, and streamed ranges are never held in memory. Encryption fails rather than leave a resource in the clear, e.g. when font obfuscation is declared for a resource which is not a font, when a link of the reading order is a URL template expanding to paths of the package, or when a remote link such as //cdn.example.com/cover.jpg (a network-path reference, with a host but no scheme) shares its path with a resource of the package, which doesn't make it decrypted as that resource either. The same goes for encryption.xml entries of remote resources, absolute or network-path references, in the remuxes, InjectLicense, the streamer and the EPUB parser. The rewritten manifest of a Readium Web Publication package is compact, and can't exceed the size limit of manifests. Media overlays read by EncryptPublication are limited like the EPUB parser's documents. In exploded publications, the resources EncryptPublication serves, and the remux copies, in the clear are pinned to the files checked not to be encrypted ones, so that a file renamed or linked to their path afterwards isn't exposed. Encryption declared in the links of a Readium Web Publication manifest is handled like in its reading order and resources, and ranges of uncompressed resources can't exceed their declared original length either
    • InjectLicense embeds a license into a protected EPUB or Readium Web Publication package. A license the package already holds doesn't make it protected: some of its resources must be declared LCP-encrypted, each of them must be in the package, and have the size of the ciphertext of its content (exactly, for uncompressed resources declaring their original length). Licenses at the path of the other format are removed, as every remux does, and ReadLicense only reads the path of the format of the package. What is checked is what is written, even if the package changes meanwhile: the document declaring the encrypted resources, read raw and validated, is written as it was read, a resource declared several times must be declared consistently, including by declarations other than LCP's such as font obfuscation, decryption applying the same rule, and the declared resources are copied whole from the files checked, through temporary files bounded to their checked length for those which may change while they are copied (anything but the entries of a local archive, which must inflate to their declared length), so that the output never holds content which doesn't pass the checks. These checks catch mistakes, not untrusted packages: they can't tell a ciphertext from other content of its size
  • pub.ServiceHrefPrefix is the prefix of the HREFs served by publication services (~readium/), shared by the services, parsers and packagers
  • fetcher.ResourceError implements Unwrap, so that errors.Is and errors.As inspect its cause
  • fetcher.Stable reports whether a resource is read from a single version of its source, as the entries of local archives are (archive.StableEntry), unlike remote resources and files
  • fetcher.Located reports a resource’s source URL. fetcher.PinLocation returns the bound URL and an error if the resource reports a URL it cannot pin. HTTP resources implement fetcher.LocationPinner, and resource wrappers propagate pinning errors.
  • fetcher.Exhaustive is implemented by fetchers whose Links list every resource they serve, recursively: archives, directories, and S3 and GCS prefixes, but not remote HTTP folders
  • epub.GetPackageDocumentPaths returns the package documents of every rendition of an EPUB
  • epub.ResourceID returns the identifier of a resource in the encryption data of the EPUB parser, shared by the LCP remuxes: the decoded path of a resource of the container, or the URL of a remote one after a slash, so that the absolute URL file:font.otf and the file ./file:font.otf are distinct resources
  • url.URLFromPath creates a relative URL whose decoded path is exactly the given one, such as a file name holding %, ? or #, unlike url.URLFromDecodedPath, meant for hrefs written without percent-encoding, which keeps ? and # as delimiters. The EPUB packager uses it for the hrefs of the files it writes, which named another file when their name held # or ?
  • manifest.ParseLinkHREF parses the href of a link as LinkFromJSON does, including decoded paths such as filenames holding a literal %
  • fetcher.FilePinner pins resources read from a file, including through transformations, to the file they were checked to be: each read checks the file it opens, failing with fetcher.ErrFileChanged when their path names another one since. It is implemented by FileResource, whose File() is then empty, the resources of exploded archives (archive.PinnableEntry), and the toolkit's proxies. fetcher.ErrNotFileBacked is returned for resources not read from a file
  • fetcher.ReadResourceUpTo, fetcher.ReadResourceAsXMLUpTo and fetcher.ReadResourceAsJSONUpTo read a resource into memory without ever holding more than a given number of bytes, failing with fetcher.ErrResourceTooLarge beyond that, whatever length the resource declares
  • fetcher.FileBacked is implemented by resources read from a local file, including through transformations: its FileInfo identifies the file, e.g. to tell with os.SameFile whether two resources are the same file. archive.FileEntry does the same for the entries of exploded archives
  • streamer.Config.ContentProtections unlocks protected publications with the credentials given to Streamer.Open, through the new protection.ContentProtection interface
  • protection.MarshalEPUBEncryption serializes an EPUB META-INF/encryption.xml, the counterpart of the EPUB parser's ParseEncryption, along with exported constants for the LCP license paths and content key retrieval method. Compressions other than deflate, which encryption.xml can't declare, are an error rather than declared as stored, and so are documents larger than protection.MaxMetadataSize, which readers refuse
  • protection.MaxMetadataSize (32 MiB) limits the DRM metadata files read from EPUB containers, such as encryption.xml
  • manifest.MaxManifestSize, epub.MaxDocumentSize and mediatype.MaxDocumentSize (32 MiB each) limit the manifests and documents the parsers and the media type sniffer read into memory
  • protection.AlgorithmIDPFObfuscation, protection.AlgorithmAdobeObfuscation and protection.IsFontObfuscation identify font obfuscation, now shared by the EPUB parser and packager
  • manifest.Strings can be unmarshalled from either a single string or an array of strings, mirroring how it is marshalled
  • MediaType.IsPrecompressed() reports whether a media type is conventionally stored compressed (bitmap images, audio, video, ZIP-based formats)
  • MediaType.IsFont() reports whether a media type is a font's, including the legacy application/* font types such as application/vnd.ms-opentype

Changed

  • The EPUB parser merges the declarations of a resource listed several times in encryption.xml (protection.MergeEncryption), rather than taking the last one, which could drop the original length an earlier one declares: declarations which can't hold together are an error. epub.ParseEncryptionEntries returns all of them. Resources are identified by their decoded path in the container, as archives resolve them, so that hrefs spelled differently, such as chapter.xhtml and %63hapter.xhtml, are the same resource: epub.PublicationFactory.EncryptionData is keyed by decoded path
  • manifest.ManifestFromJSON returns an error for a nil object, such as the JSON document null, rather than a nil manifest without error
  • The EPUB parser now assigns the DRM scheme of encryption.xml entries individually, like the Kotlin and Swift toolkits: in an LCP-protected EPUB, only the entries whose key is retrieved from the license get the LCP scheme, and obfuscated fonts never carry a DRM scheme. Previously, every entry got the scheme detected for the whole container
  • The EPUB parser no longer declares the compression of resources stored without it (Method="0") as none, so it is left out of manifests, and keeps compression methods EPUB doesn't define (such as 93) instead of taking them for no compression. It also honors the compression method when the original length is missing or invalid, instead of ignoring both

Fixed

  • LCP publication reads retain the checked source link and bind HTTP requests to its URL through resource transformations. These reads reject redirects and keep a private copy of the checked URL. HTTP resources and remote ZIPs validate byte ranges before consuming the response.

  • LCP, S3 and GCS resources normalize negative range starts. File and archive streams handle ranges ending at the largest 64-bit offset.

  • Ranges with a negative end no longer make ZIP entries, exploded-archive files, FileResources, BytesResources and TransformingResources panic, and negative starts no longer misalign font deobfuscation: a negative start is the start of the resource, and an end before the start is "range not satisfiable". BytesResource.Stream clamps ranges ending beyond the resource, which panicked too

  • TransformingResource.Stream no longer returns an error (with no cause) when it succeeds

  • ArchiveFetcher and FileFetcher list file names as paths rather than encoded hrefs: page%20one.txt was listed as page one.txt, serving that file instead, a#b.txt as a, and a name such as 100%.png made the whole listing fail. Names which were listed correctly keep their href. ArchiveFetcher resolves the dot segments of hrefs, so that ./c:file.txt, the spelling of c:file.txt as a relative URL, is found

  • FileFetcher.Get no longer races with concurrent calls, and with Close

  • S3Fetcher.Links lists every object of the prefix rather than its first 1000, without empty links for folder placeholders, and GCSFetcher.Links lists the objects of subfolders too. Both list empty files, the objects of the root of a bucket, fail on object names which can't be paths of the package (such as images//cover.jpg) and beyond 100,000 objects rather than list some, list object names as paths rather than encoded hrefs, and no longer race or share their cached listing with callers

  • FileFetcher, ArchiveFetcher, S3Fetcher and GCSFetcher no longer serve the local resource at the path of a URL with a scheme or an authority, e.g. https://example.com/secret.txt

  • ArchiveFetcher.Links reports the failure of the walk of an exploded archive, e.g. an unreadable directory, rather than list the files found until then (archive.EntriesLister)

  • epub.GetRootFilePath reports why an invalid rootfile path can't be parsed, rather than "no error"

  • The EPUB parser no longer overflows the stack, which terminates the process, on media overlays referring back to their item, and bounds the alternates of a link, in nesting, and of the publication, in total: fallbacks and media overlays follow the same chain, a cycle stops it, and links sharing references no longer multiply them without bound

  • Exploded archives opened at . no longer misname their entries, or panic on one-character names

  • S3Asset and GCSAsset can be the root of a bucket, with or without a trailing slash (s3://bucket was the object .)

  • The Web Publication parser no longer panics on a manifest which is JSON null, and neither does Manifest.UnmarshalJSON, which leaves the manifest unchanged for null, as encoding/json does

  • The entries of a local ZIP archive are no longer streamed from another file than the one opened, e.g. once the archive was replaced, and entries shorter than they declare, e.g. in a truncated archive, are an error rather than reported complete. Whole entries are read to their end, so that an entry longer than it declares, or with a bad checksum, is an error too

  • Range reads of ZIP entries, exploded-archive files and FileResources no longer allocate the requested range before clamping it to the resource: a range ending far beyond a small resource could exhaust the memory, or panic

  • The detection of EPUB protections (protection.IdentifyEPUBProtection) and the EPUB parser no longer read DRM metadata files such as encryption.xml whole whatever their size: a package of a few hundred kilobytes made them allocate gigabytes. They fail beyond protection.MaxMetadataSize

  • The parsers and the media type sniffer no longer read the documents of a package whole whatever their size, which a small package could inflate a thousandfold: the Web Publication parser's manifest, the EPUB parser's container, package, navigation, display options and media overlay documents, the audio parser's playlists, and the archive entries and JSON content the sniffer decodes. Declared documents larger than their limit are an error, including the EPUB navigation document and display options, whose read errors are otherwise ignored, while oversized playlists, which the audio parser looks for among the files of the package, are skipped, and the sniffer doesn't recognize oversized content

  • LCP decryption refuses resources declaring a compression other than deflate (or none), which it used to serve still compressed, as if they were not

  • ZIP archives no longer allocate memory from the entry sizes they declare without checking them first: a few hundred bytes of crafted EPUB could require gigabytes of memory to be parsed. Declared sizes must fit in the archive (stored entries as large as their content, deflated entries within deflate's maximum ratio), whole entries are only allocated at once up to 64 MiB, and remote archives stream large entries instead of reading them whole first

  • FileFetcher and exploded archives no longer serve files outside of their directory through symbolic links: a symbolic link is only followed when it leads to a file of the same directory. They also skip named pipes and devices, which could block reads, and FileResource.File() is empty for files they don't serve

  • TransformingResource.File() and the EPUB font DeobfuscatingResource.File() no longer return the path of the untransformed file, which consumers serving the file directly would have sent instead of the transformed bytes


AI details: Used Opus 5.5 for much of the implementation, Astra 6.2 for security/hardening and generic reviews and some changes, Fable 5.2 for a final review/cleanup

and a lot of other minor hardening-adjacent changes in the toolkit
Comment thread pkg/protection/lcp/userkey.go Dismissed
@chocolatkey
chocolatkey marked this pull request as ready for review November 25, 2026 08:44
@chocolatkey
chocolatkey merged commit 8db1012 into develop Nov 25, 2026
4 checks passed
@chocolatkey
chocolatkey deleted the feat/lcp-implementation branch November 25, 2026 08:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants