mirror of
https://github.com/gchq/CyberChef.git
synced 2025-04-24 00:36:16 -04:00
Merge branch 'master' into linuxgemini-patch-modhex
This commit is contained in:
commit
eb912547ac
60 changed files with 12005 additions and 3586 deletions
|
@ -166,6 +166,7 @@
|
|||
"name": "Public Key",
|
||||
"ops": [
|
||||
"Parse X.509 certificate",
|
||||
"Parse X.509 CRL",
|
||||
"Parse ASN.1 hex string",
|
||||
"PEM to Hex",
|
||||
"Hex to PEM",
|
||||
|
@ -235,9 +236,14 @@
|
|||
"Parse User Agent",
|
||||
"Parse IP range",
|
||||
"Parse IPv6 address",
|
||||
"IPv6 Transition Addresses",
|
||||
"Parse IPv4 header",
|
||||
"Strip IPv4 header",
|
||||
"Parse TCP",
|
||||
"Strip TCP header",
|
||||
"Parse TLS record",
|
||||
"Parse UDP",
|
||||
"Strip UDP header",
|
||||
"Parse SSH Host Key",
|
||||
"Parse URI",
|
||||
"URL Encode",
|
||||
|
@ -270,7 +276,8 @@
|
|||
"Unicode Text Format",
|
||||
"Remove Diacritics",
|
||||
"Unescape Unicode Characters",
|
||||
"Convert to NATO alphabet"
|
||||
"Convert to NATO alphabet",
|
||||
"Convert Leet Speak"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
@ -322,7 +329,9 @@
|
|||
"Unescape string",
|
||||
"Pseudo-Random Number Generator",
|
||||
"Sleep",
|
||||
"File Tree"
|
||||
"File Tree",
|
||||
"Take nth bytes",
|
||||
"Drop nth bytes"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
|
@ -44,7 +44,7 @@ export function toJA4(bytes) {
|
|||
the TLS version is the value of the Protocol Version. Handshake version (located at the top of the packet)
|
||||
should be ignored.
|
||||
*/
|
||||
let version = tlsr.version.value;
|
||||
let version = tlsr.handshake.value.helloVersion.value;
|
||||
for (const ext of tlsr.handshake.value.extensions.value) {
|
||||
if (ext.type.value === "supported_versions") {
|
||||
version = parseHighestSupportedVersion(ext.value.data);
|
||||
|
@ -189,7 +189,7 @@ export function toJA4S(bytes) {
|
|||
the TLS version is the value of the Protocol Version. Handshake version (located at the top of the packet)
|
||||
should be ignored.
|
||||
*/
|
||||
let version = tlsr.version.value;
|
||||
let version = tlsr.handshake.value.helloVersion.value;
|
||||
for (const ext of tlsr.handshake.value.extensions.value) {
|
||||
if (ext.type.value === "supported_versions") {
|
||||
version = parseHighestSupportedVersion(ext.value.data);
|
||||
|
|
|
@ -26,6 +26,9 @@ export function objToTable(obj, nested=false) {
|
|||
</tr>`;
|
||||
|
||||
for (const key in obj) {
|
||||
if (typeof obj[key] === "function")
|
||||
continue;
|
||||
|
||||
html += `<tr><td style='word-wrap: break-word'>${key}</td>`;
|
||||
if (typeof obj[key] === "object")
|
||||
html += `<td style='padding: 0'>${objToTable(obj[key], true)}</td>`;
|
||||
|
|
|
@ -22,7 +22,13 @@ class AddLineNumbers extends Operation {
|
|||
this.description = "Adds line numbers to the output.";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
this.args = [];
|
||||
this.args = [
|
||||
{
|
||||
"name": "Offset",
|
||||
"type": "number",
|
||||
"value": 0
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -33,10 +39,11 @@ class AddLineNumbers extends Operation {
|
|||
run(input, args) {
|
||||
const lines = input.split("\n"),
|
||||
width = lines.length.toString().length;
|
||||
const offset = args[0] ? parseInt(args[0], 10) : 0;
|
||||
let output = "";
|
||||
|
||||
for (let n = 0; n < lines.length; n++) {
|
||||
output += (n+1).toString().padStart(width, " ") + " " + lines[n] + "\n";
|
||||
output += (n+1+offset).toString().padStart(width, " ") + " " + lines[n] + "\n";
|
||||
}
|
||||
return output.slice(0, output.length-1);
|
||||
}
|
||||
|
|
|
@ -76,8 +76,8 @@ class BlowfishDecrypt extends Operation {
|
|||
Blowfish's key length needs to be between 4 and 56 bytes (32-448 bits).`);
|
||||
}
|
||||
|
||||
if (iv.length !== 8) {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes. Expected 8 bytes`);
|
||||
if (mode !== "ECB" && iv.length !== 8) {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes. Expected 8 bytes.`);
|
||||
}
|
||||
|
||||
input = Utils.convertToByteString(input, inputType);
|
||||
|
|
|
@ -72,12 +72,12 @@ class BlowfishEncrypt extends Operation {
|
|||
|
||||
if (key.length < 4 || key.length > 56) {
|
||||
throw new OperationError(`Invalid key length: ${key.length} bytes
|
||||
|
||||
|
||||
Blowfish's key length needs to be between 4 and 56 bytes (32-448 bits).`);
|
||||
}
|
||||
|
||||
if (iv.length !== 8) {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes. Expected 8 bytes`);
|
||||
if (mode !== "ECB" && iv.length !== 8) {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes. Expected 8 bytes.`);
|
||||
}
|
||||
|
||||
input = Utils.convertToByteString(input, inputType);
|
||||
|
|
113
src/core/operations/ConvertLeetSpeak.mjs
Normal file
113
src/core/operations/ConvertLeetSpeak.mjs
Normal file
|
@ -0,0 +1,113 @@
|
|||
/**
|
||||
* @author bartblaze []
|
||||
* @copyright Crown Copyright 2025
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
|
||||
/**
|
||||
* Convert Leet Speak operation
|
||||
*/
|
||||
class ConvertLeetSpeak extends Operation {
|
||||
/**
|
||||
* ConvertLeetSpeak constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Convert Leet Speak";
|
||||
this.module = "Default";
|
||||
this.description = "Converts to and from Leet Speak";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Leet";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
this.args = [
|
||||
{
|
||||
name: "Direction",
|
||||
type: "option",
|
||||
value: ["To Leet Speak", "From Leet Speak"],
|
||||
defaultIndex: 0
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} input
|
||||
* @param {Object[]} args
|
||||
* @returns {string}
|
||||
*/
|
||||
run(input, args) {
|
||||
const direction = args[0];
|
||||
if (direction === "To Leet Speak") {
|
||||
return input.replace(/[abcdefghijklmnopqrstuvwxyz]/gi, char => {
|
||||
return toLeetMap[char.toLowerCase()] || char;
|
||||
});
|
||||
} else if (direction === "From Leet Speak") {
|
||||
return input.replace(/[48cd3f6h1jklmn0pqr57uvwxyz]/g, char => {
|
||||
return fromLeetMap[char] || char;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const toLeetMap = {
|
||||
"a": "4",
|
||||
"b": "b",
|
||||
"c": "c",
|
||||
"d": "d",
|
||||
"e": "3",
|
||||
"f": "f",
|
||||
"g": "g",
|
||||
"h": "h",
|
||||
"i": "1",
|
||||
"j": "j",
|
||||
"k": "k",
|
||||
"l": "l",
|
||||
"m": "m",
|
||||
"n": "n",
|
||||
"o": "0",
|
||||
"p": "p",
|
||||
"q": "q",
|
||||
"r": "r",
|
||||
"s": "5",
|
||||
"t": "7",
|
||||
"u": "u",
|
||||
"v": "v",
|
||||
"w": "w",
|
||||
"x": "x",
|
||||
"y": "y",
|
||||
"z": "z"
|
||||
};
|
||||
|
||||
const fromLeetMap = {
|
||||
"4": "a",
|
||||
"b": "b",
|
||||
"c": "c",
|
||||
"d": "d",
|
||||
"3": "e",
|
||||
"f": "f",
|
||||
"g": "g",
|
||||
"h": "h",
|
||||
"1": "i",
|
||||
"j": "j",
|
||||
"k": "k",
|
||||
"l": "l",
|
||||
"m": "m",
|
||||
"n": "n",
|
||||
"0": "o",
|
||||
"p": "p",
|
||||
"q": "q",
|
||||
"r": "r",
|
||||
"5": "s",
|
||||
"7": "t",
|
||||
"u": "u",
|
||||
"v": "v",
|
||||
"w": "w",
|
||||
"x": "x",
|
||||
"y": "y",
|
||||
"z": "z"
|
||||
};
|
||||
|
||||
export default ConvertLeetSpeak;
|
||||
|
|
@ -22,7 +22,7 @@ class DESDecrypt extends Operation {
|
|||
|
||||
this.name = "DES Decrypt";
|
||||
this.module = "Ciphers";
|
||||
this.description = "DES is a previously dominant algorithm for encryption, and was published as an official U.S. Federal Information Processing Standard (FIPS). It is now considered to be insecure due to its small key size.<br><br><b>Key:</b> DES uses a key length of 8 bytes (64 bits).<br>Triple DES uses a key length of 24 bytes (192 bits).<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used as a default.";
|
||||
this.description = "DES is a previously dominant algorithm for encryption, and was published as an official U.S. Federal Information Processing Standard (FIPS). It is now considered to be insecure due to its small key size.<br><br><b>Key:</b> DES uses a key length of 8 bytes (64 bits).<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used as a default.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Data_Encryption_Standard";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
|
@ -72,8 +72,7 @@ class DESDecrypt extends Operation {
|
|||
if (key.length !== 8) {
|
||||
throw new OperationError(`Invalid key length: ${key.length} bytes
|
||||
|
||||
DES uses a key length of 8 bytes (64 bits).
|
||||
Triple DES uses a key length of 24 bytes (192 bits).`);
|
||||
DES uses a key length of 8 bytes (64 bits).`);
|
||||
}
|
||||
if (iv.length !== 8 && mode !== "ECB") {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes
|
||||
|
|
|
@ -22,7 +22,7 @@ class DESEncrypt extends Operation {
|
|||
|
||||
this.name = "DES Encrypt";
|
||||
this.module = "Ciphers";
|
||||
this.description = "DES is a previously dominant algorithm for encryption, and was published as an official U.S. Federal Information Processing Standard (FIPS). It is now considered to be insecure due to its small key size.<br><br><b>Key:</b> DES uses a key length of 8 bytes (64 bits).<br>Triple DES uses a key length of 24 bytes (192 bits).<br><br>You can generate a password-based key using one of the KDF operations.<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used.";
|
||||
this.description = "DES is a previously dominant algorithm for encryption, and was published as an official U.S. Federal Information Processing Standard (FIPS). It is now considered to be insecure due to its small key size.<br><br><b>Key:</b> DES uses a key length of 8 bytes (64 bits).<br><br>You can generate a password-based key using one of the KDF operations.<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Data_Encryption_Standard";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
|
@ -70,8 +70,7 @@ class DESEncrypt extends Operation {
|
|||
if (key.length !== 8) {
|
||||
throw new OperationError(`Invalid key length: ${key.length} bytes
|
||||
|
||||
DES uses a key length of 8 bytes (64 bits).
|
||||
Triple DES uses a key length of 24 bytes (192 bits).`);
|
||||
DES uses a key length of 8 bytes (64 bits).`);
|
||||
}
|
||||
if (iv.length !== 8 && mode !== "ECB") {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes
|
||||
|
|
79
src/core/operations/DropNthBytes.mjs
Normal file
79
src/core/operations/DropNthBytes.mjs
Normal file
|
@ -0,0 +1,79 @@
|
|||
/**
|
||||
* @author Oshawk [oshawk@protonmail.com]
|
||||
* @copyright Crown Copyright 2019
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import OperationError from "../errors/OperationError.mjs";
|
||||
|
||||
/**
|
||||
* Drop nth bytes operation
|
||||
*/
|
||||
class DropNthBytes extends Operation {
|
||||
|
||||
/**
|
||||
* DropNthBytes constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Drop nth bytes";
|
||||
this.module = "Default";
|
||||
this.description = "Drops every nth byte starting with a given byte.";
|
||||
this.infoURL = "";
|
||||
this.inputType = "byteArray";
|
||||
this.outputType = "byteArray";
|
||||
this.args = [
|
||||
{
|
||||
name: "Drop every",
|
||||
type: "number",
|
||||
value: 4
|
||||
},
|
||||
{
|
||||
name: "Starting at",
|
||||
type: "number",
|
||||
value: 0
|
||||
},
|
||||
{
|
||||
name: "Apply to each line",
|
||||
type: "boolean",
|
||||
value: false
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {byteArray} input
|
||||
* @param {Object[]} args
|
||||
* @returns {byteArray}
|
||||
*/
|
||||
run(input, args) {
|
||||
const n = args[0];
|
||||
const start = args[1];
|
||||
const eachLine = args[2];
|
||||
|
||||
if (parseInt(n, 10) !== n || n <= 0) {
|
||||
throw new OperationError("'Drop every' must be a positive integer.");
|
||||
}
|
||||
if (parseInt(start, 10) !== start || start < 0) {
|
||||
throw new OperationError("'Starting at' must be a positive or zero integer.");
|
||||
}
|
||||
|
||||
let offset = 0;
|
||||
const output = [];
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
if (eachLine && input[i] === 0x0a) {
|
||||
output.push(0x0a);
|
||||
offset = i + 1;
|
||||
} else if (i - offset < start || (i - (start + offset)) % n !== 0) {
|
||||
output.push(input[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default DropNthBytes;
|
|
@ -5,16 +5,14 @@
|
|||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import otp from "otp";
|
||||
import ToBase32 from "./ToBase32.mjs";
|
||||
import * as OTPAuth from "otpauth";
|
||||
|
||||
/**
|
||||
* Generate HOTP operation
|
||||
*/
|
||||
class GenerateHOTP extends Operation {
|
||||
|
||||
/**
|
||||
* GenerateHOTP constructor
|
||||
*
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
@ -31,11 +29,6 @@ class GenerateHOTP extends Operation {
|
|||
"type": "string",
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"name": "Key size",
|
||||
"type": "number",
|
||||
"value": 32
|
||||
},
|
||||
{
|
||||
"name": "Code length",
|
||||
"type": "number",
|
||||
|
@ -50,21 +43,26 @@ class GenerateHOTP extends Operation {
|
|||
}
|
||||
|
||||
/**
|
||||
* @param {ArrayBuffer} input
|
||||
* @param {Object[]} args
|
||||
* @returns {string}
|
||||
*
|
||||
*/
|
||||
run(input, args) {
|
||||
const otpObj = otp({
|
||||
name: args[0],
|
||||
keySize: args[1],
|
||||
codeLength: args[2],
|
||||
secret: (new ToBase32).run(input, []).split("=")[0],
|
||||
});
|
||||
const counter = args[3];
|
||||
return `URI: ${otpObj.hotpURL}\n\nPassword: ${otpObj.hotp(counter)}`;
|
||||
}
|
||||
const secretStr = new TextDecoder("utf-8").decode(input).trim();
|
||||
const secret = secretStr ? secretStr.toUpperCase().replace(/\s+/g, "") : "";
|
||||
|
||||
const hotp = new OTPAuth.HOTP({
|
||||
issuer: "",
|
||||
label: args[0],
|
||||
algorithm: "SHA1",
|
||||
digits: args[1],
|
||||
counter: args[2],
|
||||
secret: OTPAuth.Secret.fromBase32(secret)
|
||||
});
|
||||
|
||||
const uri = hotp.toString();
|
||||
const code = hotp.generate();
|
||||
|
||||
return `URI: ${uri}\n\nPassword: ${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
export default GenerateHOTP;
|
||||
|
|
|
@ -5,20 +5,17 @@
|
|||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import otp from "otp";
|
||||
import ToBase32 from "./ToBase32.mjs";
|
||||
import * as OTPAuth from "otpauth";
|
||||
|
||||
/**
|
||||
* Generate TOTP operation
|
||||
*/
|
||||
class GenerateTOTP extends Operation {
|
||||
|
||||
/**
|
||||
* GenerateTOTP constructor
|
||||
*
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Generate TOTP";
|
||||
this.module = "Default";
|
||||
this.description = "The Time-based One-Time Password algorithm (TOTP) is an algorithm that computes a one-time password from a shared secret key and the current time. It has been adopted as Internet Engineering Task Force standard RFC 6238, is the cornerstone of Initiative For Open Authentication (OAUTH), and is used in a number of two-factor authentication systems. A TOTP is an HOTP where the counter is the current time.<br><br>Enter the secret as the input or leave it blank for a random secret to be generated. T0 and T1 are in seconds.";
|
||||
|
@ -31,11 +28,6 @@ class GenerateTOTP extends Operation {
|
|||
"type": "string",
|
||||
"value": ""
|
||||
},
|
||||
{
|
||||
"name": "Key size",
|
||||
"type": "number",
|
||||
"value": 32
|
||||
},
|
||||
{
|
||||
"name": "Code length",
|
||||
"type": "number",
|
||||
|
@ -55,22 +47,27 @@ class GenerateTOTP extends Operation {
|
|||
}
|
||||
|
||||
/**
|
||||
* @param {ArrayBuffer} input
|
||||
* @param {Object[]} args
|
||||
* @returns {string}
|
||||
*
|
||||
*/
|
||||
run(input, args) {
|
||||
const otpObj = otp({
|
||||
name: args[0],
|
||||
keySize: args[1],
|
||||
codeLength: args[2],
|
||||
secret: (new ToBase32).run(input, []).split("=")[0],
|
||||
epoch: args[3],
|
||||
timeSlice: args[4]
|
||||
});
|
||||
return `URI: ${otpObj.totpURL}\n\nPassword: ${otpObj.totp()}`;
|
||||
}
|
||||
const secretStr = new TextDecoder("utf-8").decode(input).trim();
|
||||
const secret = secretStr ? secretStr.toUpperCase().replace(/\s+/g, "") : "";
|
||||
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: "",
|
||||
label: args[0],
|
||||
algorithm: "SHA1",
|
||||
digits: args[1],
|
||||
period: args[3],
|
||||
epoch: args[2] * 1000, // Convert seconds to milliseconds
|
||||
secret: OTPAuth.Secret.fromBase32(secret)
|
||||
});
|
||||
|
||||
const uri = totp.toString();
|
||||
const code = totp.generate();
|
||||
|
||||
return `URI: ${uri}\n\nPassword: ${code}`;
|
||||
}
|
||||
}
|
||||
|
||||
export default GenerateTOTP;
|
||||
|
|
209
src/core/operations/IPv6TransitionAddresses.mjs
Normal file
209
src/core/operations/IPv6TransitionAddresses.mjs
Normal file
|
@ -0,0 +1,209 @@
|
|||
/**
|
||||
* @author jb30795 [jb30795@proton.me]
|
||||
* @copyright Crown Copyright 2024
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
|
||||
/**
|
||||
* IPv6 Transition Addresses operation
|
||||
*/
|
||||
class IPv6TransitionAddresses extends Operation {
|
||||
|
||||
/**
|
||||
* IPv6TransitionAddresses constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "IPv6 Transition Addresses";
|
||||
this.module = "Default";
|
||||
this.description = "Converts IPv4 addresses to their IPv6 Transition addresses. IPv6 Transition addresses can also be converted back into their original IPv4 address. MAC addresses can also be converted into the EUI-64 format, this can them be appended to your IPv6 /64 range to obtain a full /128 address.<br><br>Transition technologies enable translation between IPv4 and IPv6 addresses or tunneling to allow traffic to pass through the incompatible network, allowing the two standards to coexist.<br><br>Only /24 ranges and currently handled. Remove headers to easily copy out results.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/IPv6_transition_mechanism";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
this.args = [
|
||||
{
|
||||
"name": "Ignore ranges",
|
||||
"type": "boolean",
|
||||
"value": true
|
||||
},
|
||||
{
|
||||
"name": "Remove headers",
|
||||
"type": "boolean",
|
||||
"value": false
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} input
|
||||
* @param {Object[]} args
|
||||
* @returns {string}
|
||||
*/
|
||||
run(input, args) {
|
||||
const XOR = {"0": "2", "1": "3", "2": "0", "3": "1", "4": "6", "5": "7", "6": "4", "7": "5", "8": "a", "9": "b", "a": "8", "b": "9", "c": "e", "d": "f", "e": "c", "f": "d"};
|
||||
|
||||
/**
|
||||
* Function to convert to hex
|
||||
*/
|
||||
function hexify(octet) {
|
||||
return Number(octet).toString(16).padStart(2, "0");
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to convert Hex to Int
|
||||
*/
|
||||
function intify(hex) {
|
||||
return parseInt(hex, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function converts IPv4 to IPv6 Transtion address
|
||||
*/
|
||||
function ipTransition(input, range) {
|
||||
let output = "";
|
||||
const HEXIP = input.split(".");
|
||||
|
||||
/**
|
||||
* 6to4
|
||||
*/
|
||||
if (!args[1]) {
|
||||
output += "6to4: ";
|
||||
}
|
||||
output += "2002:" + hexify(HEXIP[0]) + hexify(HEXIP[1]) + ":" + hexify(HEXIP[2]);
|
||||
if (range) {
|
||||
output += "00::/40\n";
|
||||
} else {
|
||||
output += hexify(HEXIP[3]) + "::/48\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Mapped
|
||||
*/
|
||||
if (!args[1]) {
|
||||
output += "IPv4 Mapped: ";
|
||||
}
|
||||
output += "::ffff:" + hexify(HEXIP[0]) + hexify(HEXIP[1]) + ":" + hexify(HEXIP[2]);
|
||||
if (range) {
|
||||
output += "00/120\n";
|
||||
} else {
|
||||
output += hexify(HEXIP[3]) + "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Translated
|
||||
*/
|
||||
if (!args[1]) {
|
||||
output += "IPv4 Translated: ";
|
||||
}
|
||||
output += "::ffff:0:" + hexify(HEXIP[0]) + hexify(HEXIP[1]) + ":" + hexify(HEXIP[2]);
|
||||
if (range) {
|
||||
output += "00/120\n";
|
||||
} else {
|
||||
output += hexify(HEXIP[3]) + "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Nat64
|
||||
*/
|
||||
if (!args[1]) {
|
||||
output += "Nat 64: ";
|
||||
}
|
||||
output += "64:ff9b::" + hexify(HEXIP[0]) + hexify(HEXIP[1]) + ":" + hexify(HEXIP[2]);
|
||||
if (range) {
|
||||
output += "00/120\n";
|
||||
} else {
|
||||
output += hexify(HEXIP[3]) + "\n";
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert MAC to EUI-64
|
||||
*/
|
||||
function macTransition(input) {
|
||||
let output = "";
|
||||
const MACPARTS = input.split(":");
|
||||
if (!args[1]) {
|
||||
output += "EUI-64 Interface ID: ";
|
||||
}
|
||||
const MAC = MACPARTS[0] + MACPARTS[1] + ":" + MACPARTS[2] + "ff:fe" + MACPARTS[3] + ":" + MACPARTS[4] + MACPARTS[5];
|
||||
output += MAC.slice(0, 1) + XOR[MAC.slice(1, 2)] + MAC.slice(2);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert IPv6 address to its original IPv4 or MAC address
|
||||
*/
|
||||
function unTransition(input) {
|
||||
let output = "";
|
||||
let hextets = "";
|
||||
|
||||
/**
|
||||
* 6to4
|
||||
*/
|
||||
if (input.startsWith("2002:")) {
|
||||
if (!args[1]) {
|
||||
output += "IPv4: ";
|
||||
}
|
||||
output += String(intify(input.slice(5, 7))) + "." + String(intify(input.slice(7, 9)))+ "." + String(intify(input.slice(10, 12)))+ "." + String(intify(input.slice(12, 14))) + "\n";
|
||||
} else if (input.startsWith("::ffff:") || input.startsWith("0000:0000:0000:0000:0000:ffff:") || input.startsWith("::ffff:0000:") || input.startsWith("0000:0000:0000:0000:ffff:0000:") || input.startsWith("64:ff9b::") || input.startsWith("0064:ff9b:0000:0000:0000:0000:")) {
|
||||
/**
|
||||
* Mapped/Translated/Nat64
|
||||
*/
|
||||
hextets = /:([0-9a-z]{1,4}):[0-9a-z]{1,4}$/.exec(input)[1].padStart(4, "0") + /:([0-9a-z]{1,4})$/.exec(input)[1].padStart(4, "0");
|
||||
if (!args[1]) {
|
||||
output += "IPv4: ";
|
||||
}
|
||||
output += intify(hextets.slice(-8, -7) + hextets.slice(-7, -6)) + "." +intify(hextets.slice(-6, -5) + hextets.slice(-5, -4)) + "." +intify(hextets.slice(-4, -3) + hextets.slice(-3, -2)) + "." +intify(hextets.slice(-2, -1) + hextets.slice(-1,)) + "\n";
|
||||
} else if (input.slice(-12, -7).toUpperCase() === "FF:FE") {
|
||||
/**
|
||||
* EUI-64
|
||||
*/
|
||||
if (!args[1]) {
|
||||
output += "Mac Address: ";
|
||||
}
|
||||
const MAC = (input.slice(-19, -17) + ":" + input.slice(-17, -15) + ":" + input.slice(-14, -12) + ":" + input.slice(-7, -5) + ":" + input.slice(-4, -2) + ":" + input.slice(-2,)).toUpperCase();
|
||||
output += MAC.slice(0, 1) + XOR[MAC.slice(1, 2)] + MAC.slice(2) + "\n";
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
let output = "";
|
||||
let inputs = input.split("\n");
|
||||
// Remove blank rows
|
||||
inputs = inputs.filter(Boolean);
|
||||
|
||||
for (let i = 0; i < inputs.length; i++) {
|
||||
// if ignore ranges is checked and input is a range, skip
|
||||
if ((args[0] && !inputs[i].includes("/")) || (!args[0])) {
|
||||
if (/^[0-9]{1,3}(?:\.[0-9]{1,3}){3}$/.test(inputs[i])) {
|
||||
output += ipTransition(inputs[i], false);
|
||||
} else if (/\/24$/.test(inputs[i])) {
|
||||
output += ipTransition(inputs[i], true);
|
||||
} else if (/^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$/.test(inputs[i])) {
|
||||
output += macTransition(inputs[i]);
|
||||
} else if (/^((?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(?::[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(?:ffff(?::0{1,4}){0,1}:){0,1}(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/.test(inputs[i])) {
|
||||
output += unTransition(inputs[i]);
|
||||
} else {
|
||||
output = "Enter compressed or expanded IPv6 address, IPv4 address or MAC Address.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default IPv6TransitionAddresses;
|
|
@ -36,6 +36,11 @@ class JWTSign extends Operation {
|
|||
name: "Signing algorithm",
|
||||
type: "option",
|
||||
value: JWT_ALGORITHMS
|
||||
},
|
||||
{
|
||||
name: "Header",
|
||||
type: "text",
|
||||
value: "{}"
|
||||
}
|
||||
];
|
||||
}
|
||||
|
@ -46,11 +51,12 @@ class JWTSign extends Operation {
|
|||
* @returns {string}
|
||||
*/
|
||||
run(input, args) {
|
||||
const [key, algorithm] = args;
|
||||
const [key, algorithm, header] = args;
|
||||
|
||||
try {
|
||||
return jwt.sign(input, key, {
|
||||
algorithm: algorithm === "None" ? "none" : algorithm
|
||||
algorithm: algorithm === "None" ? "none" : algorithm,
|
||||
header: JSON.parse(header || "{}")
|
||||
});
|
||||
} catch (err) {
|
||||
throw new OperationError(`Error: Have you entered the key correctly? The key should be either the secret for HMAC algorithms or the PEM-encoded private key for RSA and ECDSA.
|
||||
|
|
|
@ -22,7 +22,7 @@ class JWTVerify extends Operation {
|
|||
|
||||
this.name = "JWT Verify";
|
||||
this.module = "Crypto";
|
||||
this.description = "Verifies that a JSON Web Token is valid and has been signed with the provided secret / private key.<br><br>The key should be either the secret for HMAC algorithms or the PEM-encoded private key for RSA and ECDSA.";
|
||||
this.description = "Verifies that a JSON Web Token is valid and has been signed with the provided secret / private key.<br><br>The key should be either the secret for HMAC algorithms or the PEM-encoded public key for RSA and ECDSA.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/JSON_Web_Token";
|
||||
this.inputType = "string";
|
||||
this.outputType = "JSON";
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
/**
|
||||
* @author n1073645 [n1073645@gmail.com]
|
||||
* @author k3ach [k3ach@proton.me]
|
||||
* @copyright Crown Copyright 2020
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
@ -20,39 +21,46 @@ class LuhnChecksum extends Operation {
|
|||
|
||||
this.name = "Luhn Checksum";
|
||||
this.module = "Default";
|
||||
this.description = "The Luhn algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers and Canadian Social Insurance Numbers.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Luhn_algorithm";
|
||||
this.description = "The Luhn mod N algorithm using the english alphabet. The Luhn mod N algorithm is an extension to the Luhn algorithm (also known as mod 10 algorithm) that allows it to work with sequences of values in any even-numbered base. This can be useful when a check digit is required to validate an identification string composed of letters, a combination of letters and digits or any arbitrary set of N characters where N is divisible by 2.";
|
||||
this.infoURL = "https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
this.args = [];
|
||||
this.args = [
|
||||
{
|
||||
"name": "Radix",
|
||||
"type": "number",
|
||||
"value": 10
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the Luhn Checksum from the input.
|
||||
* Generates the Luhn checksum from the input.
|
||||
*
|
||||
* @param {string} inputStr
|
||||
* @returns {number}
|
||||
*/
|
||||
checksum(inputStr) {
|
||||
checksum(inputStr, radix = 10) {
|
||||
let even = false;
|
||||
return inputStr.split("").reverse().reduce((acc, elem) => {
|
||||
// Convert element to integer.
|
||||
let temp = parseInt(elem, 10);
|
||||
// Convert element to an integer based on the provided radix.
|
||||
let temp = parseInt(elem, radix);
|
||||
|
||||
// If element is not an integer.
|
||||
if (isNaN(temp))
|
||||
throw new OperationError("Character: " + elem + " is not a digit.");
|
||||
// If element is not a valid number in the given radix.
|
||||
if (isNaN(temp)) {
|
||||
throw new Error("Character: " + elem + " is not valid in radix " + radix + ".");
|
||||
}
|
||||
|
||||
// If element is in an even position
|
||||
if (even) {
|
||||
// Double the element and add the quotient and remainder together.
|
||||
temp = 2 * elem;
|
||||
temp = Math.floor(temp/10) + (temp % 10);
|
||||
// Double the element and sum the quotient and remainder.
|
||||
temp = 2 * temp;
|
||||
temp = Math.floor(temp / radix) + (temp % radix);
|
||||
}
|
||||
|
||||
even = !even;
|
||||
return acc + temp;
|
||||
}, 0) % 10;
|
||||
}, 0) % radix; // Use radix as the modulus base
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -63,9 +71,20 @@ class LuhnChecksum extends Operation {
|
|||
run(input, args) {
|
||||
if (!input) return "";
|
||||
|
||||
const checkSum = this.checksum(input);
|
||||
let checkDigit = this.checksum(input + "0");
|
||||
checkDigit = checkDigit === 0 ? 0 : (10-checkDigit);
|
||||
const radix = args[0];
|
||||
|
||||
if (radix < 2 || radix > 36) {
|
||||
throw new OperationError("Error: Radix argument must be between 2 and 36");
|
||||
}
|
||||
|
||||
if (radix % 2 !== 0) {
|
||||
throw new OperationError("Error: Radix argument must be divisible by 2");
|
||||
}
|
||||
|
||||
const checkSum = this.checksum(input, radix).toString(radix);
|
||||
let checkDigit = this.checksum(input + "0", radix);
|
||||
checkDigit = checkDigit === 0 ? 0 : (radix - checkDigit);
|
||||
checkDigit = checkDigit.toString(radix);
|
||||
|
||||
return `Checksum: ${checkSum}
|
||||
Checkdigit: ${checkDigit}
|
||||
|
|
|
@ -12,9 +12,10 @@ import { isImage } from "../lib/FileType.mjs";
|
|||
import { toBase64 } from "../lib/Base64.mjs";
|
||||
import { isWorkerEnvironment } from "../Utils.mjs";
|
||||
|
||||
import process from "process";
|
||||
import { createWorker } from "tesseract.js";
|
||||
|
||||
const OEM_MODES = ["Tesseract only", "LSTM only", "Tesseract/LSTM Combined"];
|
||||
|
||||
/**
|
||||
* Optical Character Recognition operation
|
||||
*/
|
||||
|
@ -37,6 +38,12 @@ class OpticalCharacterRecognition extends Operation {
|
|||
name: "Show confidence",
|
||||
type: "boolean",
|
||||
value: true
|
||||
},
|
||||
{
|
||||
name: "OCR Engine Mode",
|
||||
type: "option",
|
||||
value: OEM_MODES,
|
||||
defaultIndex: 1
|
||||
}
|
||||
];
|
||||
}
|
||||
|
@ -47,7 +54,7 @@ class OpticalCharacterRecognition extends Operation {
|
|||
* @returns {string}
|
||||
*/
|
||||
async run(input, args) {
|
||||
const [showConfidence] = args;
|
||||
const [showConfidence, oemChoice] = args;
|
||||
|
||||
if (!isWorkerEnvironment()) throw new OperationError("This operation only works in a browser");
|
||||
|
||||
|
@ -56,12 +63,13 @@ class OpticalCharacterRecognition extends Operation {
|
|||
throw new OperationError("Unsupported file type (supported: jpg,png,pbm,bmp) or no file provided");
|
||||
}
|
||||
|
||||
const assetDir = isWorkerEnvironment() ? `${self.docURL}/assets/` : `${process.cwd()}/src/core/vendor/`;
|
||||
const assetDir = `${self.docURL}/assets/`;
|
||||
const oem = OEM_MODES.indexOf(oemChoice);
|
||||
|
||||
try {
|
||||
self.sendStatusMessage("Spinning up Tesseract worker...");
|
||||
const image = `data:${type};base64,${toBase64(input)}`;
|
||||
const worker = createWorker({
|
||||
const worker = await createWorker("eng", oem, {
|
||||
workerPath: `${assetDir}tesseract/worker.min.js`,
|
||||
langPath: `${assetDir}tesseract/lang-data`,
|
||||
corePath: `${assetDir}tesseract/tesseract-core.wasm.js`,
|
||||
|
@ -71,11 +79,6 @@ class OpticalCharacterRecognition extends Operation {
|
|||
}
|
||||
}
|
||||
});
|
||||
await worker.load();
|
||||
self.sendStatusMessage(`Loading English language pack...`);
|
||||
await worker.loadLanguage("eng");
|
||||
self.sendStatusMessage("Intialising Tesseract API...");
|
||||
await worker.initialize("eng");
|
||||
self.sendStatusMessage("Finding text...");
|
||||
const result = await worker.recognize(image);
|
||||
|
||||
|
|
|
@ -4,8 +4,9 @@
|
|||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import r from "jsrsasign";
|
||||
import Operation from "../Operation.mjs";
|
||||
import forge from "node-forge";
|
||||
import { formatDnObj } from "../lib/PublicKey.mjs";
|
||||
import Utils from "../Utils.mjs";
|
||||
|
||||
/**
|
||||
|
@ -30,16 +31,6 @@ class ParseCSR extends Operation {
|
|||
"name": "Input format",
|
||||
"type": "option",
|
||||
"value": ["PEM"]
|
||||
},
|
||||
{
|
||||
"name": "Key type",
|
||||
"type": "option",
|
||||
"value": ["RSA"]
|
||||
},
|
||||
{
|
||||
"name": "Strict ASN.1 value lengths",
|
||||
"type": "boolean",
|
||||
"value": true
|
||||
}
|
||||
];
|
||||
this.checks = [
|
||||
|
@ -61,73 +52,71 @@ class ParseCSR extends Operation {
|
|||
return "No input";
|
||||
}
|
||||
|
||||
const csr = forge.pki.certificationRequestFromPem(input, args[1]);
|
||||
// Parse the CSR into JSON parameters
|
||||
const csrParam = new r.KJUR.asn1.csr.CSRUtil.getParam(input);
|
||||
|
||||
// RSA algorithm is the only one supported for CSR in node-forge as of 1.3.1
|
||||
return `Version: ${1 + csr.version} (0x${Utils.hex(csr.version)})
|
||||
Subject${formatSubject(csr.subject)}
|
||||
Subject Alternative Names${formatSubjectAlternativeNames(csr)}
|
||||
Public Key
|
||||
Algorithm: RSA
|
||||
Length: ${csr.publicKey.n.bitLength()} bits
|
||||
Modulus: ${formatMultiLine(chop(csr.publicKey.n.toString(16).replace(/(..)/g, "$&:")))}
|
||||
Exponent: ${csr.publicKey.e} (0x${Utils.hex(csr.publicKey.e)})
|
||||
Signature
|
||||
Algorithm: ${forge.pki.oids[csr.signatureOid]}
|
||||
Signature: ${formatMultiLine(Utils.strToByteArray(csr.signature).map(b => Utils.hex(b)).join(":"))}
|
||||
Extensions${formatExtensions(csr)}`;
|
||||
return `Subject\n${formatDnObj(csrParam.subject, 2)}
|
||||
Public Key${formatSubjectPublicKey(csrParam.sbjpubkey)}
|
||||
Signature${formatSignature(csrParam.sigalg, csrParam.sighex)}
|
||||
Requested Extensions${formatRequestedExtensions(csrParam)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Subject of the request as a multi-line string
|
||||
* @param {*} subject CSR Subject
|
||||
* @returns Multi-line string describing Subject
|
||||
* Format signature of a CSR
|
||||
* @param {*} sigAlg string
|
||||
* @param {*} sigHex string
|
||||
* @returns Multi-line string describing CSR Signature
|
||||
*/
|
||||
function formatSubject(subject) {
|
||||
let out = "\n";
|
||||
function formatSignature(sigAlg, sigHex) {
|
||||
let out = `\n`;
|
||||
|
||||
for (const attribute of subject.attributes) {
|
||||
out += ` ${attribute.shortName} = ${attribute.value}\n`;
|
||||
out += ` Algorithm: ${sigAlg}\n`;
|
||||
|
||||
if (new RegExp("withdsa", "i").test(sigAlg)) {
|
||||
const d = new r.KJUR.crypto.DSA();
|
||||
const sigParam = d.parseASN1Signature(sigHex);
|
||||
out += ` Signature:
|
||||
R: ${formatHexOntoMultiLine(absBigIntToHex(sigParam[0]))}
|
||||
S: ${formatHexOntoMultiLine(absBigIntToHex(sigParam[1]))}\n`;
|
||||
} else if (new RegExp("withrsa", "i").test(sigAlg)) {
|
||||
out += ` Signature: ${formatHexOntoMultiLine(sigHex)}\n`;
|
||||
} else {
|
||||
out += ` Signature: ${formatHexOntoMultiLine(ensureHexIsPositiveInTwosComplement(sigHex))}\n`;
|
||||
}
|
||||
|
||||
return chop(out);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Format Subject Alternative Names from the name `subjectAltName` extension
|
||||
* @param {*} extension CSR object
|
||||
* @returns Multi-line string describing Subject Alternative Names
|
||||
* Format Subject Public Key from PEM encoded public key string
|
||||
* @param {*} publicKeyPEM string
|
||||
* @returns Multi-line string describing Subject Public Key Info
|
||||
*/
|
||||
function formatSubjectAlternativeNames(csr) {
|
||||
function formatSubjectPublicKey(publicKeyPEM) {
|
||||
let out = "\n";
|
||||
|
||||
for (const attribute of csr.attributes) {
|
||||
for (const extension of attribute.extensions) {
|
||||
if (extension.name === "subjectAltName") {
|
||||
const names = [];
|
||||
for (const altName of extension.altNames) {
|
||||
switch (altName.type) {
|
||||
case 1:
|
||||
names.push(`EMAIL: ${altName.value}`);
|
||||
break;
|
||||
case 2:
|
||||
names.push(`DNS: ${altName.value}`);
|
||||
break;
|
||||
case 6:
|
||||
names.push(`URI: ${altName.value}`);
|
||||
break;
|
||||
case 7:
|
||||
names.push(`IP: ${altName.ip}`);
|
||||
break;
|
||||
default:
|
||||
names.push(`(unable to format type ${altName.type} name)\n`);
|
||||
}
|
||||
}
|
||||
out += indent(2, names);
|
||||
}
|
||||
}
|
||||
const publicKey = r.KEYUTIL.getKey(publicKeyPEM);
|
||||
if (publicKey instanceof r.RSAKey) {
|
||||
out += ` Algorithm: RSA
|
||||
Length: ${publicKey.n.bitLength()} bits
|
||||
Modulus: ${formatHexOntoMultiLine(absBigIntToHex(publicKey.n))}
|
||||
Exponent: ${publicKey.e} (0x${Utils.hex(publicKey.e)})\n`;
|
||||
} else if (publicKey instanceof r.KJUR.crypto.ECDSA) {
|
||||
out += ` Algorithm: ECDSA
|
||||
Length: ${publicKey.ecparams.keylen} bits
|
||||
Pub: ${formatHexOntoMultiLine(publicKey.pubKeyHex)}
|
||||
ASN1 OID: ${r.KJUR.crypto.ECDSA.getName(publicKey.getShortNISTPCurveName())}
|
||||
NIST CURVE: ${publicKey.getShortNISTPCurveName()}\n`;
|
||||
} else if (publicKey instanceof r.KJUR.crypto.DSA) {
|
||||
out += ` Algorithm: DSA
|
||||
Length: ${publicKey.p.toString(16).length * 4} bits
|
||||
Pub: ${formatHexOntoMultiLine(absBigIntToHex(publicKey.y))}
|
||||
P: ${formatHexOntoMultiLine(absBigIntToHex(publicKey.p))}
|
||||
Q: ${formatHexOntoMultiLine(absBigIntToHex(publicKey.q))}
|
||||
G: ${formatHexOntoMultiLine(absBigIntToHex(publicKey.g))}\n`;
|
||||
} else {
|
||||
out += `unsupported public key algorithm\n`;
|
||||
}
|
||||
|
||||
return chop(out);
|
||||
|
@ -135,45 +124,105 @@ function formatSubjectAlternativeNames(csr) {
|
|||
|
||||
/**
|
||||
* Format known extensions of a CSR
|
||||
* @param {*} csr CSR object
|
||||
* @returns Multi-line string describing attributes
|
||||
* @param {*} csrParam object
|
||||
* @returns Multi-line string describing CSR Requested Extensions
|
||||
*/
|
||||
function formatExtensions(csr) {
|
||||
let out = "\n";
|
||||
function formatRequestedExtensions(csrParam) {
|
||||
const formattedExtensions = new Array(4).fill("");
|
||||
|
||||
for (const attribute of csr.attributes) {
|
||||
for (const extension of attribute.extensions) {
|
||||
// formatted separately
|
||||
if (extension.name === "subjectAltName") {
|
||||
continue;
|
||||
}
|
||||
out += ` ${extension.name}${(extension.critical ? " CRITICAL" : "")}:\n`;
|
||||
if (Object.hasOwn(csrParam, "extreq")) {
|
||||
for (const extension of csrParam.extreq) {
|
||||
let parts = [];
|
||||
switch (extension.name) {
|
||||
switch (extension.extname) {
|
||||
case "basicConstraints" :
|
||||
parts = describeBasicConstraints(extension);
|
||||
formattedExtensions[0] = ` Basic Constraints:${formatExtensionCriticalTag(extension)}\n${indent(4, parts)}`;
|
||||
break;
|
||||
case "keyUsage" :
|
||||
parts = describeKeyUsage(extension);
|
||||
formattedExtensions[1] = ` Key Usage:${formatExtensionCriticalTag(extension)}\n${indent(4, parts)}`;
|
||||
break;
|
||||
case "extKeyUsage" :
|
||||
parts = describeExtendedKeyUsage(extension);
|
||||
formattedExtensions[2] = ` Extended Key Usage:${formatExtensionCriticalTag(extension)}\n${indent(4, parts)}`;
|
||||
break;
|
||||
case "subjectAltName" :
|
||||
parts = describeSubjectAlternativeName(extension);
|
||||
formattedExtensions[3] = ` Subject Alternative Name:${formatExtensionCriticalTag(extension)}\n${indent(4, parts)}`;
|
||||
break;
|
||||
default :
|
||||
parts = ["(unable to format extension)"];
|
||||
parts = ["(unsuported extension)"];
|
||||
formattedExtensions.push(` ${extension.extname}:${formatExtensionCriticalTag(extension)}\n${indent(4, parts)}`);
|
||||
}
|
||||
out += indent(4, parts);
|
||||
}
|
||||
}
|
||||
|
||||
let out = "\n";
|
||||
|
||||
formattedExtensions.forEach((formattedExtension) => {
|
||||
if (formattedExtension !== undefined && formattedExtension !== null && formattedExtension.length !== 0) {
|
||||
out += formattedExtension;
|
||||
}
|
||||
});
|
||||
|
||||
return chop(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format extension critical tag
|
||||
* @param {*} extension Object
|
||||
* @returns String describing whether the extension is critical or not
|
||||
*/
|
||||
function formatExtensionCriticalTag(extension) {
|
||||
return Object.hasOwn(extension, "critical") && extension.critical ? " critical" : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Format hex string onto multiple lines
|
||||
* Format string input as a comma separated hex string on multiple lines
|
||||
* @param {*} hex String
|
||||
* @returns Multi-line string describing the Hex input
|
||||
*/
|
||||
function formatHexOntoMultiLine(hex) {
|
||||
if (hex.length % 2 !== 0) {
|
||||
hex = "0" + hex;
|
||||
}
|
||||
|
||||
return formatMultiLine(chop(hex.replace(/(..)/g, "$&:")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert BigInt to abs value in Hex
|
||||
* @param {*} int BigInt
|
||||
* @returns String representing absolute value in Hex
|
||||
*/
|
||||
function absBigIntToHex(int) {
|
||||
int = int < 0n ? -int : int;
|
||||
|
||||
return ensureHexIsPositiveInTwosComplement(int.toString(16));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure Hex String remains positive in 2's complement
|
||||
* @param {*} hex String
|
||||
* @returns Hex String ensuring value remains positive in 2's complement
|
||||
*/
|
||||
function ensureHexIsPositiveInTwosComplement(hex) {
|
||||
if (hex.length % 2 !== 0) {
|
||||
return "0" + hex;
|
||||
}
|
||||
|
||||
// prepend 00 if most significant bit is 1 (sign bit)
|
||||
if (hex.length >=2 && (parseInt(hex.substring(0, 2), 16) & 128)) {
|
||||
hex = "00" + hex;
|
||||
}
|
||||
|
||||
return hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format string onto multiple lines
|
||||
* @param {*} longStr
|
||||
* @returns Hex string as a multi-line hex string
|
||||
* @returns String as a multi-line string
|
||||
*/
|
||||
function formatMultiLine(longStr) {
|
||||
const lines = [];
|
||||
|
@ -194,8 +243,8 @@ function formatMultiLine(longStr) {
|
|||
function describeBasicConstraints(extension) {
|
||||
const constraints = [];
|
||||
|
||||
constraints.push(`CA = ${extension.cA}`);
|
||||
if (extension.pathLenConstraint !== undefined) constraints.push(`PathLenConstraint = ${extension.pathLenConstraint}`);
|
||||
constraints.push(`CA = ${Object.hasOwn(extension, "cA") && extension.cA ? "true" : "false"}`);
|
||||
if (Object.hasOwn(extension, "pathLen")) constraints.push(`PathLenConstraint = ${extension.pathLen}`);
|
||||
|
||||
return constraints;
|
||||
}
|
||||
|
@ -209,15 +258,27 @@ function describeBasicConstraints(extension) {
|
|||
function describeKeyUsage(extension) {
|
||||
const usage = [];
|
||||
|
||||
if (extension.digitalSignature) usage.push("Digital signature");
|
||||
if (extension.nonRepudiation) usage.push("Non-repudiation");
|
||||
if (extension.keyEncipherment) usage.push("Key encipherment");
|
||||
if (extension.dataEncipherment) usage.push("Data encipherment");
|
||||
if (extension.keyAgreement) usage.push("Key agreement");
|
||||
if (extension.keyCertSign) usage.push("Key certificate signing");
|
||||
if (extension.cRLSign) usage.push("CRL signing");
|
||||
if (extension.encipherOnly) usage.push("Encipher only");
|
||||
if (extension.decipherOnly) usage.push("Decipher only");
|
||||
const kuIdentifierToName = {
|
||||
digitalSignature: "Digital Signature",
|
||||
nonRepudiation: "Non-repudiation",
|
||||
keyEncipherment: "Key encipherment",
|
||||
dataEncipherment: "Data encipherment",
|
||||
keyAgreement: "Key agreement",
|
||||
keyCertSign: "Key certificate signing",
|
||||
cRLSign: "CRL signing",
|
||||
encipherOnly: "Encipher Only",
|
||||
decipherOnly: "Decipher Only",
|
||||
};
|
||||
|
||||
if (Object.hasOwn(extension, "names")) {
|
||||
extension.names.forEach((ku) => {
|
||||
if (Object.hasOwn(kuIdentifierToName, ku)) {
|
||||
usage.push(kuIdentifierToName[ku]);
|
||||
} else {
|
||||
usage.push(`unknown key usage (${ku})`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (usage.length === 0) usage.push("(none)");
|
||||
|
||||
|
@ -233,23 +294,79 @@ function describeKeyUsage(extension) {
|
|||
function describeExtendedKeyUsage(extension) {
|
||||
const usage = [];
|
||||
|
||||
if (extension.serverAuth) usage.push("TLS Web Server Authentication");
|
||||
if (extension.clientAuth) usage.push("TLS Web Client Authentication");
|
||||
if (extension.codeSigning) usage.push("Code signing");
|
||||
if (extension.emailProtection) usage.push("E-mail Protection (S/MIME)");
|
||||
if (extension.timeStamping) usage.push("Trusted Timestamping");
|
||||
if (extension.msCodeInd) usage.push("Microsoft Individual Code Signing");
|
||||
if (extension.msCodeCom) usage.push("Microsoft Commercial Code Signing");
|
||||
if (extension.msCTLSign) usage.push("Microsoft Trust List Signing");
|
||||
if (extension.msSGC) usage.push("Microsoft Server Gated Crypto");
|
||||
if (extension.msEFS) usage.push("Microsoft Encrypted File System");
|
||||
if (extension.nsSGC) usage.push("Netscape Server Gated Crypto");
|
||||
const ekuIdentifierToName = {
|
||||
"serverAuth": "TLS Web Server Authentication",
|
||||
"clientAuth": "TLS Web Client Authentication",
|
||||
"codeSigning": "Code signing",
|
||||
"emailProtection": "E-mail Protection (S/MIME)",
|
||||
"timeStamping": "Trusted Timestamping",
|
||||
"1.3.6.1.4.1.311.2.1.21": "Microsoft Individual Code Signing", // msCodeInd
|
||||
"1.3.6.1.4.1.311.2.1.22": "Microsoft Commercial Code Signing", // msCodeCom
|
||||
"1.3.6.1.4.1.311.10.3.1": "Microsoft Trust List Signing", // msCTLSign
|
||||
"1.3.6.1.4.1.311.10.3.3": "Microsoft Server Gated Crypto", // msSGC
|
||||
"1.3.6.1.4.1.311.10.3.4": "Microsoft Encrypted File System", // msEFS
|
||||
"1.3.6.1.4.1.311.20.2.2": "Microsoft Smartcard Login", // msSmartcardLogin
|
||||
"2.16.840.1.113730.4.1": "Netscape Server Gated Crypto", // nsSGC
|
||||
};
|
||||
|
||||
if (Object.hasOwn(extension, "array")) {
|
||||
extension.array.forEach((eku) => {
|
||||
if (Object.hasOwn(ekuIdentifierToName, eku)) {
|
||||
usage.push(ekuIdentifierToName[eku]);
|
||||
} else {
|
||||
usage.push(eku);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (usage.length === 0) usage.push("(none)");
|
||||
|
||||
return usage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Subject Alternative Names from the name `subjectAltName` extension
|
||||
* @see RFC 5280 4.2.1.6. Subject Alternative Name https://www.ietf.org/rfc/rfc5280.txt
|
||||
* @param {*} extension object
|
||||
* @returns Array of strings describing Subject Alternative Name extension
|
||||
*/
|
||||
function describeSubjectAlternativeName(extension) {
|
||||
const names = [];
|
||||
|
||||
if (Object.hasOwn(extension, "extname") && extension.extname === "subjectAltName") {
|
||||
if (Object.hasOwn(extension, "array")) {
|
||||
for (const altName of extension.array) {
|
||||
Object.keys(altName).forEach((key) => {
|
||||
switch (key) {
|
||||
case "rfc822":
|
||||
names.push(`EMAIL: ${altName[key]}`);
|
||||
break;
|
||||
case "dns":
|
||||
names.push(`DNS: ${altName[key]}`);
|
||||
break;
|
||||
case "uri":
|
||||
names.push(`URI: ${altName[key]}`);
|
||||
break;
|
||||
case "ip":
|
||||
names.push(`IP: ${altName[key]}`);
|
||||
break;
|
||||
case "dn":
|
||||
names.push(`DIR: ${altName[key].str}`);
|
||||
break;
|
||||
case "other" :
|
||||
names.push(`Other: ${altName[key].oid}::${altName[key].value.utf8str.str}`);
|
||||
break;
|
||||
default:
|
||||
names.push(`(unable to format SAN '${key}':${altName[key]})\n`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join an array of strings and add leading spaces to each line.
|
||||
* @param {*} n How many leading spaces
|
||||
|
|
884
src/core/operations/ParseTLSRecord.mjs
Normal file
884
src/core/operations/ParseTLSRecord.mjs
Normal file
|
@ -0,0 +1,884 @@
|
|||
/**
|
||||
* @author c65722 []
|
||||
* @copyright Crown Copyright 2024
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import {toHexFast} from "../lib/Hex.mjs";
|
||||
import {objToTable} from "../lib/Protocol.mjs";
|
||||
import Stream from "../lib/Stream.mjs";
|
||||
|
||||
/**
|
||||
* Parse TLS record operation.
|
||||
*/
|
||||
class ParseTLSRecord extends Operation {
|
||||
|
||||
/**
|
||||
* ParseTLSRecord constructor.
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Parse TLS record";
|
||||
this.module = "Default";
|
||||
this.description = "Parses one or more TLS records";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Transport_Layer_Security";
|
||||
this.inputType = "ArrayBuffer";
|
||||
this.outputType = "json";
|
||||
this.presentType = "html";
|
||||
this.args = [];
|
||||
this._handshakeParser = new HandshakeParser();
|
||||
this._contentTypes = new Map();
|
||||
|
||||
for (const key in ContentType) {
|
||||
this._contentTypes[ContentType[key]] = key.toString().toLocaleLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ArrayBuffer} input - Stream, containing one or more raw TLS Records.
|
||||
* @param {Object[]} args
|
||||
* @returns {Object[]} Array of Object representations of TLS Records contained within input.
|
||||
*/
|
||||
run(input, args) {
|
||||
const s = new Stream(new Uint8Array(input));
|
||||
|
||||
const output = [];
|
||||
|
||||
while (s.hasMore()) {
|
||||
const record = this._readRecord(s);
|
||||
if (record) {
|
||||
output.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a TLS Record from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw TLS Record.
|
||||
* @returns {Object} Object representation of TLS Record.
|
||||
*/
|
||||
_readRecord(input) {
|
||||
const RECORD_HEADER_LEN = 5;
|
||||
|
||||
if (input.position + RECORD_HEADER_LEN > input.length) {
|
||||
input.moveTo(input.length);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const type = input.readInt(1);
|
||||
const typeString = this._contentTypes[type] ?? type.toString();
|
||||
const version = "0x" + toHexFast(input.getBytes(2));
|
||||
const length = input.readInt(2);
|
||||
const content = input.getBytes(length);
|
||||
const truncated = content.length < length;
|
||||
|
||||
const recordHeader = new RecordHeader(typeString, version, length, truncated);
|
||||
|
||||
if (!content.length) {
|
||||
return {...recordHeader};
|
||||
}
|
||||
|
||||
if (type === ContentType.HANDSHAKE) {
|
||||
return this._handshakeParser.parse(new Stream(content), recordHeader);
|
||||
}
|
||||
|
||||
const record = {...recordHeader};
|
||||
record.value = "0x" + toHexFast(content);
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the parsed TLS Records in a tabular style.
|
||||
*
|
||||
* @param {Object[]} data - Array of Object representations of the TLS Records.
|
||||
* @returns {html} HTML representation of TLS Records contained within data.
|
||||
*/
|
||||
present(data) {
|
||||
return data.map(r => objToTable(r)).join("\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
export default ParseTLSRecord;
|
||||
|
||||
/**
|
||||
* Repesents the known values of type field of a TLS Record header.
|
||||
*/
|
||||
const ContentType = Object.freeze({
|
||||
CHANGE_CIPHER_SPEC: 20,
|
||||
ALERT: 21,
|
||||
HANDSHAKE: 22,
|
||||
APPLICATION_DATA: 23,
|
||||
});
|
||||
|
||||
/**
|
||||
* Represents a TLS Record header
|
||||
*/
|
||||
class RecordHeader {
|
||||
/**
|
||||
* RecordHeader cosntructor.
|
||||
*
|
||||
* @param {string} type - String representation of TLS Record type field.
|
||||
* @param {string} version - Hex representation of TLS Record version field.
|
||||
* @param {int} length - Length of TLS Record.
|
||||
* @param {bool} truncated - Is TLS Record truncated.
|
||||
*/
|
||||
constructor(type, version, length, truncated) {
|
||||
this.type = type;
|
||||
this.version = version;
|
||||
this.length = length;
|
||||
|
||||
if (truncated) {
|
||||
this.truncated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake messages.
|
||||
*/
|
||||
class HandshakeParser {
|
||||
|
||||
/**
|
||||
* HandshakeParser constructor.
|
||||
*/
|
||||
constructor() {
|
||||
this._clientHelloParser = new ClientHelloParser();
|
||||
this._serverHelloParser = new ServerHelloParser();
|
||||
this._newSessionTicketParser = new NewSessionTicketParser();
|
||||
this._certificateParser = new CertificateParser();
|
||||
this._certificateRequestParser = new CertificateRequestParser();
|
||||
this._certificateVerifyParser = new CertificateVerifyParser();
|
||||
this._handshakeTypes = new Map();
|
||||
|
||||
for (const key in HandshakeType) {
|
||||
this._handshakeTypes[HandshakeType[key]] = key.toString().toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a single TLS handshake message.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw Handshake message.
|
||||
* @param {RecordHeader} recordHeader - TLS Record header.
|
||||
* @returns {Object} Object representation of Handshake.
|
||||
*/
|
||||
parse(input, recordHeader) {
|
||||
const output = {...recordHeader};
|
||||
|
||||
if (!input.hasMore()) {
|
||||
return output;
|
||||
}
|
||||
|
||||
const handshakeType = input.readInt(1);
|
||||
output.handshakeType = this._handshakeTypes[handshakeType] ?? handshakeType.toString();
|
||||
|
||||
if (input.position + 3 > input.length) {
|
||||
input.moveTo(input.length);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
const handshakeLength = input.readInt(3);
|
||||
|
||||
if (handshakeLength + 4 !== recordHeader.length) {
|
||||
input.moveTo(0);
|
||||
|
||||
output.handshakeType = this._handshakeTypes[HandshakeType.FINISHED];
|
||||
output.handshakeValue = "0x" + toHexFast(input.bytes);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
const content = input.getBytes(handshakeLength);
|
||||
if (!content.length) {
|
||||
return output;
|
||||
}
|
||||
|
||||
switch (handshakeType) {
|
||||
case HandshakeType.CLIENT_HELLO:
|
||||
return {...output, ...this._clientHelloParser.parse(new Stream(content))};
|
||||
case HandshakeType.SERVER_HELLO:
|
||||
return {...output, ...this._serverHelloParser.parse(new Stream(content))};
|
||||
case HandshakeType.NEW_SESSION_TICKET:
|
||||
return {...output, ...this._newSessionTicketParser.parse(new Stream(content))};
|
||||
case HandshakeType.CERTIFICATE:
|
||||
return {...output, ...this._certificateParser.parse(new Stream(content))};
|
||||
case HandshakeType.CERTIFICATE_REQUEST:
|
||||
return {...output, ...this._certificateRequestParser.parse(new Stream(content))};
|
||||
case HandshakeType.CERTIFICATE_VERIFY:
|
||||
return {...output, ...this._certificateVerifyParser.parse(new Stream(content))};
|
||||
default:
|
||||
output.handshakeValue = "0x" + toHexFast(content);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the known values of the msg_type field of a TLS Handshake message.
|
||||
*/
|
||||
const HandshakeType = Object.freeze({
|
||||
HELLO_REQUEST: 0,
|
||||
CLIENT_HELLO: 1,
|
||||
SERVER_HELLO: 2,
|
||||
NEW_SESSION_TICKET: 4,
|
||||
CERTIFICATE: 11,
|
||||
SERVER_KEY_EXCHANGE: 12,
|
||||
CERTIFICATE_REQUEST: 13,
|
||||
SERVER_HELLO_DONE: 14,
|
||||
CERTIFICATE_VERIFY: 15,
|
||||
CLIENT_KEY_EXCHANGE: 16,
|
||||
FINISHED: 20,
|
||||
});
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake ClientHello messages.
|
||||
*/
|
||||
class ClientHelloParser {
|
||||
|
||||
/**
|
||||
* ClientHelloParser constructor.
|
||||
*/
|
||||
constructor() {
|
||||
this._extensionsParser = new ExtensionsParser();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a single TLS Handshake ClientHello message.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ClientHello message.
|
||||
* @returns {Object} Object representation of ClientHello.
|
||||
*/
|
||||
parse(input) {
|
||||
const output = {};
|
||||
|
||||
output.clientVersion = this._readClientVersion(input);
|
||||
output.random = this._readRandom(input);
|
||||
|
||||
const sessionID = this._readSessionID(input);
|
||||
if (sessionID) {
|
||||
output.sessionID = sessionID;
|
||||
}
|
||||
|
||||
output.cipherSuites = this._readCipherSuites(input);
|
||||
output.compressionMethods = this._readCompressionMethods(input);
|
||||
output.extensions = this._readExtensions(input);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the client_version field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ClientHello message, with position before client_version field.
|
||||
* @returns {string} Hex representation of client_version.
|
||||
*/
|
||||
_readClientVersion(input) {
|
||||
return readBytesAsHex(input, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the random field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ClientHello message, with position before random field.
|
||||
* @returns {string} Hex representation of random.
|
||||
*/
|
||||
_readRandom(input) {
|
||||
return readBytesAsHex(input, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session_id field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ClientHello message, with position before session_id length field.
|
||||
* @returns {string} Hex representation of session_id, or empty string if session_id not present.
|
||||
*/
|
||||
_readSessionID(input) {
|
||||
return readSizePrefixedBytesAsHex(input, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the cipher_suites field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ClientHello message, with position before cipher_suites length field.
|
||||
* @returns {Object} Object represention of cipher_suites field.
|
||||
*/
|
||||
_readCipherSuites(input) {
|
||||
const output = {};
|
||||
|
||||
output.length = input.readInt(2);
|
||||
if (!output.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const cipherSuites = new Stream(input.getBytes(output.length));
|
||||
if (cipherSuites.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = [];
|
||||
|
||||
while (cipherSuites.hasMore()) {
|
||||
const cipherSuite = readBytesAsHex(cipherSuites, 2);
|
||||
if (cipherSuite) {
|
||||
output.values.push(cipherSuite);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the compression_methods field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ClientHello message, with position before compression_methods length field.
|
||||
* @returns {Object} Object representation of compression_methods field.
|
||||
*/
|
||||
_readCompressionMethods(input) {
|
||||
const output = {};
|
||||
|
||||
output.length = input.readInt(1);
|
||||
if (!output.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const compressionMethods = new Stream(input.getBytes(output.length));
|
||||
if (compressionMethods.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = [];
|
||||
|
||||
while (compressionMethods.hasMore()) {
|
||||
const compressionMethod = readBytesAsHex(compressionMethods, 1);
|
||||
if (compressionMethod) {
|
||||
output.values.push(compressionMethod);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the extensions field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ClientHello message, with position before extensions length field.
|
||||
* @returns {Object} Object representations of extensions field.
|
||||
*/
|
||||
_readExtensions(input) {
|
||||
const output = {};
|
||||
|
||||
output.length = input.readInt(2);
|
||||
if (!output.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const extensions = new Stream(input.getBytes(output.length));
|
||||
if (extensions.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = this._extensionsParser.parse(extensions);
|
||||
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake ServeHello messages.
|
||||
*/
|
||||
class ServerHelloParser {
|
||||
|
||||
/**
|
||||
* ServerHelloParser constructor.
|
||||
*/
|
||||
constructor() {
|
||||
this._extensionsParser = new ExtensionsParser();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a single TLS Handshake ServerHello message.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ServerHello message.
|
||||
* @return {Object} Object representation of ServerHello.
|
||||
*/
|
||||
parse(input) {
|
||||
const output = {};
|
||||
|
||||
output.serverVersion = this._readServerVersion(input);
|
||||
output.random = this._readRandom(input);
|
||||
|
||||
const sessionID = this._readSessionID(input);
|
||||
if (sessionID) {
|
||||
output.sessionID = sessionID;
|
||||
}
|
||||
|
||||
output.cipherSuite = this._readCipherSuite(input);
|
||||
output.compressionMethod = this._readCompressionMethod(input);
|
||||
output.extensions = this._readExtensions(input);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the server_version field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ServerHello message, with position before server_version field.
|
||||
* @returns {string} Hex representation of server_version.
|
||||
*/
|
||||
_readServerVersion(input) {
|
||||
return readBytesAsHex(input, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the random field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ServerHello message, with position before random field.
|
||||
* @returns {string} Hex representation of random.
|
||||
*/
|
||||
_readRandom(input) {
|
||||
return readBytesAsHex(input, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session_id field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ServertHello message, with position before session_id length field.
|
||||
* @returns {string} Hex representation of session_id, or empty string if session_id not present.
|
||||
*/
|
||||
_readSessionID(input) {
|
||||
return readSizePrefixedBytesAsHex(input, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the cipher_suite field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ServerHello message, with position before cipher_suite field.
|
||||
* @returns {string} Hex represention of cipher_suite.
|
||||
*/
|
||||
_readCipherSuite(input) {
|
||||
return readBytesAsHex(input, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the compression_method field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ServerHello message, with position before compression_method field.
|
||||
* @returns {string} Hex represention of compression_method.
|
||||
*/
|
||||
_readCompressionMethod(input) {
|
||||
return readBytesAsHex(input, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the extensions field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw ServerHello message, with position before extensions length field.
|
||||
* @returns {Object} Object representation of extensions field.
|
||||
*/
|
||||
_readExtensions(input) {
|
||||
const output = {};
|
||||
|
||||
output.length = input.readInt(2);
|
||||
if (!output.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const extensions = new Stream(input.getBytes(output.length));
|
||||
if (extensions.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = this._extensionsParser.parse(extensions);
|
||||
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake Hello Extensions.
|
||||
*/
|
||||
class ExtensionsParser {
|
||||
|
||||
/**
|
||||
* Parses a stream of TLS Handshake Hello Extensions.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing multiple raw Extensions, with position before first extension length field.
|
||||
* @returns {Object[]} Array of Object representations of Extensions contained within input.
|
||||
*/
|
||||
parse(input) {
|
||||
const output = [];
|
||||
|
||||
while (input.hasMore()) {
|
||||
const extension = this._readExtension(input);
|
||||
if (extension) {
|
||||
output.push(extension);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a single Extension from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a list of Extensions, with position before the length field of the next Extension.
|
||||
* @returns {Object} Object representation of Extension.
|
||||
*/
|
||||
_readExtension(input) {
|
||||
const output = {};
|
||||
|
||||
if (input.position + 4 > input.length) {
|
||||
input.moveTo(input.length);
|
||||
return null;
|
||||
}
|
||||
|
||||
output.type = "0x" + toHexFast(input.getBytes(2));
|
||||
output.length = input.readInt(2);
|
||||
if (!output.length) {
|
||||
return output;
|
||||
}
|
||||
|
||||
const value = input.getBytes(output.length);
|
||||
if (!value || value.length !== output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
if (value && value.length) {
|
||||
output.value = "0x" + toHexFast(value);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake NewSessionTicket messages.
|
||||
*/
|
||||
class NewSessionTicketParser {
|
||||
|
||||
/**
|
||||
* Parses a single TLS Handshake NewSessionTicket message.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw NewSessionTicket message.
|
||||
* @returns {Object} Object representation of NewSessionTicket.
|
||||
*/
|
||||
parse(input) {
|
||||
return {
|
||||
ticketLifetimeHint: this._readTicketLifetimeHint(input),
|
||||
ticket: this._readTicket(input),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the ticket_lifetime_hint field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw NewSessionTicket message, with position before ticket_lifetime_hint field.
|
||||
* @returns {string} Lifetime hint, in seconds.
|
||||
*/
|
||||
_readTicketLifetimeHint(input) {
|
||||
if (input.position + 4 > input.length) {
|
||||
input.moveTo(input.length);
|
||||
return "";
|
||||
}
|
||||
|
||||
return input.readInt(4) + "s";
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the ticket field fromt the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw NewSessionTicket message, with position before ticket length field.
|
||||
* @returns {string} Hex representation of ticket.
|
||||
*/
|
||||
_readTicket(input) {
|
||||
return readSizePrefixedBytesAsHex(input, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake Certificate messages.
|
||||
*/
|
||||
class CertificateParser {
|
||||
|
||||
/**
|
||||
* Parses a single TLS Handshake Certificate message.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw Certificate message.
|
||||
* @returns {Object} Object representation of Certificate.
|
||||
*/
|
||||
parse(input) {
|
||||
const output = {};
|
||||
|
||||
output.certificateList = this._readCertificateList(input);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the certificate_list field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw Certificate message, with position before certificate_list length field.
|
||||
* @returns {string[]} Array of strings, each containing a hex representation of a value within the certificate_list field.
|
||||
*/
|
||||
_readCertificateList(input) {
|
||||
const output = {};
|
||||
|
||||
if (input.position + 3 > input.length) {
|
||||
input.moveTo(input.length);
|
||||
return output;
|
||||
}
|
||||
|
||||
output.length = input.readInt(3);
|
||||
if (!output.length) {
|
||||
return output;
|
||||
}
|
||||
|
||||
const certificates = new Stream(input.getBytes(output.length));
|
||||
if (certificates.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = [];
|
||||
|
||||
while (certificates.hasMore()) {
|
||||
const certificate = this._readCertificate(certificates);
|
||||
if (certificate) {
|
||||
output.values.push(certificate);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a single certificate from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a list of certificicates, with position before the length field of the next certificate.
|
||||
* @returns {string} Hex representation of certificate.
|
||||
*/
|
||||
_readCertificate(input) {
|
||||
return readSizePrefixedBytesAsHex(input, 3);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake CertificateRequest messages.
|
||||
*/
|
||||
class CertificateRequestParser {
|
||||
|
||||
/**
|
||||
* Parses a single TLS Handshake CertificateRequest message.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateRequest message.
|
||||
* @return {Object} Object representation of CertificateRequest.
|
||||
*/
|
||||
parse(input) {
|
||||
const output = {};
|
||||
|
||||
output.certificateTypes = this._readCertificateTypes(input);
|
||||
output.supportedSignatureAlgorithms = this._readSupportedSignatureAlgorithms(input);
|
||||
|
||||
const certificateAuthorities = this._readCertificateAuthorities(input);
|
||||
if (certificateAuthorities.length) {
|
||||
output.certificateAuthorities = certificateAuthorities;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the certificate_types field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateRequest message, with position before certificate_types length field.
|
||||
* @return {string[]} Array of strings, each containing a hex representation of a value within the certificate_types field.
|
||||
*/
|
||||
_readCertificateTypes(input) {
|
||||
const output = {};
|
||||
|
||||
output.length = input.readInt(1);
|
||||
if (!output.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const certificateTypes = new Stream(input.getBytes(output.length));
|
||||
if (certificateTypes.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = [];
|
||||
|
||||
while (certificateTypes.hasMore()) {
|
||||
const certificateType = readBytesAsHex(certificateTypes, 1);
|
||||
if (certificateType) {
|
||||
output.values.push(certificateType);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the supported_signature_algorithms field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateRequest message, with position before supported_signature_algorithms length field.
|
||||
* @returns {string[]} Array of strings, each containing a hex representation of a value within the supported_signature_algorithms field.
|
||||
*/
|
||||
_readSupportedSignatureAlgorithms(input) {
|
||||
const output = {};
|
||||
|
||||
output.length = input.readInt(2);
|
||||
if (!output.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const signatureAlgorithms = new Stream(input.getBytes(output.length));
|
||||
if (signatureAlgorithms.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = [];
|
||||
|
||||
while (signatureAlgorithms.hasMore()) {
|
||||
const signatureAlgorithm = readBytesAsHex(signatureAlgorithms, 2);
|
||||
if (signatureAlgorithm) {
|
||||
output.values.push(signatureAlgorithm);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the certificate_authorities field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateRequest message, with position before certificate_authorities length field.
|
||||
* @returns {string[]} Array of strings, each containing a hex representation of a value within the certificate_authorities field.
|
||||
*/
|
||||
_readCertificateAuthorities(input) {
|
||||
const output = {};
|
||||
|
||||
output.length = input.readInt(2);
|
||||
if (!output.length) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const certificateAuthorities = new Stream(input.getBytes(output.length));
|
||||
if (certificateAuthorities.length < output.length) {
|
||||
output.truncated = true;
|
||||
}
|
||||
|
||||
output.values = [];
|
||||
|
||||
while (certificateAuthorities.hasMore()) {
|
||||
const certificateAuthority = this._readCertificateAuthority(certificateAuthorities);
|
||||
if (certificateAuthority) {
|
||||
output.values.push(certificateAuthority);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a single certificate authority from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a list of raw certificate authorities, with position before the length field of the next certificate authority.
|
||||
* @returns {string} Hex representation of certificate authority.
|
||||
*/
|
||||
_readCertificateAuthority(input) {
|
||||
return readSizePrefixedBytesAsHex(input, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses TLS Handshake CertificateVerify messages.
|
||||
*/
|
||||
class CertificateVerifyParser {
|
||||
|
||||
/**
|
||||
* Parses a single CertificateVerify Message.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateVerify message.
|
||||
* @returns {Object} Object representation of CertificateVerify.
|
||||
*/
|
||||
parse(input) {
|
||||
return {
|
||||
algorithmHash: this._readAlgorithmHash(input),
|
||||
algorithmSignature: this._readAlgorithmSignature(input),
|
||||
signature: this._readSignature(input),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the algorithm.hash field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateVerify message, with position before algorithm.hash field.
|
||||
* @return {string} Hex representation of hash algorithm.
|
||||
*/
|
||||
_readAlgorithmHash(input) {
|
||||
return readBytesAsHex(input, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the algorithm.signature field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateVerify message, with position before algorithm.signature field.
|
||||
* @return {string} Hex representation of signature algorithm.
|
||||
*/
|
||||
_readAlgorithmSignature(input) {
|
||||
return readBytesAsHex(input, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the signature field from the following bytes in the provided Stream.
|
||||
*
|
||||
* @param {Stream} input - Stream, containing a raw CertificateVerify message, with position before signature field.
|
||||
* @return {string} Hex representation of signature.
|
||||
*/
|
||||
_readSignature(input) {
|
||||
return readSizePrefixedBytesAsHex(input, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the following size prefixed bytes from the provided Stream, and reuturn as a hex string.
|
||||
*
|
||||
* @param {Stream} input - Stream to read from.
|
||||
* @param {int} sizePrefixLength - Length of the size prefix field.
|
||||
* @returns {string} Hex representation of bytes read from Stream, empty string is returned if
|
||||
* field cannot be read in full.
|
||||
*/
|
||||
function readSizePrefixedBytesAsHex(input, sizePrefixLength) {
|
||||
const length = input.readInt(sizePrefixLength);
|
||||
if (!length) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return readBytesAsHex(input, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read n bytes from the provided Stream, and return as a hex string.
|
||||
*
|
||||
* @param {Stream} input - Stream to read from.
|
||||
* @param {int} n - Number of bytes to read.
|
||||
* @returns {string} Hex representation of bytes read from Stream, or empty string if field cannot
|
||||
* be read in full.
|
||||
*/
|
||||
function readBytesAsHex(input, n) {
|
||||
const bytes = input.getBytes(n);
|
||||
if (!bytes || bytes.length !== n) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return "0x" + toHexFast(bytes);
|
||||
}
|
391
src/core/operations/ParseX509CRL.mjs
Normal file
391
src/core/operations/ParseX509CRL.mjs
Normal file
|
@ -0,0 +1,391 @@
|
|||
/**
|
||||
* @author robinsandhu
|
||||
* @copyright Crown Copyright 2024
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import r from "jsrsasign";
|
||||
import Operation from "../Operation.mjs";
|
||||
import { fromBase64 } from "../lib/Base64.mjs";
|
||||
import { toHex } from "../lib/Hex.mjs";
|
||||
import { formatDnObj } from "../lib/PublicKey.mjs";
|
||||
import OperationError from "../errors/OperationError.mjs";
|
||||
import Utils from "../Utils.mjs";
|
||||
|
||||
/**
|
||||
* Parse X.509 CRL operation
|
||||
*/
|
||||
class ParseX509CRL extends Operation {
|
||||
|
||||
/**
|
||||
* ParseX509CRL constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Parse X.509 CRL";
|
||||
this.module = "PublicKey";
|
||||
this.description = "Parse Certificate Revocation List (CRL)";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Certificate_revocation_list";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
this.args = [
|
||||
{
|
||||
"name": "Input format",
|
||||
"type": "option",
|
||||
"value": ["PEM", "DER Hex", "Base64", "Raw"]
|
||||
}
|
||||
];
|
||||
this.checks = [
|
||||
{
|
||||
"pattern": "^-+BEGIN X509 CRL-+\\r?\\n[\\da-z+/\\n\\r]+-+END X509 CRL-+\\r?\\n?$",
|
||||
"flags": "i",
|
||||
"args": ["PEM"]
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} input
|
||||
* @param {Object[]} args
|
||||
* @returns {string} Human-readable description of a Certificate Revocation List (CRL).
|
||||
*/
|
||||
run(input, args) {
|
||||
if (!input.length) {
|
||||
return "No input";
|
||||
}
|
||||
|
||||
const inputFormat = args[0];
|
||||
|
||||
let undefinedInputFormat = false;
|
||||
try {
|
||||
switch (inputFormat) {
|
||||
case "DER Hex":
|
||||
input = input.replace(/\s/g, "").toLowerCase();
|
||||
break;
|
||||
case "PEM":
|
||||
break;
|
||||
case "Base64":
|
||||
input = toHex(fromBase64(input, null, "byteArray"), "");
|
||||
break;
|
||||
case "Raw":
|
||||
input = toHex(Utils.strToArrayBuffer(input), "");
|
||||
break;
|
||||
default:
|
||||
undefinedInputFormat = true;
|
||||
}
|
||||
} catch (e) {
|
||||
throw "Certificate load error (non-certificate input?)";
|
||||
}
|
||||
if (undefinedInputFormat) throw "Undefined input format";
|
||||
|
||||
const crl = new r.X509CRL(input);
|
||||
|
||||
let out = `Certificate Revocation List (CRL):
|
||||
Version: ${crl.getVersion() === null ? "1 (0x0)" : "2 (0x1)"}
|
||||
Signature Algorithm: ${crl.getSignatureAlgorithmField()}
|
||||
Issuer:\n${formatDnObj(crl.getIssuer(), 8)}
|
||||
Last Update: ${generalizedDateTimeToUTC(crl.getThisUpdate())}
|
||||
Next Update: ${generalizedDateTimeToUTC(crl.getNextUpdate())}\n`;
|
||||
|
||||
if (crl.getParam().ext !== undefined) {
|
||||
out += `\tCRL extensions:\n${formatCRLExtensions(crl.getParam().ext, 8)}\n`;
|
||||
}
|
||||
|
||||
out += `Revoked Certificates:\n${formatRevokedCertificates(crl.getRevCertArray(), 4)}
|
||||
Signature Value:\n${formatCRLSignature(crl.getSignatureValueHex(), 8)}`;
|
||||
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generalized date time string to UTC.
|
||||
* @param {string} datetime
|
||||
* @returns UTC datetime string.
|
||||
*/
|
||||
function generalizedDateTimeToUTC(datetime) {
|
||||
// Ensure the string is in the correct format
|
||||
if (!/^\d{12,14}Z$/.test(datetime)) {
|
||||
throw new OperationError(`failed to format datetime string ${datetime}`);
|
||||
}
|
||||
|
||||
// Extract components
|
||||
let centuary = "20";
|
||||
if (datetime.length === 15) {
|
||||
centuary = datetime.substring(0, 2);
|
||||
datetime = datetime.slice(2);
|
||||
}
|
||||
const year = centuary + datetime.substring(0, 2);
|
||||
const month = datetime.substring(2, 4);
|
||||
const day = datetime.substring(4, 6);
|
||||
const hour = datetime.substring(6, 8);
|
||||
const minute = datetime.substring(8, 10);
|
||||
const second = datetime.substring(10, 12);
|
||||
|
||||
// Construct ISO 8601 format string
|
||||
const isoString = `${year}-${month}-${day}T${hour}:${minute}:${second}Z`;
|
||||
|
||||
// Parse using standard Date object
|
||||
const isoDateTime = new Date(isoString);
|
||||
|
||||
return isoDateTime.toUTCString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Format CRL extensions.
|
||||
* @param {r.ExtParam[] | undefined} extensions
|
||||
* @param {Number} indent
|
||||
* @returns Formatted string detailing CRL extensions.
|
||||
*/
|
||||
function formatCRLExtensions(extensions, indent) {
|
||||
if (Array.isArray(extensions) === false || extensions.length === 0) {
|
||||
return indentString(`No CRL extensions.`, indent);
|
||||
}
|
||||
|
||||
let out = ``;
|
||||
|
||||
extensions.sort((a, b) => {
|
||||
if (!Object.hasOwn(a, "extname") || !Object.hasOwn(b, "extname")) {
|
||||
return 0;
|
||||
}
|
||||
if (a.extname < b.extname) {
|
||||
return -1;
|
||||
} else if (a.extname === b.extname) {
|
||||
return 0;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
});
|
||||
|
||||
extensions.forEach((ext) => {
|
||||
if (!Object.hasOwn(ext, "extname")) {
|
||||
throw new OperationError(`CRL entry extension object missing 'extname' key: ${ext}`);
|
||||
}
|
||||
switch (ext.extname) {
|
||||
case "authorityKeyIdentifier":
|
||||
out += `X509v3 Authority Key Identifier:\n`;
|
||||
if (Object.hasOwn(ext, "kid")) {
|
||||
out += `\tkeyid:${colonDelimitedHexFormatString(ext.kid.hex.toUpperCase())}\n`;
|
||||
}
|
||||
if (Object.hasOwn(ext, "issuer")) {
|
||||
out += `\tDirName:${ext.issuer.str}\n`;
|
||||
}
|
||||
if (Object.hasOwn(ext, "sn")) {
|
||||
out += `\tserial:${colonDelimitedHexFormatString(ext.sn.hex.toUpperCase())}\n`;
|
||||
}
|
||||
break;
|
||||
case "cRLDistributionPoints":
|
||||
out += `X509v3 CRL Distribution Points:\n`;
|
||||
ext.array.forEach((distPoint) => {
|
||||
const fullName = `Full Name:\n${formatGeneralNames(distPoint.dpname.full, 4)}`;
|
||||
out += indentString(fullName, 4) + "\n";
|
||||
});
|
||||
break;
|
||||
case "cRLNumber":
|
||||
if (!Object.hasOwn(ext, "num")) {
|
||||
throw new OperationError(`'cRLNumber' CRL entry extension missing 'num' key: ${ext}`);
|
||||
}
|
||||
out += `X509v3 CRL Number:\n\t${ext.num.hex.toUpperCase()}\n`;
|
||||
break;
|
||||
case "issuerAltName":
|
||||
out += `X509v3 Issuer Alternative Name:\n${formatGeneralNames(ext.array, 4)}\n`;
|
||||
break;
|
||||
default:
|
||||
out += `${ext.extname}:\n`;
|
||||
out += `\tUnsupported CRL extension. Try openssl CLI.\n`;
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return indentString(chop(out), indent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format general names array.
|
||||
* @param {Object[]} names
|
||||
* @returns Multi-line formatted string describing all supported general name types.
|
||||
*/
|
||||
function formatGeneralNames(names, indent) {
|
||||
let out = ``;
|
||||
|
||||
names.forEach((name) => {
|
||||
const key = Object.keys(name)[0];
|
||||
|
||||
switch (key) {
|
||||
case "ip":
|
||||
out += `IP:${name.ip}\n`;
|
||||
break;
|
||||
case "dns":
|
||||
out += `DNS:${name.dns}\n`;
|
||||
break;
|
||||
case "uri":
|
||||
out += `URI:${name.uri}\n`;
|
||||
break;
|
||||
case "rfc822":
|
||||
out += `EMAIL:${name.rfc822}\n`;
|
||||
break;
|
||||
case "dn":
|
||||
out += `DIR:${name.dn.str}\n`;
|
||||
break;
|
||||
case "other":
|
||||
out += `OtherName:${name.other.oid}::${Object.values(name.other.value)[0].str}\n`;
|
||||
break;
|
||||
default:
|
||||
out += `${key}: unsupported general name type`;
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return indentString(chop(out), indent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Colon-delimited hex formatted output.
|
||||
* @param {string} hexString Hex String
|
||||
* @returns String representing input hex string with colon delimiter.
|
||||
*/
|
||||
function colonDelimitedHexFormatString(hexString) {
|
||||
if (hexString.length % 2 !== 0) {
|
||||
hexString = "0" + hexString;
|
||||
}
|
||||
|
||||
return chop(hexString.replace(/(..)/g, "$&:"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Format revoked certificates array
|
||||
* @param {r.RevokedCertificate[] | null} revokedCertificates
|
||||
* @param {Number} indent
|
||||
* @returns Multi-line formatted string output of revoked certificates array
|
||||
*/
|
||||
function formatRevokedCertificates(revokedCertificates, indent) {
|
||||
if (Array.isArray(revokedCertificates) === false || revokedCertificates.length === 0) {
|
||||
return indentString("No Revoked Certificates.", indent);
|
||||
}
|
||||
|
||||
let out=``;
|
||||
|
||||
revokedCertificates.forEach((revCert) => {
|
||||
if (!Object.hasOwn(revCert, "sn") || !Object.hasOwn(revCert, "date")) {
|
||||
throw new OperationError("invalid revoked certificate object, missing either serial number or date");
|
||||
}
|
||||
|
||||
out += `Serial Number: ${revCert.sn.hex.toUpperCase()}
|
||||
Revocation Date: ${generalizedDateTimeToUTC(revCert.date)}\n`;
|
||||
if (Object.hasOwn(revCert, "ext") && Array.isArray(revCert.ext) && revCert.ext.length !== 0) {
|
||||
out += `\tCRL entry extensions:\n${indentString(formatCRLEntryExtensions(revCert.ext), 2*indent)}\n`;
|
||||
}
|
||||
});
|
||||
|
||||
return indentString(chop(out), indent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format CRL entry extensions.
|
||||
* @param {Object[]} exts
|
||||
* @returns Formatted multi-line string describing CRL entry extensions.
|
||||
*/
|
||||
function formatCRLEntryExtensions(exts) {
|
||||
let out = ``;
|
||||
|
||||
const crlReasonCodeToReasonMessage = {
|
||||
0: "Unspecified",
|
||||
1: "Key Compromise",
|
||||
2: "CA Compromise",
|
||||
3: "Affiliation Changed",
|
||||
4: "Superseded",
|
||||
5: "Cessation Of Operation",
|
||||
6: "Certificate Hold",
|
||||
8: "Remove From CRL",
|
||||
9: "Privilege Withdrawn",
|
||||
10: "AA Compromise",
|
||||
};
|
||||
|
||||
const holdInstructionOIDToName = {
|
||||
"1.2.840.10040.2.1": "Hold Instruction None",
|
||||
"1.2.840.10040.2.2": "Hold Instruction Call Issuer",
|
||||
"1.2.840.10040.2.3": "Hold Instruction Reject",
|
||||
};
|
||||
|
||||
exts.forEach((ext) => {
|
||||
if (!Object.hasOwn(ext, "extname")) {
|
||||
throw new OperationError(`CRL entry extension object missing 'extname' key: ${ext}`);
|
||||
}
|
||||
switch (ext.extname) {
|
||||
case "cRLReason":
|
||||
if (!Object.hasOwn(ext, "code")) {
|
||||
throw new OperationError(`'cRLReason' CRL entry extension missing 'code' key: ${ext}`);
|
||||
}
|
||||
out += `X509v3 CRL Reason Code:
|
||||
${Object.hasOwn(crlReasonCodeToReasonMessage, ext.code) ? crlReasonCodeToReasonMessage[ext.code] : `invalid reason code: ${ext.code}`}\n`;
|
||||
break;
|
||||
case "2.5.29.23": // Hold instruction
|
||||
out += `Hold Instruction Code:\n\t${Object.hasOwn(holdInstructionOIDToName, ext.extn.oid) ? holdInstructionOIDToName[ext.extn.oid] : `${ext.extn.oid}: unknown hold instruction OID`}\n`;
|
||||
break;
|
||||
case "2.5.29.24": // Invalidity Date
|
||||
out += `Invalidity Date:\n\t${generalizedDateTimeToUTC(ext.extn.gentime.str)}\n`;
|
||||
break;
|
||||
default:
|
||||
out += `${ext.extname}:\n`;
|
||||
out += `\tUnsupported CRL entry extension. Try openssl CLI.\n`;
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return chop(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format CRL signature.
|
||||
* @param {String} sigHex
|
||||
* @param {Number} indent
|
||||
* @returns String representing hex signature value formatted on multiple lines.
|
||||
*/
|
||||
function formatCRLSignature(sigHex, indent) {
|
||||
if (sigHex.length % 2 !== 0) {
|
||||
sigHex = "0" + sigHex;
|
||||
}
|
||||
|
||||
return indentString(formatMultiLine(chop(sigHex.replace(/(..)/g, "$&:"))), indent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format string onto multiple lines.
|
||||
* @param {string} longStr
|
||||
* @returns String as a multi-line string.
|
||||
*/
|
||||
function formatMultiLine(longStr) {
|
||||
const lines = [];
|
||||
|
||||
for (let remain = longStr ; remain !== "" ; remain = remain.substring(54)) {
|
||||
lines.push(remain.substring(0, 54));
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Indent a multi-line string by n spaces.
|
||||
* @param {string} input String
|
||||
* @param {number} spaces How many leading spaces
|
||||
* @returns Indented string.
|
||||
*/
|
||||
function indentString(input, spaces) {
|
||||
const indent = " ".repeat(spaces);
|
||||
return input.replace(/^/gm, indent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove last character from a string.
|
||||
* @param {string} s String
|
||||
* @returns Chopped string.
|
||||
*/
|
||||
function chop(s) {
|
||||
if (s.length < 1) {
|
||||
return s;
|
||||
}
|
||||
return s.substring(0, s.length - 1);
|
||||
}
|
||||
|
||||
export default ParseX509CRL;
|
|
@ -59,15 +59,16 @@ class ROT13 extends Operation {
|
|||
rot13Upperacse = args[1],
|
||||
rotNumbers = args[2];
|
||||
let amount = args[3],
|
||||
chr;
|
||||
amountNumbers = args[3];
|
||||
|
||||
if (amount) {
|
||||
if (amount < 0) {
|
||||
amount = 26 - (Math.abs(amount) % 26);
|
||||
amountNumbers = 10 - (Math.abs(amountNumbers) % 10);
|
||||
}
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
chr = input[i];
|
||||
let chr = input[i];
|
||||
if (rot13Upperacse && chr >= 65 && chr <= 90) { // Upper case
|
||||
chr = (chr - 65 + amount) % 26;
|
||||
output[i] = chr + 65;
|
||||
|
@ -75,7 +76,7 @@ class ROT13 extends Operation {
|
|||
chr = (chr - 97 + amount) % 26;
|
||||
output[i] = chr + 97;
|
||||
} else if (rotNumbers && chr >= 48 && chr <= 57) { // Numbers
|
||||
chr = (chr - 48 + amount) % 10;
|
||||
chr = (chr - 48 + amountNumbers) % 10;
|
||||
output[i] = chr + 48;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -60,7 +60,7 @@ class RSASign extends Operation {
|
|||
const privateKey = forge.pki.decryptRsaPrivateKey(key, password);
|
||||
// Generate message hash
|
||||
const md = MD_ALGORITHMS[mdAlgo].create();
|
||||
md.update(input, "utf8");
|
||||
md.update(input, "raw");
|
||||
// Sign message hash
|
||||
const sig = privateKey.sign(md);
|
||||
return sig;
|
||||
|
|
|
@ -8,6 +8,7 @@ import Operation from "../Operation.mjs";
|
|||
import OperationError from "../errors/OperationError.mjs";
|
||||
import forge from "node-forge";
|
||||
import { MD_ALGORITHMS } from "../lib/RSA.mjs";
|
||||
import Utils from "../Utils.mjs";
|
||||
|
||||
/**
|
||||
* RSA Verify operation
|
||||
|
@ -37,6 +38,11 @@ class RSAVerify extends Operation {
|
|||
type: "text",
|
||||
value: ""
|
||||
},
|
||||
{
|
||||
name: "Message format",
|
||||
type: "option",
|
||||
value: ["Raw", "Hex", "Base64"]
|
||||
},
|
||||
{
|
||||
name: "Message Digest Algorithm",
|
||||
type: "option",
|
||||
|
@ -51,7 +57,7 @@ class RSAVerify extends Operation {
|
|||
* @returns {string}
|
||||
*/
|
||||
run(input, args) {
|
||||
const [pemKey, message, mdAlgo] = args;
|
||||
const [pemKey, message, format, mdAlgo] = args;
|
||||
if (pemKey.replace("-----BEGIN RSA PUBLIC KEY-----", "").length === 0) {
|
||||
throw new OperationError("Please enter a public key.");
|
||||
}
|
||||
|
@ -60,7 +66,8 @@ class RSAVerify extends Operation {
|
|||
const pubKey = forge.pki.publicKeyFromPem(pemKey);
|
||||
// Generate message digest
|
||||
const md = MD_ALGORITHMS[mdAlgo].create();
|
||||
md.update(message, "utf8");
|
||||
const messageStr = Utils.convertToByteString(message, format);
|
||||
md.update(messageStr, "raw");
|
||||
// Compare signed message digest and generated message digest
|
||||
const result = pubKey.verify(md.digest().bytes(), input);
|
||||
return result ? "Verified OK" : "Verification Failure";
|
||||
|
|
57
src/core/operations/StripIPv4Header.mjs
Normal file
57
src/core/operations/StripIPv4Header.mjs
Normal file
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
* @author c65722 []
|
||||
* @copyright Crown Copyright 2024
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import OperationError from "../errors/OperationError.mjs";
|
||||
import Stream from "../lib/Stream.mjs";
|
||||
|
||||
/**
|
||||
* Strip IPv4 header operation
|
||||
*/
|
||||
class StripIPv4Header extends Operation {
|
||||
|
||||
/**
|
||||
* StripIPv4Header constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Strip IPv4 header";
|
||||
this.module = "Default";
|
||||
this.description = "Strips the IPv4 header from an IPv4 packet, outputting the payload.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/IPv4";
|
||||
this.inputType = "ArrayBuffer";
|
||||
this.outputType = "ArrayBuffer";
|
||||
this.args = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ArrayBuffer} input
|
||||
* @param {Object[]} args
|
||||
* @returns {ArrayBuffer}
|
||||
*/
|
||||
run(input, args) {
|
||||
const MIN_HEADER_LEN = 20;
|
||||
|
||||
const s = new Stream(new Uint8Array(input));
|
||||
if (s.length < MIN_HEADER_LEN) {
|
||||
throw new OperationError("Input length is less than minimum IPv4 header length");
|
||||
}
|
||||
|
||||
const ihl = s.readInt(1) & 0x0f;
|
||||
const dataOffsetBytes = ihl * 4;
|
||||
if (s.length < dataOffsetBytes) {
|
||||
throw new OperationError("Input length is less than IHL");
|
||||
}
|
||||
|
||||
s.moveTo(dataOffsetBytes);
|
||||
|
||||
return s.getBytes().buffer;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default StripIPv4Header;
|
60
src/core/operations/StripTCPHeader.mjs
Normal file
60
src/core/operations/StripTCPHeader.mjs
Normal file
|
@ -0,0 +1,60 @@
|
|||
/**
|
||||
* @author c65722 []
|
||||
* @copyright Crown Copyright 2024
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import OperationError from "../errors/OperationError.mjs";
|
||||
import Stream from "../lib/Stream.mjs";
|
||||
|
||||
/**
|
||||
* Strip TCP header operation
|
||||
*/
|
||||
class StripTCPHeader extends Operation {
|
||||
|
||||
/**
|
||||
* StripTCPHeader constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Strip TCP header";
|
||||
this.module = "Default";
|
||||
this.description = "Strips the TCP header from a TCP segment, outputting the payload.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Transmission_Control_Protocol";
|
||||
this.inputType = "ArrayBuffer";
|
||||
this.outputType = "ArrayBuffer";
|
||||
this.args = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ArrayBuffer} input
|
||||
* @param {Object[]} args
|
||||
* @returns {ArrayBuffer}
|
||||
*/
|
||||
run(input, args) {
|
||||
const MIN_HEADER_LEN = 20;
|
||||
const DATA_OFFSET_OFFSET = 12;
|
||||
const DATA_OFFSET_LEN_BITS = 4;
|
||||
|
||||
const s = new Stream(new Uint8Array(input));
|
||||
if (s.length < MIN_HEADER_LEN) {
|
||||
throw new OperationError("Need at least 20 bytes for a TCP Header");
|
||||
}
|
||||
|
||||
s.moveTo(DATA_OFFSET_OFFSET);
|
||||
const dataOffsetWords = s.readBits(DATA_OFFSET_LEN_BITS);
|
||||
const dataOffsetBytes = dataOffsetWords * 4;
|
||||
if (s.length < dataOffsetBytes) {
|
||||
throw new OperationError("Input length is less than data offset");
|
||||
}
|
||||
|
||||
s.moveTo(dataOffsetBytes);
|
||||
|
||||
return s.getBytes().buffer;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default StripTCPHeader;
|
51
src/core/operations/StripUDPHeader.mjs
Normal file
51
src/core/operations/StripUDPHeader.mjs
Normal file
|
@ -0,0 +1,51 @@
|
|||
/**
|
||||
* @author c65722 []
|
||||
* @copyright Crown Copyright 2024
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import Stream from "../lib/Stream.mjs";
|
||||
import OperationError from "../errors/OperationError.mjs";
|
||||
|
||||
/**
|
||||
* Strip UDP header operation
|
||||
*/
|
||||
class StripUDPHeader extends Operation {
|
||||
|
||||
/**
|
||||
* StripUDPHeader constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Strip UDP header";
|
||||
this.module = "Default";
|
||||
this.description = "Strips the UDP header from a UDP datagram, outputting the payload.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/User_Datagram_Protocol";
|
||||
this.inputType = "ArrayBuffer";
|
||||
this.outputType = "ArrayBuffer";
|
||||
this.args = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ArrayBuffer} input
|
||||
* @param {Object[]} args
|
||||
* @returns {ArrayBuffer}
|
||||
*/
|
||||
run(input, args) {
|
||||
const HEADER_LEN = 8;
|
||||
|
||||
const s = new Stream(new Uint8Array(input));
|
||||
if (s.length < HEADER_LEN) {
|
||||
throw new OperationError("Need 8 bytes for a UDP Header");
|
||||
}
|
||||
|
||||
s.moveTo(HEADER_LEN);
|
||||
|
||||
return s.getBytes().buffer;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default StripUDPHeader;
|
79
src/core/operations/TakeNthBytes.mjs
Normal file
79
src/core/operations/TakeNthBytes.mjs
Normal file
|
@ -0,0 +1,79 @@
|
|||
/**
|
||||
* @author Oshawk [oshawk@protonmail.com]
|
||||
* @copyright Crown Copyright 2019
|
||||
* @license Apache-2.0
|
||||
*/
|
||||
|
||||
import Operation from "../Operation.mjs";
|
||||
import OperationError from "../errors/OperationError.mjs";
|
||||
|
||||
/**
|
||||
* Take nth bytes operation
|
||||
*/
|
||||
class TakeNthBytes extends Operation {
|
||||
|
||||
/**
|
||||
* TakeNthBytes constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "Take nth bytes";
|
||||
this.module = "Default";
|
||||
this.description = "Takes every nth byte starting with a given byte.";
|
||||
this.infoURL = "";
|
||||
this.inputType = "byteArray";
|
||||
this.outputType = "byteArray";
|
||||
this.args = [
|
||||
{
|
||||
name: "Take every",
|
||||
type: "number",
|
||||
value: 4
|
||||
},
|
||||
{
|
||||
name: "Starting at",
|
||||
type: "number",
|
||||
value: 0
|
||||
},
|
||||
{
|
||||
name: "Apply to each line",
|
||||
type: "boolean",
|
||||
value: false
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {byteArray} input
|
||||
* @param {Object[]} args
|
||||
* @returns {byteArray}
|
||||
*/
|
||||
run(input, args) {
|
||||
const n = args[0];
|
||||
const start = args[1];
|
||||
const eachLine = args[2];
|
||||
|
||||
if (parseInt(n, 10) !== n || n <= 0) {
|
||||
throw new OperationError("'Take every' must be a positive integer.");
|
||||
}
|
||||
if (parseInt(start, 10) !== start || start < 0) {
|
||||
throw new OperationError("'Starting at' must be a positive or zero integer.");
|
||||
}
|
||||
|
||||
let offset = 0;
|
||||
const output = [];
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
if (eachLine && input[i] === 0x0a) {
|
||||
output.push(0x0a);
|
||||
offset = i + 1;
|
||||
} else if (i - offset >= start && (i - (start + offset)) % n === 0) {
|
||||
output.push(input[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default TakeNthBytes;
|
|
@ -22,7 +22,7 @@ class TripleDESDecrypt extends Operation {
|
|||
|
||||
this.name = "Triple DES Decrypt";
|
||||
this.module = "Ciphers";
|
||||
this.description = "Triple DES applies DES three times to each block to increase key size.<br><br><b>Key:</b> Triple DES uses a key length of 24 bytes (192 bits).<br>DES uses a key length of 8 bytes (64 bits).<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used as a default.";
|
||||
this.description = "Triple DES applies DES three times to each block to increase key size.<br><br><b>Key:</b> Triple DES uses a key length of 24 bytes (192 bits).<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used as a default.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Triple_DES";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
|
@ -73,8 +73,7 @@ class TripleDESDecrypt extends Operation {
|
|||
if (key.length !== 24 && key.length !== 16) {
|
||||
throw new OperationError(`Invalid key length: ${key.length} bytes
|
||||
|
||||
Triple DES uses a key length of 24 bytes (192 bits).
|
||||
DES uses a key length of 8 bytes (64 bits).`);
|
||||
Triple DES uses a key length of 24 bytes (192 bits).`);
|
||||
}
|
||||
if (iv.length !== 8 && mode !== "ECB") {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes
|
||||
|
|
|
@ -22,7 +22,7 @@ class TripleDESEncrypt extends Operation {
|
|||
|
||||
this.name = "Triple DES Encrypt";
|
||||
this.module = "Ciphers";
|
||||
this.description = "Triple DES applies DES three times to each block to increase key size.<br><br><b>Key:</b> Triple DES uses a key length of 24 bytes (192 bits).<br>DES uses a key length of 8 bytes (64 bits).<br><br>You can generate a password-based key using one of the KDF operations.<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used.";
|
||||
this.description = "Triple DES applies DES three times to each block to increase key size.<br><br><b>Key:</b> Triple DES uses a key length of 24 bytes (192 bits).<br><br>You can generate a password-based key using one of the KDF operations.<br><br><b>IV:</b> The Initialization Vector should be 8 bytes long. If not entered, it will default to 8 null bytes.<br><br><b>Padding:</b> In CBC and ECB mode, PKCS#7 padding will be used.";
|
||||
this.infoURL = "https://wikipedia.org/wiki/Triple_DES";
|
||||
this.inputType = "string";
|
||||
this.outputType = "string";
|
||||
|
@ -72,8 +72,7 @@ class TripleDESEncrypt extends Operation {
|
|||
if (key.length !== 24 && key.length !== 16) {
|
||||
throw new OperationError(`Invalid key length: ${key.length} bytes
|
||||
|
||||
Triple DES uses a key length of 24 bytes (192 bits).
|
||||
DES uses a key length of 8 bytes (64 bits).`);
|
||||
Triple DES uses a key length of 24 bytes (192 bits).`);
|
||||
}
|
||||
if (iv.length !== 8 && mode !== "ECB") {
|
||||
throw new OperationError(`Invalid IV length: ${iv.length} bytes
|
||||
|
|
|
@ -23,7 +23,7 @@ const dir = path.join(`${process.cwd()}/src/node`);
|
|||
if (!fs.existsSync(dir)) {
|
||||
console.log("\nCWD: " + process.cwd());
|
||||
console.log("Error: generateNodeIndex.mjs should be run from the project root");
|
||||
console.log("Example> node --experimental-modules src/core/config/scripts/generateNodeIndex.mjs");
|
||||
console.log("Example> node --experimental-modules src/node/config/scripts/generateNodeIndex.mjs");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
|
3
src/web/App.mjs
Executable file → Normal file
3
src/web/App.mjs
Executable file → Normal file
|
@ -60,6 +60,7 @@ class App {
|
|||
|
||||
this.initialiseSplitter();
|
||||
this.loadLocalStorage();
|
||||
this.manager.options.applyPreferredColorScheme();
|
||||
this.populateOperationsList();
|
||||
this.manager.setup();
|
||||
this.manager.output.saveBombe();
|
||||
|
@ -536,6 +537,8 @@ class App {
|
|||
// Read in theme from URI params
|
||||
if (this.uriParams.theme) {
|
||||
this.manager.options.changeTheme(Utils.escapeHtml(this.uriParams.theme));
|
||||
} else {
|
||||
this.manager.options.applyPreferredColorScheme();
|
||||
}
|
||||
|
||||
window.dispatchEvent(this.manager.statechange);
|
||||
|
|
8
src/web/waiters/OptionsWaiter.mjs
Executable file → Normal file
8
src/web/waiters/OptionsWaiter.mjs
Executable file → Normal file
|
@ -163,6 +163,14 @@ class OptionsWaiter {
|
|||
themeSelect.selectedIndex = themeSelect.querySelector(`option[value="${theme}"`).index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the user's preferred color scheme using the `prefers-color-scheme` media query.
|
||||
*/
|
||||
applyPreferredColorScheme() {
|
||||
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
const theme = prefersDarkScheme ? "dark" : "classic";
|
||||
this.changeTheme(theme);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the console logging level.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue