TLS-Lens/lib/asn1-parser.js

474 lines
14 KiB
JavaScript
Executable file

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
"use strict";
/**
* Minimal ASN.1 DER parser for X.509 certificates.
* Provides: readASN1(), decodeOID(), extractAIA(), extractSAN(),
* extractKeyInfo(), extractKeyUsage(), extractExtKeyUsage()
*
* Every extract* function returns stable identifiers (OID keys, algorithm
* slugs), never prose — the popup translates them. Same rule as the error
* codes in background.js.
*/
const MAX_ASN1_DEPTH = 20;
function readASN1(data, offset, depth) {
if (offset === undefined) offset = 0;
if (depth === undefined) depth = 0;
if (depth > MAX_ASN1_DEPTH) {
throw new Error("ASN.1 max nesting depth exceeded");
}
const start = offset;
if (offset + 2 > data.length) {
throw new Error("ASN.1 truncated: not enough data for tag and length");
}
const tag = data[offset++];
const lengthByte = data[offset++];
let length;
if (lengthByte & 0x80) {
const numBytes = lengthByte & 0x7f;
if (numBytes === 0) {
throw new Error("ASN.1 indefinite length is not valid in DER");
}
if (numBytes > 4) {
throw new Error("ASN.1 length field too large: " + numBytes + " bytes");
}
if (offset + numBytes > data.length) {
throw new Error("ASN.1 truncated: not enough data for length field");
}
length = 0;
for (let i = 0; i < numBytes; i++) {
length = (length * 256) + data[offset++];
}
} else {
length = lengthByte;
}
if (offset + length > data.length) {
throw new Error("ASN.1 truncated: value extends beyond data (need " +
(offset + length) + ", have " + data.length + ")");
}
const value = data.slice(offset, offset + length);
const isConstructed = (tag & 0x20) !== 0;
let children = [];
if (isConstructed || tag === 0xa0 || tag === 0xa3) {
try {
let childOffset = 0;
while (childOffset < value.length) {
const child = readASN1(value, childOffset, depth + 1);
children.push(child);
childOffset += child.totalLength;
}
} catch (e) {
if (e.message && e.message.includes("max nesting depth")) {
throw e;
}
children = [];
}
}
return {
tag: tag,
length: length,
totalLength: offset + length - start,
value: value,
children: children
};
}
function decodeOID(bytes) {
if (!bytes || bytes.length === 0) return "";
const values = [];
let value = 0;
let first = true;
let continuationCount = 0;
for (let i = 0; i < bytes.length; i++) {
const byte = bytes[i];
if (first) {
values.push(Math.floor(byte / 40));
values.push(byte % 40);
first = false;
continue;
}
continuationCount++;
if (continuationCount > 5) {
value = 0;
continuationCount = 0;
if ((byte & 0x80) === 0) {
values.push(-1);
}
continue;
}
value = (value * 128) + (byte & 0x7f);
if ((byte & 0x80) === 0) {
values.push(value);
value = 0;
continuationCount = 0;
}
}
return values.join(".");
}
const OID_AIA = "1.3.6.1.5.5.7.1.1";
const OID_OCSP = "1.3.6.1.5.5.7.48.1";
const OID_CA_ISSUERS = "1.3.6.1.5.5.7.48.2";
const OID_SAN = "2.5.29.17";
const OID_KEY_USAGE = "2.5.29.15";
const OID_EXT_KEY_USAGE = "2.5.29.37";
// Public key algorithms -> stable slug
const PUBLIC_KEY_ALGORITHMS = {
"1.2.840.113549.1.1.1": "rsa",
"1.2.840.10045.2.1": "ec",
"1.3.101.112": "ed25519",
"1.3.101.113": "ed448"
};
// Named elliptic curves. The values are the standard curve names and are
// shown verbatim — they are identifiers, not translatable text.
const NAMED_CURVES = {
"1.2.840.10045.3.1.7": "P-256",
"1.3.132.0.34": "P-384",
"1.3.132.0.35": "P-521",
"1.3.132.0.10": "secp256k1",
"1.2.840.10045.3.1.1": "P-192",
"1.3.132.0.33": "P-224"
};
// Signature algorithms -> { hash, key } slugs. The hash slug also drives the
// SHA-1 warning in the popup.
const SIGNATURE_ALGORITHMS = {
"1.2.840.113549.1.1.5": { hash: "sha1", key: "rsa" },
"1.2.840.113549.1.1.11": { hash: "sha256", key: "rsa" },
"1.2.840.113549.1.1.12": { hash: "sha384", key: "rsa" },
"1.2.840.113549.1.1.13": { hash: "sha512", key: "rsa" },
"1.2.840.113549.1.1.14": { hash: "sha224", key: "rsa" },
"1.2.840.113549.1.1.4": { hash: "md5", key: "rsa" },
"1.2.840.113549.1.1.10": { hash: null, key: "rsapss" },
"1.2.840.10045.4.1": { hash: "sha1", key: "ecdsa" },
"1.2.840.10045.4.3.2": { hash: "sha256", key: "ecdsa" },
"1.2.840.10045.4.3.3": { hash: "sha384", key: "ecdsa" },
"1.2.840.10045.4.3.4": { hash: "sha512", key: "ecdsa" },
"1.3.101.112": { hash: null, key: "ed25519" },
"1.3.101.113": { hash: null, key: "ed448" }
};
// KeyUsage ::= BIT STRING — bit position (MSB first) -> stable slug
const KEY_USAGE_BITS = [
"digital_signature",
"non_repudiation",
"key_encipherment",
"data_encipherment",
"key_agreement",
"key_cert_sign",
"crl_sign",
"encipher_only",
"decipher_only"
];
// Extended key usage purposes -> stable slug
const EXT_KEY_USAGES = {
"1.3.6.1.5.5.7.3.1": "server_auth",
"1.3.6.1.5.5.7.3.2": "client_auth",
"1.3.6.1.5.5.7.3.3": "code_signing",
"1.3.6.1.5.5.7.3.4": "email_protection",
"1.3.6.1.5.5.7.3.8": "time_stamping",
"1.3.6.1.5.5.7.3.9": "ocsp_signing"
};
// Locate the extensions SEQUENCE within a parsed X.509 root node.
// Returns the SEQUENCE-of-extension node, or null if none is present.
function findExtensionsSeq(root) {
if (!root.children || root.children.length === 0) {
return null;
}
const tbsCert = root.children[0];
// Find extensions container (context tag 0xa3 = [3] constructed)
let extensionsContainer = null;
for (const child of tbsCert.children) {
if (child.tag === 0xa3) {
extensionsContainer = child;
break;
}
}
if (!extensionsContainer || extensionsContainer.children.length === 0) {
return null;
}
// Extensions is a SEQUENCE of SEQUENCE (each extension)
return extensionsContainer.children[0];
}
// Locate one extension by OID and return its value node (the trailing OCTET
// STRING — the optional `critical` BOOLEAN sits between OID and value).
// Returns null if the certificate does not carry that extension.
function findExtensionValue(root, oid) {
const extensionsSeq = findExtensionsSeq(root);
if (!extensionsSeq) {
return null;
}
for (const ext of extensionsSeq.children) {
if (ext.children.length < 2) continue;
const oidNode = ext.children[0];
if (oidNode.tag !== 0x06) continue;
if (decodeOID(oidNode.value) !== oid) continue;
return ext.children[ext.children.length - 1];
}
return null;
}
// Format the raw bytes of an iPAddress GeneralName.
// 4 bytes -> IPv4 dotted decimal, 16 bytes -> IPv6 colon hex.
function formatIpAddress(bytes) {
if (bytes.length === 4) {
return bytes[0] + "." + bytes[1] + "." + bytes[2] + "." + bytes[3];
}
if (bytes.length === 16) {
const groups = [];
for (let i = 0; i < 16; i += 2) {
const group = (bytes[i] * 256) + bytes[i + 1];
groups.push(group.toString(16));
}
return groups.join(":");
}
return null;
}
function extractAIA(derBytes) {
const result = { ocspUrl: null, caIssuersUrl: null };
const root = readASN1(derBytes, 0, 0);
const octetString = findExtensionValue(root, OID_AIA);
if (!octetString) {
return result;
}
// Parse the OCTET STRING content as ASN.1
const aiaSeq = readASN1(octetString.value, 0, 0);
for (const accessDesc of aiaSeq.children) {
if (accessDesc.children.length < 2) continue;
const methodOid = decodeOID(accessDesc.children[0].value);
const accessLocation = accessDesc.children[1];
// Tag 0x86 = context [6] = uniformResourceIdentifier (IA5String implicit)
if (accessLocation.tag === 0x86) {
const url = new TextDecoder().decode(accessLocation.value);
if (methodOid === OID_OCSP) {
result.ocspUrl = url;
} else if (methodOid === OID_CA_ISSUERS) {
result.caIssuersUrl = url;
}
}
}
return result;
}
function extractSAN(derBytes) {
const result = { dnsNames: [], ipAddresses: [] };
const root = readASN1(derBytes, 0, 0);
const octetString = findExtensionValue(root, OID_SAN);
if (!octetString) {
return result;
}
// OCTET STRING content is GeneralNames ::= SEQUENCE OF GeneralName
const sanSeq = readASN1(octetString.value, 0, 0);
for (const generalName of sanSeq.children) {
// Tag 0x82 = context [2] = dNSName (IA5String, implicit)
if (generalName.tag === 0x82) {
result.dnsNames.push(new TextDecoder().decode(generalName.value));
// Tag 0x87 = context [7] = iPAddress (OCTET STRING, implicit)
} else if (generalName.tag === 0x87) {
const ip = formatIpAddress(generalName.value);
if (ip) {
result.ipAddresses.push(ip);
}
}
}
return result;
}
// AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL }
function readAlgorithmIdentifier(node) {
if (!node || !node.children || node.children.length === 0) {
return { oid: null, parameters: null };
}
const oidNode = node.children[0];
if (oidNode.tag !== 0x06) {
return { oid: null, parameters: null };
}
return {
oid: decodeOID(oidNode.value),
parameters: node.children.length > 1 ? node.children[1] : null
};
}
// Bit length of a DER INTEGER, ignoring the leading 0x00 sign padding byte.
function integerBitLength(bytes) {
let i = 0;
while (i < bytes.length && bytes[i] === 0x00) {
i++;
}
if (i >= bytes.length) {
return 0;
}
let topBits = 8;
let top = bytes[i];
while (topBits > 0 && (top & 0x80) === 0) {
top = (top << 1) & 0xff;
topBits--;
}
return ((bytes.length - i - 1) * 8) + topBits;
}
// Public key algorithm/size plus the signature algorithm the issuer used.
// Returns stable slugs; unknown algorithms fall back to their raw OID.
function extractKeyInfo(derBytes) {
const result = {
keyAlgorithm: null,
keyAlgorithmOid: null,
keySize: null,
curve: null,
signatureHash: null,
signatureKey: null,
signatureOid: null
};
const root = readASN1(derBytes, 0, 0);
if (!root.children || root.children.length === 0) {
return result;
}
// Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, signatureValue }
const tbsCert = root.children[0];
if (root.children.length > 1) {
const sigAlg = readAlgorithmIdentifier(root.children[1]);
result.signatureOid = sigAlg.oid;
const known = SIGNATURE_ALGORITHMS[sigAlg.oid];
if (known) {
result.signatureHash = known.hash;
result.signatureKey = known.key;
}
}
if (!tbsCert.children || tbsCert.children.length === 0) {
return result;
}
// TBSCertificate ::= SEQUENCE { [0] version DEFAULT v1, serialNumber,
// signature, issuer, validity, subject, subjectPublicKeyInfo, ... }
// The version field is optional, which shifts every following index by one.
const hasVersion = tbsCert.children[0].tag === 0xa0;
const spki = tbsCert.children[hasVersion ? 6 : 5];
if (!spki || !spki.children || spki.children.length < 2) {
return result;
}
const keyAlg = readAlgorithmIdentifier(spki.children[0]);
result.keyAlgorithmOid = keyAlg.oid;
result.keyAlgorithm = PUBLIC_KEY_ALGORITHMS[keyAlg.oid] || null;
if (result.keyAlgorithm === "ec" && keyAlg.parameters &&
keyAlg.parameters.tag === 0x06) {
const curveOid = decodeOID(keyAlg.parameters.value);
result.curve = NAMED_CURVES[curveOid] || curveOid;
}
if (result.keyAlgorithm === "rsa") {
// subjectPublicKey is a BIT STRING; its first byte counts unused bits.
const bitString = spki.children[1];
if (bitString.tag === 0x03 && bitString.value.length > 1) {
const rsaKey = readASN1(bitString.value.slice(1), 0, 0);
if (rsaKey.children && rsaKey.children.length > 0 &&
rsaKey.children[0].tag === 0x02) {
result.keySize = integerBitLength(rsaKey.children[0].value);
}
}
} else if (result.keyAlgorithm === "ed25519") {
result.keySize = 256;
} else if (result.keyAlgorithm === "ed448") {
result.keySize = 448;
}
return result;
}
// KeyUsage ::= BIT STRING — returns the set bits as stable slugs.
function extractKeyUsage(derBytes) {
const result = [];
const root = readASN1(derBytes, 0, 0);
const octetString = findExtensionValue(root, OID_KEY_USAGE);
if (!octetString) {
return result;
}
const bitString = readASN1(octetString.value, 0, 0);
if (bitString.tag !== 0x03 || bitString.value.length < 2) {
return result;
}
// First byte is the number of unused bits in the final byte.
const unusedBits = bitString.value[0];
const bytes = bitString.value.slice(1);
const totalBits = (bytes.length * 8) - unusedBits;
for (let bit = 0; bit < KEY_USAGE_BITS.length && bit < totalBits; bit++) {
const byte = bytes[Math.floor(bit / 8)];
if (byte & (0x80 >> (bit % 8))) {
result.push(KEY_USAGE_BITS[bit]);
}
}
return result;
}
// ExtKeyUsageSyntax ::= SEQUENCE OF KeyPurposeId — returns stable slugs,
// falling back to the raw OID for purposes we do not have a name for.
function extractExtKeyUsage(derBytes) {
const result = [];
const root = readASN1(derBytes, 0, 0);
const octetString = findExtensionValue(root, OID_EXT_KEY_USAGE);
if (!octetString) {
return result;
}
const seq = readASN1(octetString.value, 0, 0);
for (const purpose of seq.children) {
if (purpose.tag !== 0x06) continue;
const oid = decodeOID(purpose.value);
result.push(EXT_KEY_USAGES[oid] || oid);
}
return result;
}