Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

refactor(apk): consume shared BER node facts

morluto486111725e9e
diff --git a/src/domain/apkSignature/apkV1SignatureBlock.ts b/src/domain/apkSignature/apkV1SignatureBlock.ts
index c3a84edc3..7ab2a0e32 100644
--- a/src/domain/apkSignature/apkV1SignatureBlock.ts
+++ b/src/domain/apkSignature/apkV1SignatureBlock.ts
@@ -5,9 +5,9 @@
* certificates it identifies (by `issuerAndSerialNumber` or
* `subjectKeyIdentifier`) and its digest and signature algorithm OIDs.
*
- * This owns the DER structure only. Certificate facts (fingerprint, subject)
- * stay with the adapter's X.509 owner, and no signature is verified: a
- * `SignerInfo` naming a certificate is what the block declares.
+ * This owns the CMS BER structure only. Certificate facts (fingerprint,
+ * subject) stay with the adapter's X.509 owner, and no signature is verified:
+ * a `SignerInfo` naming a certificate is what the block declares.
*
* Dependency-free and bounded. Every tag and length is checked against its
* enclosing element; BER indefinite lengths (which some JAR signers emit) are
@@ -74,8 +74,6 @@ const TAG = {
context0Primitive: 0x80,
} as const;
-type Tlv = Asn1BerNode;
-
/** Expected failures inside one decode; converted to a Result at the boundary. */
class BlockFailure {
constructor(readonly error: ApkV1BlockError) {}
@@ -85,21 +83,16 @@ const malformed = (detail: string): BlockFailure =>
class ApkBerReader {
readonly #reader: Asn1BerReader;
- readonly #bytes: Buffer;
- constructor(readonly bytes: Uint8Array) {
- this.#bytes = Buffer.isBuffer(bytes)
+ constructor(bytes: Uint8Array) {
+ const buffer = Buffer.isBuffer(bytes)
? bytes
: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- this.#reader = new Asn1BerReader(
- this.#bytes,
- MAX_ASN1_ELEMENTS,
- MAX_ASN1_DEPTH,
- );
+ this.#reader = new Asn1BerReader(buffer, MAX_ASN1_ELEMENTS, MAX_ASN1_DEPTH);
}
/** One TLV starting at `at`, which must end at or before `limit`. */
- read(at: number, limit: number, depth: number): Tlv {
+ read(at: number, limit: number, depth: number): Asn1BerNode {
try {
return this.#reader.read(at, limit, depth);
} catch (cause: unknown) {
@@ -114,20 +107,16 @@ class ApkBerReader {
}
}
- children(parent: Tlv): Tlv[] {
- return [...parent.children];
- }
-
- content(tlv: Tlv): Uint8Array {
- return this.bytes.subarray(tlv.contentStart, tlv.contentEnd);
- }
-
- raw(tlv: Tlv): Uint8Array {
- return this.bytes.subarray(tlv.start, tlv.end);
+ rawEncodedSpan(tlv: Asn1BerNode): Uint8Array {
+ return this.#reader.bytes.subarray(tlv.start, tlv.end);
}
}
-const expectTag = (tlv: Tlv | undefined, tag: number, what: string): Tlv => {
+const expectTag = (
+ tlv: Asn1BerNode | undefined,
+ tag: number,
+ what: string,
+): Asn1BerNode => {
if (tlv === undefined) throw malformed(`${what} is missing`);
if (tlv.tag !== tag)
throw malformed(
@@ -137,14 +126,17 @@ const expectTag = (tlv: Tlv | undefined, tag: number, what: string): Tlv => {
};
/** BER permits an OCTET STRING to use constructed form with string fragments. */
-const expectOctetString = (tlv: Tlv | undefined, what: string): Tlv => {
+const expectOctetString = (
+ tlv: Asn1BerNode | undefined,
+ what: string,
+): Asn1BerNode => {
if (tlv === undefined) throw malformed(`${what} is missing`);
if (tlv.tag === TAG.octetString) return tlv;
if (tlv.tag !== 0x24)
throw malformed(
`${what} has tag 0x${tlv.tag.toString(16)}, expected 0x4 or 0x24`,
);
- const validateFragments = (node: Tlv): void => {
+ const validateFragments = (node: Asn1BerNode): void => {
for (const child of node.children) {
if (child.tag === TAG.octetString) continue;
if (child.tag === 0x24) validateFragments(child);
@@ -180,19 +172,13 @@ const oidText = (content: Uint8Array): string => {
return arcs.join(".");
};
-const algorithmOid = (
- reader: ApkBerReader,
- tlv: Tlv | undefined,
- what: string,
-) =>
+const algorithmOid = (tlv: Asn1BerNode | undefined, what: string) =>
oidText(
- reader.content(
- expectTag(
- reader.children(expectTag(tlv, TAG.sequence, what))[0],
- TAG.oid,
- `${what} algorithm`,
- ),
- ),
+ expectTag(
+ expectTag(tlv, TAG.sequence, what).children[0],
+ TAG.oid,
+ `${what} algorithm`,
+ ).content,
);
const equalBytes = (a: Uint8Array, b: Uint8Array): boolean =>
@@ -212,15 +198,15 @@ interface CertificateIdentity {
*/
const certificateIdentity = (
reader: ApkBerReader,
- certificate: Tlv,
+ certificate: Asn1BerNode,
): CertificateIdentity | null => {
try {
const tbs = expectTag(
- reader.children(certificate)[0],
+ certificate.children[0],
TAG.sequence,
"tbsCertificate",
);
- const fields = reader.children(tbs);
+ const fields = tbs.children;
const offset = fields[0]?.tag === TAG.context0 ? 1 : 0;
const serial = expectTag(fields[offset], TAG.integer, "serialNumber");
const issuer = expectTag(fields[offset + 2], TAG.sequence, "issuer");
@@ -228,25 +214,26 @@ const certificateIdentity = (
const extensions = fields.find((field) => field.tag === TAG.context3);
if (extensions !== undefined) {
const list = expectTag(
- reader.children(extensions)[0],
+ extensions.children[0],
TAG.sequence,
"extensions",
);
- for (const extension of reader.children(list)) {
- const parts = reader.children(extension);
+ for (const extension of list.children) {
+ const parts = extension.children;
const id = expectTag(parts[0], TAG.oid, "extension id");
- if (oidText(reader.content(id)) !== OID_SUBJECT_KEY_IDENTIFIER)
- continue;
+ if (oidText(id.content) !== OID_SUBJECT_KEY_IDENTIFIER) continue;
const value = expectTag(parts.at(-1), TAG.octetString, "extnValue");
const inner = reader.read(value.contentStart, value.contentEnd, 0);
- subjectKeyIdentifier = reader.content(
- expectTag(inner, TAG.octetString, "keyIdentifier"),
- );
+ subjectKeyIdentifier = expectTag(
+ inner,
+ TAG.octetString,
+ "keyIdentifier",
+ ).content;
}
}
return {
- issuer: reader.raw(issuer),
- serial: reader.content(serial),
+ issuer: reader.rawEncodedSpan(issuer),
+ serial: serial.content,
subjectKeyIdentifier,
};
} catch (cause: unknown) {
@@ -258,24 +245,26 @@ const certificateIdentity = (
const signerInfo = (
reader: ApkBerReader,
- tlv: Tlv,
+ tlv: Asn1BerNode,
identities: readonly (CertificateIdentity | null)[],
index: number,
): ApkV1SignerInfo => {
const what = `signerInfo ${String(index)}`;
- const fields = reader.children(expectTag(tlv, TAG.sequence, what));
+ const fields = expectTag(tlv, TAG.sequence, what).children;
expectTag(fields[0], TAG.integer, `${what} version`);
const sid = fields[1];
let identifiedBy: ApkV1SignerInfo["identifiedBy"];
let certificateIndex: number;
if (sid?.tag === TAG.sequence) {
- const parts = reader.children(sid);
- const issuer = reader.raw(
+ const parts = sid.children;
+ const issuer = reader.rawEncodedSpan(
expectTag(parts[0], TAG.sequence, `${what} issuer`),
);
- const serial = reader.content(
- expectTag(parts[1], TAG.integer, `${what} serialNumber`),
- );
+ const serial = expectTag(
+ parts[1],
+ TAG.integer,
+ `${what} serialNumber`,
+ ).content;
identifiedBy = "issuer-and-serial";
certificateIndex = identities.findIndex(
(identity) =>
@@ -284,7 +273,7 @@ const signerInfo = (
equalBytes(identity.serial, serial),
);
} else if (sid?.tag === TAG.context0Primitive) {
- const keyId = reader.content(sid);
+ const keyId = sid.content;
identifiedBy = "subject-key-identifier";
certificateIndex = identities.findIndex(
(identity) =>
@@ -292,15 +281,10 @@ const signerInfo = (
equalBytes(identity.subjectKeyIdentifier, keyId),
);
} else throw malformed(`${what} has no supported signer identifier`);
- const digestAlgorithmOid = algorithmOid(
- reader,
- fields[2],
- `${what} digestAlgorithm`,
- );
+ const digestAlgorithmOid = algorithmOid(fields[2], `${what} digestAlgorithm`);
// signedAttrs ([0] IMPLICIT) is optional before signatureAlgorithm.
const next = fields[3]?.tag === TAG.context0 ? 4 : 3;
const signatureAlgorithmOid = algorithmOid(
- reader,
fields[next],
`${what} signatureAlgorithm`,
);
@@ -320,25 +304,23 @@ const decode = (bytes: Uint8Array): ApkV1SignedData => {
TAG.sequence,
"ContentInfo",
);
- const [contentType, explicit] = reader.children(contentInfo);
- const type = oidText(
- reader.content(expectTag(contentType, TAG.oid, "contentType")),
- );
+ const [contentType, explicit] = contentInfo.children;
+ const type = oidText(expectTag(contentType, TAG.oid, "contentType").content);
if (type !== OID_SIGNED_DATA)
throw malformed(`contentType ${type} is not SignedData`);
const signedData = expectTag(
- reader.children(expectTag(explicit, TAG.context0, "content"))[0],
+ expectTag(explicit, TAG.context0, "content").children[0],
TAG.sequence,
"SignedData",
);
- const fields = reader.children(signedData);
+ const fields = signedData.children;
expectTag(fields[0], TAG.integer, "SignedData version");
expectTag(fields[1], TAG.set, "digestAlgorithms");
expectTag(fields[2], TAG.sequence, "encapContentInfo");
let at = 3;
- const certificates: Tlv[] = [];
+ const certificates: Asn1BerNode[] = [];
if (fields[at]?.tag === TAG.context0) {
- for (const choice of reader.children(fields[at] as Tlv)) {
+ for (const choice of fields[at]!.children) {
// Other CertificateChoices (extended, attribute, other) carry no X.509 signer.
if (choice.tag !== TAG.sequence)
throw malformed(
@@ -355,7 +337,7 @@ const decode = (bytes: Uint8Array): ApkV1SignedData => {
at += 1;
}
if (fields[at]?.tag === TAG.context1) at += 1;
- const infos = reader.children(expectTag(fields[at], TAG.set, "signerInfos"));
+ const infos = expectTag(fields[at], TAG.set, "signerInfos").children;
if (infos.length > MAX_V1_SIGNER_INFOS)
throw new BlockFailure({
kind: "budget-exceeded",
@@ -366,7 +348,9 @@ const decode = (bytes: Uint8Array): ApkV1SignedData => {
certificateIdentity(reader, certificate),
);
return {
- certificates: certificates.map((certificate) => reader.raw(certificate)),
+ certificates: certificates.map((certificate) =>
+ reader.rawEncodedSpan(certificate),
+ ),
signerInfos: infos.map((info, index) =>
signerInfo(reader, info, identities, index),
),