Repository navigation
Add LCP encryption/decryption implementation - #342
Merged
Merged
Conversation
and a lot of other minor hardening-adjacent changes in the toolkit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
protection/lcppackage 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'slcpencryptand LCP reading systems), derived from readium-lcp-server and rewritten to stream resourcesEncryptEPUB/DecryptEPUBandEncryptRWP/DecryptRWPprotect 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 itsencryption.xmlor 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.Encryptis 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 andEncryptPublication, 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.DecryptPublicationrefuses remote resources declared LCP-encrypted, which a packager would leave encrypted.EncryptEPUBleaves 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 orencryption.xmldeclares, 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.EncryptPublicationserializes its reads ofOptions.Random, as the resources of the publication it returns may be fetched concurrently, and keeps a copy of the content key, asNewDecryptordoes, so that the caller may clear its ownEncryptPublication/DecryptPublication(andDecryptBuilderforstreamer.Config.OnCreatePublication) encrypt or decrypt a parsed publication, to be written by a packager such aspackager/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 encryptionDecryptoris a resource transformer serving decrypted resources, with efficient random access to those that weren't compressed before encryptionEncryptContent/DecryptContentand lower-level streaming primitivesLicensemodels an LCP License Document (ParseLicense, andReadLicense, 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 aProfile, the basic one or a production one (1.0, and 2.0 to 2.9): licenses of other profiles are refused withErrUnknownProfile. It is unlocked with a user key (UserKeyFromHex) or, for the basic profile, a passphrase (ContentKeyFromPassphrase, which returnsErrUnsupportedProfilefor production profiles), and validated withVerifySignature(provider certificate chain, and RSA, ECDSA or Ed25519 signature over the canonical form of the specification, or the one readium-lcp-server produces) andCheckRights, or all at once with aVerifier, 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 withRevokedBy, which reportsErrNoRevocationListrather 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.StrictProfilerequires 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 whatInjectLicensedelivers, rather than one attached afterwards. Decoding a license withencoding/jsonparses it asParseLicensedoes, keeping the document its signature covers, and refusesnull, rather than keeping a previously decoded license. Verifying or injecting a nil license is an errorContentProtectionopens LCP-protected publications in the streamer, given their user passphrase or user key. It requires aVerifyfunction to validate licenses, orInsecureSkipVerifyto explicitly skip their validation. It decrypts the resources the package declares LCP-encrypted, in itsencryption.xmlor 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 itsMETA-INF/container.xmlormanifest.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.xmltaking precedence overmanifest.json;InjectLicenseapplies the same rule, andEncryptRWPrefuses packages holding aMETA-INF/container.xml, which would be taken for EPUBsDefaultMaxInflatedLength(256 MiB, adjustable withContentProtection.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 forencryption.xmlentries 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 byEncryptPublicationare limited like the EPUB parser's documents. In exploded publications, the resourcesEncryptPublicationserves, 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 thelinksof 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 eitherInjectLicenseembeds 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, andReadLicenseonly 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 sizepub.ServiceHrefPrefixis the prefix of the HREFs served by publication services (~readium/), shared by the services, parsers and packagersfetcher.ResourceErrorimplementsUnwrap, so thaterrors.Isanderrors.Asinspect its causefetcher.Stablereports 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 filesfetcher.Locatedreports a resource’s source URL.fetcher.PinLocationreturns the bound URL and an error if the resource reports a URL it cannot pin. HTTP resources implementfetcher.LocationPinner, and resource wrappers propagate pinning errors.fetcher.Exhaustiveis implemented by fetchers whoseLinkslist every resource they serve, recursively: archives, directories, and S3 and GCS prefixes, but not remote HTTP foldersepub.GetPackageDocumentPathsreturns the package documents of every rendition of an EPUBepub.ResourceIDreturns 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 URLfile:font.otfand the file./file:font.otfare distinct resourcesurl.URLFromPathcreates a relative URL whose decoded path is exactly the given one, such as a file name holding%,?or#, unlikeurl.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.ParseLinkHREFparses the href of a link asLinkFromJSONdoes, including decoded paths such as filenames holding a literal%fetcher.FilePinnerpins resources read from a file, including through transformations, to the file they were checked to be: each read checks the file it opens, failing withfetcher.ErrFileChangedwhen their path names another one since. It is implemented byFileResource, whoseFile()is then empty, the resources of exploded archives (archive.PinnableEntry), and the toolkit's proxies.fetcher.ErrNotFileBackedis returned for resources not read from a filefetcher.ReadResourceUpTo,fetcher.ReadResourceAsXMLUpToandfetcher.ReadResourceAsJSONUpToread a resource into memory without ever holding more than a given number of bytes, failing withfetcher.ErrResourceTooLargebeyond that, whatever length the resource declaresfetcher.FileBackedis implemented by resources read from a local file, including through transformations: itsFileInfoidentifies the file, e.g. to tell withos.SameFilewhether two resources are the same file.archive.FileEntrydoes the same for the entries of exploded archivesstreamer.Config.ContentProtectionsunlocks protected publications with the credentials given toStreamer.Open, through the newprotection.ContentProtectioninterfaceprotection.MarshalEPUBEncryptionserializes an EPUBMETA-INF/encryption.xml, the counterpart of the EPUB parser'sParseEncryption, along with exported constants for the LCP license paths and content key retrieval method. Compressions other thandeflate, whichencryption.xmlcan't declare, are an error rather than declared as stored, and so are documents larger thanprotection.MaxMetadataSize, which readers refuseprotection.MaxMetadataSize(32 MiB) limits the DRM metadata files read from EPUB containers, such asencryption.xmlmanifest.MaxManifestSize,epub.MaxDocumentSizeandmediatype.MaxDocumentSize(32 MiB each) limit the manifests and documents the parsers and the media type sniffer read into memoryprotection.AlgorithmIDPFObfuscation,protection.AlgorithmAdobeObfuscationandprotection.IsFontObfuscationidentify font obfuscation, now shared by the EPUB parser and packagermanifest.Stringscan be unmarshalled from either a single string or an array of strings, mirroring how it is marshalledMediaType.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 legacyapplication/*font types such asapplication/vnd.ms-opentypeChanged
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.ParseEncryptionEntriesreturns all of them. Resources are identified by their decoded path in the container, as archives resolve them, so that hrefs spelled differently, such aschapter.xhtmland%63hapter.xhtml, are the same resource:epub.PublicationFactory.EncryptionDatais keyed by decoded pathmanifest.ManifestFromJSONreturns an error for a nil object, such as the JSON documentnull, rather than a nil manifest without errorencryption.xmlentries 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 containerMethod="0") asnone, so it is left out of manifests, and keeps compression methods EPUB doesn't define (such as93) instead of taking them for no compression. It also honors the compression method when the original length is missing or invalid, instead of ignoring bothFixed
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 andTransformingResources 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.Streamclamps ranges ending beyond the resource, which panicked tooTransformingResource.Streamno longer returns an error (with no cause) when it succeedsArchiveFetcherandFileFetcherlist file names as paths rather than encoded hrefs:page%20one.txtwas listed aspage one.txt, serving that file instead,a#b.txtasa, and a name such as100%.pngmade the whole listing fail. Names which were listed correctly keep their href.ArchiveFetcherresolves the dot segments of hrefs, so that./c:file.txt, the spelling ofc:file.txtas a relative URL, is foundFileFetcher.Getno longer races with concurrent calls, and withCloseS3Fetcher.Linkslists every object of the prefix rather than its first 1000, without empty links for folder placeholders, andGCSFetcher.Linkslists 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 asimages//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 callersFileFetcher,ArchiveFetcher,S3FetcherandGCSFetcherno longer serve the local resource at the path of a URL with a scheme or an authority, e.g.https://example.com/secret.txtArchiveFetcher.Linksreports 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.GetRootFilePathreports 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 namesS3AssetandGCSAssetcan be the root of a bucket, with or without a trailing slash (s3://bucketwas the object.)The Web Publication parser no longer panics on a manifest which is JSON
null, and neither doesManifest.UnmarshalJSON, which leaves the manifest unchanged fornull, asencoding/jsondoesThe 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 panicThe detection of EPUB protections (
protection.IdentifyEPUBProtection) and the EPUB parser no longer read DRM metadata files such asencryption.xmlwhole whatever their size: a package of a few hundred kilobytes made them allocate gigabytes. They fail beyondprotection.MaxMetadataSizeThe 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(ornone), which it used to serve still compressed, as if they were notZIP 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
FileFetcherand 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, andFileResource.File()is empty for files they don't serveTransformingResource.File()and the EPUB fontDeobfuscatingResource.File()no longer return the path of the untransformed file, which consumers serving the file directly would have sent instead of the transformed bytesAI 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