295 lines
10 KiB
JavaScript
Executable file
295 lines
10 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";
|
|
|
|
// Cache: tabId -> { url, securityInfo, certData, aiaInfo, sanInfo, techInfo,
|
|
// chainInfo, errorCode, errorDetail }
|
|
const certCache = {};
|
|
|
|
const ICON_DEFAULT = "icons/icon.svg";
|
|
const ICON_ERROR = "icons/icon-error.svg";
|
|
|
|
// Stable error codes — the popup translates them (see popup/i18n.js).
|
|
// Never report prose from here: it cannot be localized on the popup side.
|
|
const ERR_INSECURE_HTTP = "insecure_http";
|
|
const ERR_AIA_PARSE = "aia_parse_failed";
|
|
const ERR_SAN_PARSE = "san_parse_failed";
|
|
const ERR_KEYINFO_PARSE = "keyinfo_parse_failed";
|
|
const ERR_KEYUSAGE_PARSE = "keyusage_parse_failed";
|
|
const ERR_CERT_INFO = "cert_info_failed";
|
|
|
|
function updateIcon(tabId, isError) {
|
|
var path = isError
|
|
? { "48": ICON_ERROR, "96": ICON_ERROR }
|
|
: { "48": ICON_DEFAULT, "96": ICON_DEFAULT };
|
|
browser.browserAction.setIcon({ tabId: tabId, path: path })
|
|
.catch(function() { /* tab may have closed */ });
|
|
}
|
|
|
|
function hasCertificateError(data) {
|
|
if (!data) return false;
|
|
if (data.securityInfo) {
|
|
if (data.securityInfo.state === "broken") return true;
|
|
if (data.securityInfo.isNotValidAtThisTime) return true;
|
|
if (data.securityInfo.isDomainMismatch) return true;
|
|
if (data.securityInfo.isUntrusted) return true;
|
|
}
|
|
if (data.certData && data.certData.isNotValidAtThisTime) return true;
|
|
// Only treat generic errors as cert errors if no securityInfo exists
|
|
// (e.g. exception during getSecurityInfo). HTTP "not secure" errors
|
|
// have securityInfo: null but are NOT certificate errors.
|
|
if (data.errorCode && !data.securityInfo && data.errorCode !== ERR_INSECURE_HTTP) return true;
|
|
return false;
|
|
}
|
|
|
|
// btoa() needs a binary string. Chunk the conversion so large certificates
|
|
// do not blow the argument limit of String.fromCharCode.apply().
|
|
function toBase64(bytes) {
|
|
const CHUNK = 0x8000;
|
|
let binary = "";
|
|
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
|
|
}
|
|
return btoa(binary);
|
|
}
|
|
|
|
// PEM is built here, not in the popup: the raw DER only exists in this
|
|
// context, and sending strings avoids shipping binary through sendMessage().
|
|
function toPem(bytes) {
|
|
const base64 = toBase64(bytes);
|
|
const lines = [];
|
|
for (let i = 0; i < base64.length; i += 64) {
|
|
lines.push(base64.substring(i, i + 64));
|
|
}
|
|
return "-----BEGIN CERTIFICATE-----\n" +
|
|
lines.join("\n") +
|
|
"\n-----END CERTIFICATE-----";
|
|
}
|
|
|
|
// Colon-separated uppercase hex, matching `openssl x509 -fingerprint -sha256`.
|
|
async function sha256Fingerprint(bytes) {
|
|
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
const view = new Uint8Array(digest);
|
|
const parts = [];
|
|
for (let i = 0; i < view.length; i++) {
|
|
parts.push(view[i].toString(16).padStart(2, "0").toUpperCase());
|
|
}
|
|
return parts.join(":");
|
|
}
|
|
|
|
function parseDN(dnString) {
|
|
const result = Object.create(null);
|
|
if (!dnString) return result;
|
|
|
|
const parts = dnString.split(",");
|
|
for (const part of parts) {
|
|
const eqIndex = part.indexOf("=");
|
|
if (eqIndex > 0) {
|
|
const key = part.substring(0, eqIndex).trim();
|
|
const value = part.substring(eqIndex + 1).trim();
|
|
result[key] = value;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async function handleHeadersReceived(details) {
|
|
if (details.type !== "main_frame") {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const securityInfo = await browser.webRequest.getSecurityInfo(
|
|
details.requestId,
|
|
{ certificateChain: true, rawDER: true }
|
|
);
|
|
|
|
const tabId = details.tabId;
|
|
|
|
if (securityInfo.state === "insecure") {
|
|
certCache[tabId] = {
|
|
url: details.url,
|
|
securityInfo: null,
|
|
certData: null,
|
|
aiaInfo: null,
|
|
errorCode: ERR_INSECURE_HTTP
|
|
};
|
|
updateIcon(tabId, false);
|
|
return;
|
|
}
|
|
|
|
if (!securityInfo.certificates || securityInfo.certificates.length === 0) {
|
|
certCache[tabId] = {
|
|
url: details.url,
|
|
securityInfo: {
|
|
state: securityInfo.state,
|
|
protocolVersion: securityInfo.protocolVersion,
|
|
cipherSuite: securityInfo.cipherSuite,
|
|
isNotValidAtThisTime: securityInfo.isNotValidAtThisTime || false,
|
|
isDomainMismatch: securityInfo.isDomainMismatch || false,
|
|
isUntrusted: securityInfo.isUntrusted || false,
|
|
isExtendedValidation: securityInfo.isExtendedValidation || false,
|
|
errorMessage: securityInfo.errorMessage || null
|
|
},
|
|
certData: null,
|
|
aiaInfo: null,
|
|
errorCode: null
|
|
};
|
|
updateIcon(tabId, hasCertificateError(certCache[tabId]));
|
|
return;
|
|
}
|
|
|
|
const leafCert = securityInfo.certificates[0];
|
|
|
|
const certData = {
|
|
subject: parseDN(leafCert.subject),
|
|
issuer: parseDN(leafCert.issuer),
|
|
validityStart: leafCert.validity.start,
|
|
validityEnd: leafCert.validity.end,
|
|
isNotValidAtThisTime: securityInfo.isNotValidAtThisTime || false,
|
|
state: securityInfo.state,
|
|
isExtendedValidation: securityInfo.isExtendedValidation || false,
|
|
serialNumber: leafCert.serialNumber
|
|
};
|
|
|
|
let aiaInfo = null;
|
|
let sanInfo = null;
|
|
let techInfo = null;
|
|
if (leafCert.rawDER && leafCert.rawDER.length > 0) {
|
|
const der = new Uint8Array(leafCert.rawDER);
|
|
try {
|
|
aiaInfo = extractAIA(der);
|
|
} catch (e) {
|
|
console.warn("TLS Lens: Failed to parse AIA from DER:", e);
|
|
aiaInfo = { errorCode: ERR_AIA_PARSE };
|
|
}
|
|
try {
|
|
sanInfo = extractSAN(der);
|
|
} catch (e) {
|
|
console.warn("TLS Lens: Failed to parse SAN from DER:", e);
|
|
sanInfo = { errorCode: ERR_SAN_PARSE };
|
|
}
|
|
|
|
// Technical details — shown only in the collapsed section of the popup.
|
|
techInfo = { fingerprintSha256: await sha256Fingerprint(der) };
|
|
try {
|
|
Object.assign(techInfo, extractKeyInfo(der));
|
|
} catch (e) {
|
|
console.warn("TLS Lens: Failed to parse key info from DER:", e);
|
|
techInfo.keyInfoErrorCode = ERR_KEYINFO_PARSE;
|
|
}
|
|
try {
|
|
techInfo.keyUsage = extractKeyUsage(der);
|
|
techInfo.extKeyUsage = extractExtKeyUsage(der);
|
|
} catch (e) {
|
|
console.warn("TLS Lens: Failed to parse key usage from DER:", e);
|
|
techInfo.keyUsageErrorCode = ERR_KEYUSAGE_PARSE;
|
|
}
|
|
}
|
|
|
|
// Build certificate chain info. The PEM lets the popup offer an export
|
|
// without ever handling the raw DER itself.
|
|
const chainInfo = securityInfo.certificates.map(function(cert) {
|
|
return {
|
|
subject: parseDN(cert.subject),
|
|
issuer: parseDN(cert.issuer),
|
|
isBuiltInRoot: cert.isBuiltInRoot || false,
|
|
pem: cert.rawDER && cert.rawDER.length > 0
|
|
? toPem(new Uint8Array(cert.rawDER))
|
|
: null
|
|
};
|
|
});
|
|
|
|
certCache[tabId] = {
|
|
url: details.url,
|
|
securityInfo: {
|
|
state: securityInfo.state,
|
|
protocolVersion: securityInfo.protocolVersion,
|
|
cipherSuite: securityInfo.cipherSuite,
|
|
// Kept even on the full path: the summary line and the warning list
|
|
// need them, and Firefox reports state "secure" for accepted
|
|
// security exceptions while these flags still signal the problem.
|
|
isNotValidAtThisTime: securityInfo.isNotValidAtThisTime || false,
|
|
isDomainMismatch: securityInfo.isDomainMismatch || false,
|
|
isUntrusted: securityInfo.isUntrusted || false,
|
|
errorMessage: securityInfo.errorMessage || null,
|
|
isExtendedValidation: securityInfo.isExtendedValidation || false,
|
|
certificateTransparencyStatus: securityInfo.certificateTransparencyStatus || null,
|
|
usedOcsp: securityInfo.usedOcsp || false
|
|
},
|
|
certData,
|
|
aiaInfo,
|
|
sanInfo,
|
|
techInfo,
|
|
chainInfo,
|
|
errorCode: null
|
|
};
|
|
updateIcon(tabId, hasCertificateError(certCache[tabId]));
|
|
} catch (error) {
|
|
console.error("TLS Lens: Error getting security info:", error);
|
|
certCache[details.tabId] = {
|
|
url: details.url,
|
|
securityInfo: null,
|
|
certData: null,
|
|
aiaInfo: null,
|
|
errorCode: ERR_CERT_INFO,
|
|
// Raw Firefox message — already localized by the browser, shown as-is
|
|
errorDetail: error && error.message ? error.message : null
|
|
};
|
|
updateIcon(details.tabId, hasCertificateError(certCache[details.tabId]));
|
|
}
|
|
}
|
|
|
|
browser.webRequest.onHeadersReceived.addListener(
|
|
handleHeadersReceived,
|
|
{ urls: ["<all_urls>"] },
|
|
["blocking"]
|
|
);
|
|
|
|
// Invalidate stale cache when URL changes (e.g. bfcache, non-HTTP navigation)
|
|
// and update icon when page finishes loading
|
|
browser.tabs.onUpdated.addListener(function(tabId, changeInfo) {
|
|
if (changeInfo.url) {
|
|
var cached = certCache[tabId];
|
|
if (cached && cached.url !== changeInfo.url) {
|
|
delete certCache[tabId];
|
|
}
|
|
}
|
|
if (changeInfo.status === "complete") {
|
|
var data = certCache[tabId] || null;
|
|
updateIcon(tabId, hasCertificateError(data));
|
|
}
|
|
});
|
|
|
|
// Update icon when switching tabs — verify cache matches current tab URL
|
|
browser.tabs.onActivated.addListener(function(activeInfo) {
|
|
browser.tabs.get(activeInfo.tabId).then(function(tab) {
|
|
var data = certCache[activeInfo.tabId] || null;
|
|
if (data && tab.url && data.url !== tab.url) {
|
|
delete certCache[activeInfo.tabId];
|
|
data = null;
|
|
}
|
|
updateIcon(activeInfo.tabId, hasCertificateError(data));
|
|
}).catch(function() {});
|
|
});
|
|
|
|
// Clean up cache when tabs are closed
|
|
browser.tabs.onRemoved.addListener((tabId) => {
|
|
delete certCache[tabId];
|
|
});
|
|
|
|
// Message handler for popup communication
|
|
browser.runtime.onMessage.addListener((message, sender) => {
|
|
if (message.type === "getCertInfo") {
|
|
var data = certCache[message.tabId] || null;
|
|
// Verify cached URL matches the tab's current URL
|
|
if (data && message.url && data.url !== message.url) {
|
|
delete certCache[message.tabId];
|
|
data = null;
|
|
}
|
|
updateIcon(message.tabId, hasCertificateError(data));
|
|
return Promise.resolve(data);
|
|
}
|
|
});
|