diff --git a/CHANGELOG.md b/CHANGELOG.md index ddff4460..e9fbb154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,24 @@ All major and minor version changes will be documented in this file. Details of ## Details +### [10.18.0] - 2024-04-24 +- Added 'XXTEA Encrypt' and 'XXTEA Decrypt' operations [@n1474335] | [0a353ee] + +### [10.17.0] - 2024-04-13 +- Fix unit test 'expectOutput' implementation [@zb3] | [#1783] +- Add accessibility labels for icons [@e218736] | [#1743] +- Add focus styling for keyboard navigation [@e218736] | [#1739] +- Add support for operation option hiding [@TheZ3ro] | [#541] +- Improve efficiency of RAKE implementation [@sw5678] | [#1751] +- Require (a, 26) to be coprime in 'Affine Encode' [@EvieHarv] | [#1788] +- Added 'JWK to PEM' operation [@cplussharp] | [#1277] +- Added 'PEM to JWK' operation [@cplussharp] | [#1277] +- Added 'Public Key from Certificate' operation [@cplussharp] | [#1642] +- Added 'Public Key from Private Key' operation [@cplussharp] | [#1642] + +### [10.16.0] - 2024-04-12 +- Added 'JA4Server Fingerprint' operation [@n1474335] | [#1789] + ### [10.15.0] - 2024-04-02 - Fix Ciphersaber2 key concatenation [@zb3] | [#1765] - Fix DeriveEVPKey's array parsing [@zb3] | [#1767] @@ -418,6 +436,9 @@ All major and minor version changes will be documented in this file. Details of ## [4.0.0] - 2016-11-28 - Initial open source commit [@n1474335] | [b1d73a72](https://github.com/gchq/CyberChef/commit/b1d73a725dc7ab9fb7eb789296efd2b7e4b08306) +[10.18.0]: https://github.com/gchq/CyberChef/releases/tag/v10.18.0 +[10.17.0]: https://github.com/gchq/CyberChef/releases/tag/v10.17.0 +[10.16.0]: https://github.com/gchq/CyberChef/releases/tag/v10.16.0 [10.15.0]: https://github.com/gchq/CyberChef/releases/tag/v10.15.0 [10.14.0]: https://github.com/gchq/CyberChef/releases/tag/v10.14.0 [10.13.0]: https://github.com/gchq/CyberChef/releases/tag/v10.13.0 @@ -598,6 +619,10 @@ All major and minor version changes will be documented in this file. Details of [@zb3]: https://github.com/zb3 [@jkataja]: https://github.com/jkataja [@tomgond]: https://github.com/tomgond +[@e218736]: https://github.com/e218736 +[@TheZ3ro]: https://github.com/TheZ3ro +[@EvieHarv]: https://github.com/EvieHarv +[@cplussharp]: https://github.com/cplussharp [8ad18b]: https://github.com/gchq/CyberChef/commit/8ad18bc7db6d9ff184ba3518686293a7685bf7b7 @@ -609,6 +634,7 @@ All major and minor version changes will be documented in this file. Details of [31a7f83]: https://github.com/gchq/CyberChef/commit/31a7f83b82e78927f89689f323fcb9185144d6ff [760eff4]: https://github.com/gchq/CyberChef/commit/760eff49b5307aaa3104c5e5b437ffe62299acd1 [65ffd8d]: https://github.com/gchq/CyberChef/commit/65ffd8d65d88eb369f6f61a5d1d0f807179bffb7 +[0a353ee]: https://github.com/gchq/CyberChef/commit/0a353eeb378b9ca5d49e23c7dfc175ae07107b08 [#95]: https://github.com/gchq/CyberChef/pull/299 [#173]: https://github.com/gchq/CyberChef/pull/173 @@ -725,7 +751,7 @@ All major and minor version changes will be documented in this file. Details of [#1667]: https://github.com/gchq/CyberChef/issues/1667 [#1555]: https://github.com/gchq/CyberChef/issues/1555 [#1694]: https://github.com/gchq/CyberChef/issues/1694 -[#1699]: https://github.com/gchq/CyberChef/issues/1694 +[#1699]: https://github.com/gchq/CyberChef/issues/1699 [#1757]: https://github.com/gchq/CyberChef/issues/1757 [#1752]: https://github.com/gchq/CyberChef/issues/1752 [#1753]: https://github.com/gchq/CyberChef/issues/1753 @@ -740,6 +766,9 @@ All major and minor version changes will be documented in this file. Details of [#1765]: https://github.com/gchq/CyberChef/issues/1765 [#1767]: https://github.com/gchq/CyberChef/issues/1767 [#1769]: https://github.com/gchq/CyberChef/issues/1769 +[#1759]: https://github.com/gchq/CyberChef/issues/1759 [#1504]: https://github.com/gchq/CyberChef/issues/1504 [#512]: https://github.com/gchq/CyberChef/issues/512 [#1732]: https://github.com/gchq/CyberChef/issues/1732 +[#1789]: https://github.com/gchq/CyberChef/issues/1789 + diff --git a/Gruntfile.js b/Gruntfile.js index 32ba9007..b040d98d 100755 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -86,10 +86,12 @@ module.exports = function (grunt) { // Project configuration - const compileTime = grunt.template.today("UTC:dd/mm/yyyy HH:MM:ss") + " UTC", + const compileYear = grunt.template.today("UTC:yyyy"), + compileTime = grunt.template.today("UTC:dd/mm/yyyy HH:MM:ss") + " UTC", pkg = grunt.file.readJSON("package.json"), webpackConfig = require("./webpack.config.js"), BUILD_CONSTANTS = { + COMPILE_YEAR: JSON.stringify(compileYear), COMPILE_TIME: JSON.stringify(compileTime), COMPILE_MSG: JSON.stringify(grunt.option("compile-msg") || grunt.option("msg") || ""), PKG_VERSION: JSON.stringify(pkg.version), @@ -125,6 +127,7 @@ module.exports = function (grunt) { filename: "index.html", template: "./src/web/html/index.html", chunks: ["main"], + compileYear: compileYear, compileTime: compileTime, version: pkg.version, minify: { @@ -227,6 +230,7 @@ module.exports = function (grunt) { filename: "index.html", template: "./src/web/html/index.html", chunks: ["main"], + compileYear: compileYear, compileTime: compileTime, version: pkg.version, }) diff --git a/package-lock.json b/package-lock.json index 693e0d42..3603be54 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cyberchef", - "version": "10.15.0", + "version": "10.18.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cyberchef", - "version": "10.15.0", + "version": "10.18.7", "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { @@ -115,7 +115,7 @@ "babel-plugin-dynamic-import-node": "^2.3.3", "babel-plugin-transform-builtin-extend": "1.1.2", "base64-loader": "^1.0.0", - "chromedriver": "^122.0.0", + "chromedriver": "^123.0.4", "cli-progress": "^3.12.0", "colors": "^1.4.0", "copy-webpack-plugin": "^12.0.2", @@ -4744,9 +4744,9 @@ } }, "node_modules/chromedriver": { - "version": "122.0.6", - "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-122.0.6.tgz", - "integrity": "sha512-Q0r+QlUtiJWMQ5HdYaFa0CtBmLFq3n5JWfmq9mOC00UMBvWxku09gUkvBt457QnYfTM/XHqY/HTFOxHvATnTmA==", + "version": "123.0.4", + "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-123.0.4.tgz", + "integrity": "sha512-3Yi7y7q35kkSAOTbRisiww/SL2w+DqafDPAaUShpSuLMmPaOvHQR0i3bm2/33QBiQ8fUb1J/MzppzVL6IDqvhA==", "dev": true, "hasInstallScript": true, "dependencies": { diff --git a/package.json b/package.json index ef61fbab..ce80b4d0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cyberchef", - "version": "10.15.0", + "version": "10.18.7", "description": "The Cyber Swiss Army Knife for encryption, encoding, compression and data analysis.", "author": "n1474335 ", "homepage": "https://gchq.github.io/CyberChef", @@ -55,7 +55,7 @@ "babel-plugin-dynamic-import-node": "^2.3.3", "babel-plugin-transform-builtin-extend": "1.1.2", "base64-loader": "^1.0.0", - "chromedriver": "^122.0.0", + "chromedriver": "^123.0.4", "cli-progress": "^3.12.0", "colors": "^1.4.0", "copy-webpack-plugin": "^12.0.2", @@ -96,6 +96,7 @@ "@babel/polyfill": "^7.12.1", "@blu3r4y/lzma": "^2.3.3", "@wavesenterprise/crypto-gost-js": "^2.1.0-RC1", + "@xmldom/xmldom": "^0.8.0", "argon2-browser": "^1.18.0", "arrive": "^2.4.1", "avsc": "^5.7.7", @@ -122,12 +123,12 @@ "escodegen": "^2.1.0", "esprima": "^4.0.1", "exif-parser": "^0.1.12", - "ieee754": "^1.1.13", "fernet": "^0.3.2", "file-saver": "^2.0.5", "flat": "^6.0.1", "geodesy": "1.1.3", "highlight.js": "^11.9.0", + "ieee754": "^1.1.13", "jimp": "^0.16.13", "jquery": "3.7.1", "js-crc": "^0.2.0", @@ -175,7 +176,6 @@ "unorm": "^1.6.0", "utf8": "^3.0.0", "vkbeautify": "^0.99.3", - "@xmldom/xmldom": "^0.8.0", "xpath": "0.0.34", "xregexp": "^5.1.1", "zlibjs": "^0.3.1" diff --git a/src/core/Utils.mjs b/src/core/Utils.mjs index 18b0e688..a9c381d7 100755 --- a/src/core/Utils.mjs +++ b/src/core/Utils.mjs @@ -893,7 +893,7 @@ class Utils { /** - * Converts a string to it's title case equivalent. + * Converts a string to its title case equivalent. * * @param {string} str * @returns string diff --git a/src/core/config/Categories.json b/src/core/config/Categories.json index e81d8ca1..59492887 100644 --- a/src/core/config/Categories.json +++ b/src/core/config/Categories.json @@ -117,6 +117,8 @@ "XOR Brute Force", "Vigenère Encode", "Vigenère Decode", + "XXTEA Encrypt", + "XXTEA Decrypt", "To Morse Code", "From Morse Code", "Bacon Cipher Encode", @@ -155,8 +157,7 @@ "Typex", "Lorenz", "Colossus", - "SIGABA", - "XXTEA" + "SIGABA" ] }, { @@ -168,6 +169,8 @@ "Hex to PEM", "Hex to Object Identifier", "Object Identifier to Hex", + "PEM to JWK", + "JWK to PEM", "Generate PGP Key Pair", "PGP Encrypt", "PGP Decrypt", @@ -179,8 +182,14 @@ "RSA Verify", "RSA Encrypt", "RSA Decrypt", + "Generate ECDSA Key Pair", + "ECDSA Signature Conversion", + "ECDSA Sign", + "ECDSA Verify", "Parse SSH Host Key", - "Parse CSR" + "Parse CSR", + "Public Key from Certificate", + "Public Key from Private Key" ] }, { @@ -238,6 +247,7 @@ "JA3 Fingerprint", "JA3S Fingerprint", "JA4 Fingerprint", + "JA4Server Fingerprint", "HASSH Client Fingerprint", "HASSH Server Fingerprint", "Format MAC addresses", @@ -389,7 +399,6 @@ "SHA2", "SHA3", "SM3", - "MurmurHash3", "Keccak", "Shake", "RIPEMD", @@ -414,6 +423,7 @@ "Scrypt", "NT Hash", "LM Hash", + "MurmurHash3", "Fletcher-8 Checksum", "Fletcher-16 Checksum", "Fletcher-32 Checksum", diff --git a/src/core/config/scripts/newOperation.mjs b/src/core/config/scripts/newOperation.mjs index fddeff97..1686f6eb 100644 --- a/src/core/config/scripts/newOperation.mjs +++ b/src/core/config/scripts/newOperation.mjs @@ -147,7 +147,7 @@ class ${moduleName} extends Operation { this.name = "${result.opName}"; this.module = "${result.module}"; this.description = "${(new EscapeString).run(result.description, ["Special chars", "Double"])}"; - this.infoURL = "${result.infoURL}"; + this.infoURL = "${result.infoURL}"; // Usually a Wikipedia link. Remember to remove localisation (i.e. https://wikipedia.org/etc rather than https://en.wikipedia.org/etc) this.inputType = "${result.inputType}"; this.outputType = "${result.outputType}"; this.args = [ diff --git a/src/core/lib/Ciphers.mjs b/src/core/lib/Ciphers.mjs index a4d174b5..6266a8e1 100644 --- a/src/core/lib/Ciphers.mjs +++ b/src/core/lib/Ciphers.mjs @@ -3,6 +3,7 @@ * * @author Matt C [matt@artemisbot.uk] * @author n1474335 [n1474335@gmail.com] + * @author Evie H [evie@evie.sh] * * @copyright Crown Copyright 2018 * @license Apache-2.0 @@ -10,6 +11,7 @@ */ import OperationError from "../errors/OperationError.mjs"; +import Utils from "../Utils.mjs"; import CryptoJS from "crypto-js"; /** @@ -30,6 +32,10 @@ export function affineEncode(input, args) { throw new OperationError("The values of a and b can only be integers."); } + if (Utils.gcd(a, 26) !== 1) { + throw new OperationError("The value of `a` must be coprime to 26."); + } + for (let i = 0; i < input.length; i++) { if (alphabet.indexOf(input[i]) >= 0) { // Uses the affine function ax+b % m = y (where m is length of the alphabet) diff --git a/src/core/lib/FileSignatures.mjs b/src/core/lib/FileSignatures.mjs index 69157a1b..22132823 100644 --- a/src/core/lib/FileSignatures.mjs +++ b/src/core/lib/FileSignatures.mjs @@ -81,7 +81,7 @@ export const FILE_SIGNATURES = { 0: 0x00, 1: 0x00, 2: 0x00, - // 3 could be 0x24 or 0x18, so skip it + 3: [0x24, 0x18], 4: 0x66, // ftypheic 5: 0x74, 6: 0x79, @@ -2748,7 +2748,7 @@ export function extractGIF(bytes, offset) { stream.moveForwardsBy(11); // Loop until next Graphic Control Extension. - while (stream.getBytes(2) !== [0x21, 0xf9]) { + while (!Array.from(stream.getBytes(2)).equals([0x21, 0xf9])) { stream.moveBackwardsBy(2); stream.moveForwardsBy(stream.readInt(1)); if (!stream.readInt(1)) diff --git a/src/core/lib/JA4.mjs b/src/core/lib/JA4.mjs index b0b423a2..5e606f46 100644 --- a/src/core/lib/JA4.mjs +++ b/src/core/lib/JA4.mjs @@ -25,6 +25,9 @@ export function toJA4(bytes) { let tlsr = {}; try { tlsr = parseTLSRecord(bytes); + if (tlsr.handshake.value.handshakeType.value !== 0x01) { + throw new Error(); + } } catch (err) { throw new OperationError("Data is not a valid TLS Client Hello. QUIC is not yet supported.\n" + err); } @@ -48,16 +51,7 @@ export function toJA4(bytes) { break; } } - switch (version) { - case 0x0304: version = "13"; break; // TLS 1.3 - case 0x0303: version = "12"; break; // TLS 1.2 - case 0x0302: version = "11"; break; // TLS 1.1 - case 0x0301: version = "10"; break; // TLS 1.0 - case 0x0300: version = "s3"; break; // SSL 3.0 - case 0x0200: version = "s2"; break; // SSL 2.0 - case 0x0100: version = "s1"; break; // SSL 1.0 - default: version = "00"; // Unknown - } + version = tlsVersionMapper(version); /* SNI If the SNI extension (0x0000) exists, then the destination of the connection is a domain, or “d” in the fingerprint. @@ -99,6 +93,7 @@ export function toJA4(bytes) { if (ext.type.value === "application_layer_protocol_negotiation") { alpn = parseFirstALPNValue(ext.value.data); alpn = alpn.charAt(0) + alpn.charAt(alpn.length - 1); + if (alpn.charCodeAt(0) > 127) alpn = "99"; break; } } @@ -164,3 +159,106 @@ export function toJA4(bytes) { "JA4_ro": `${ptype}${version}${sni}${cipherLen}${extLen}${alpn}_${originalCiphersRaw}_${originalExtensionsRaw}`, }; } + + +/** + * Calculate the JA4Server from a given TLS Server Hello Stream + * @param {Uint8Array} bytes + * @returns {string} + */ +export function toJA4S(bytes) { + let tlsr = {}; + try { + tlsr = parseTLSRecord(bytes); + if (tlsr.handshake.value.handshakeType.value !== 0x02) { + throw new Error(); + } + } catch (err) { + throw new OperationError("Data is not a valid TLS Server Hello. QUIC is not yet supported.\n" + err); + } + + /* QUIC + “q” or “t”, which denotes whether the hello packet is for QUIC or TCP. + TODO: Implement QUIC + */ + const ptype = "t"; + + /* TLS Version + TLS version is shown in 3 different places. If extension 0x002b exists (supported_versions), then the version + is the highest value in the extension. Remember to ignore GREASE values. If the extension doesn’t exist, then + 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; + for (const ext of tlsr.handshake.value.extensions.value) { + if (ext.type.value === "supported_versions") { + version = parseHighestSupportedVersion(ext.value.data); + break; + } + } + version = tlsVersionMapper(version); + + /* Number of Extensions + 2 character number of cipher suites, so if there’s 6 cipher suites in the hello packet, then the value should be “06”. + If there’s > 99, which there should never be, then output “99”. + */ + let extLen = tlsr.handshake.value.extensions.value.length; + extLen = extLen > 99 ? "99" : extLen.toString().padStart(2, "0"); + + /* ALPN Extension Chosen Value + The first and last characters of the ALPN (Application-Layer Protocol Negotiation) first value. + If there are no ALPN values or no ALPN extension then we print “00” as the value in the fingerprint. + */ + let alpn = "00"; + for (const ext of tlsr.handshake.value.extensions.value) { + if (ext.type.value === "application_layer_protocol_negotiation") { + alpn = parseFirstALPNValue(ext.value.data); + alpn = alpn.charAt(0) + alpn.charAt(alpn.length - 1); + if (alpn.charCodeAt(0) > 127) alpn = "99"; + break; + } + } + + /* Chosen Cipher + The hex value of the chosen cipher suite + */ + const cipher = toHexFast(tlsr.handshake.value.cipherSuite.data); + + /* Extension hash + A 12 character truncated sha256 hash of the list of extensions. + The extension list is created using the 4 character hex values of the extensions, lower case, comma delimited. + */ + const extensionsList = []; + for (const ext of tlsr.handshake.value.extensions.value) { + extensionsList.push(toHexFast(ext.type.data)); + } + const extensionsRaw = extensionsList.join(","); + const extensionsHash = runHash( + "sha256", + Utils.strToArrayBuffer(extensionsRaw) + ).substring(0, 12); + + return { + "JA4S": `${ptype}${version}${extLen}${alpn}_${cipher}_${extensionsHash}`, + "JA4S_r": `${ptype}${version}${extLen}${alpn}_${cipher}_${extensionsRaw}`, + }; +} + + +/** + * Takes a TLS version value and returns a JA4 TLS version string + * @param {Uint8Array} version - Two byte array of version number + * @returns {string} + */ +function tlsVersionMapper(version) { + switch (version) { + case 0x0304: return "13"; // TLS 1.3 + case 0x0303: return "12"; // TLS 1.2 + case 0x0302: return "11"; // TLS 1.1 + case 0x0301: return "10"; // TLS 1.0 + case 0x0300: return "s3"; // SSL 3.0 + case 0x0200: return "s2"; // SSL 2.0 + case 0x0100: return "s1"; // SSL 1.0 + default: return "00"; // Unknown + } +} diff --git a/src/core/lib/TLS.mjs b/src/core/lib/TLS.mjs index e3f18eb3..6373bfa2 100644 --- a/src/core/lib/TLS.mjs +++ b/src/core/lib/TLS.mjs @@ -70,13 +70,11 @@ function parseHandshake(bytes) { // Handshake type h.handshakeType = { - description: "Client Hello", + description: "Handshake Type", length: 1, data: b.getBytes(1), value: s.readInt(1) }; - if (h.handshakeType.value !== 0x01) - throw new OperationError("Not a Client Hello."); // Handshake length h.handshakeLength = { @@ -86,8 +84,33 @@ function parseHandshake(bytes) { value: s.readInt(3) }; if (s.length !== h.handshakeLength.value + 4) - throw new OperationError("Not enough data in Client Hello."); + throw new OperationError("Not enough data in Handshake message."); + + switch (h.handshakeType.value) { + case 0x01: + h.handshakeType.description = "Client Hello"; + parseClientHello(s, b, h); + break; + case 0x02: + h.handshakeType.description = "Server Hello"; + parseServerHello(s, b, h); + break; + default: + throw new OperationError("Not a known handshake message."); + } + + return h; +} + +/** + * Parse a TLS Client Hello + * @param {Stream} s + * @param {Stream} b + * @param {Object} h + * @returns {JSON} + */ +function parseClientHello(s, b, h) { // Hello version h.helloVersion = { description: "Client Hello Version", @@ -171,6 +194,79 @@ function parseHandshake(bytes) { return h; } +/** + * Parse a TLS Server Hello + * @param {Stream} s + * @param {Stream} b + * @param {Object} h + * @returns {JSON} + */ +function parseServerHello(s, b, h) { + // Hello version + h.helloVersion = { + description: "Server Hello Version", + length: 2, + data: b.getBytes(2), + value: s.readInt(2) + }; + + // Random + h.random = { + description: "Server Random", + length: 32, + data: b.getBytes(32), + value: s.getBytes(32) + }; + + // Session ID Length + h.sessionIDLength = { + description: "Session ID Length", + length: 1, + data: b.getBytes(1), + value: s.readInt(1) + }; + + // Session ID + h.sessionID = { + description: "Session ID", + length: h.sessionIDLength.value, + data: b.getBytes(h.sessionIDLength.value), + value: s.getBytes(h.sessionIDLength.value) + }; + + // Cipher Suite + h.cipherSuite = { + description: "Selected Cipher Suite", + length: 2, + data: b.getBytes(2), + value: CIPHER_SUITES_LOOKUP[s.readInt(2)] || "Unknown" + }; + + // Compression Method + h.compressionMethod = { + description: "Selected Compression Method", + length: 1, + data: b.getBytes(1), + value: s.readInt(1) // TODO: Compression method name here + }; + + // Extensions Length + h.extensionsLength = { + description: "Extensions Length", + length: 2, + data: b.getBytes(2), + value: s.readInt(2) + }; + + // Extensions + h.extensions = { + description: "Extensions", + length: h.extensionsLength.value, + data: b.getBytes(h.extensionsLength.value), + value: parseExtensions(s.getBytes(h.extensionsLength.value)) + }; +} + /** * Parse Cipher Suites * @param {Uint8Array} bytes @@ -748,6 +844,11 @@ export const GREASE_VALUES = [ export function parseHighestSupportedVersion(bytes) { const s = new Stream(bytes); + // The Server Hello supported_versions extension simply contains the chosen version + if (s.length === 2) { + return s.readInt(2); + } + // Length let i = s.readInt(1); diff --git a/src/core/lib/XXTEA.mjs b/src/core/lib/XXTEA.mjs new file mode 100644 index 00000000..6d556fc5 --- /dev/null +++ b/src/core/lib/XXTEA.mjs @@ -0,0 +1,174 @@ +/** + * XXTEA library + * + * Encryption Algorithm Authors: + * David J. Wheeler + * Roger M. Needham + * + * @author Ma Bingyao [mabingyao@gmail.com] + * @author n1474335 [n1474335@gmail.com] + * @license MIT + */ + +const DELTA = 0x9E3779B9; + +/** + * Convert a buffer to a Uint8Array + * @param {Uint32Array} v + * @param {boolean} includeLength + * @returns {Uint8Array} + */ +function toUint8Array(v, includeLength) { + const length = v.length; + let n = length << 2; + if (includeLength) { + const m = v[length - 1]; + n -= 4; + if ((m < n - 3) || (m > n)) { + return null; + } + n = m; + } + const bytes = new Uint8Array(n); + for (let i = 0; i < n; i++) { + bytes[i] = v[i >> 2] >> ((i & 3) << 3); + } + return bytes; +} + +/** + * Convert a buffer to a Uint32Array + * @param {TypedArray} bs + * @param {boolean} includeLength + * @returns {Uint32Array} + */ +function toUint32Array(bs, includeLength) { + const length = bs.length; + let n = length >> 2; + if ((length & 3) !== 0) { + ++n; + } + let v; + if (includeLength) { + v = new Uint32Array(n + 1); + v[n] = length; + } else { + v = new Uint32Array(n); + } + for (let i = 0; i < length; ++i) { + v[i >> 2] |= bs[i] << ((i & 3) << 3); + } + return v; +} + +/** + * Mask an int to 32 bits + * @param {number} i + * @returns {number} + */ +function int32(i) { + return i & 0xFFFFFFFF; +} + +/** + * MX function for data randomisation + * @param {number} sum + * @param {number} y + * @param {number} z + * @param {number} p + * @param {number} e + * @param {number} k + * @returns {number} + */ +function mx(sum, y, z, p, e, k) { + return ((z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4)) ^ ((sum ^ y) + (k[p & 3 ^ e] ^ z)); +} + +/** + * Ensure an array is a multiple of 16 bits + * @param {TypedArray} k + * @returns {TypedArray} + */ +function fixk(k) { + if (k.length < 16) { + const key = new Uint8Array(16); + key.set(k); + return key; + } + return k; +} + +/** + * Performs XXTEA encryption on a Uint32Array + * @param {Uint32Array} v + * @param {Uint32Array} k + * @returns {Uint32Array} + */ +function encryptUint32Array(v, k) { + const length = v.length; + const n = length - 1; + let y, z, sum, e, p, q; + z = v[n]; + sum = 0; + for (q = Math.floor(6 + 52 / length) | 0; q > 0; --q) { + sum = int32(sum + DELTA); + e = sum >>> 2 & 3; + for (p = 0; p < n; ++p) { + y = v[p + 1]; + z = v[p] = int32(v[p] + mx(sum, y, z, p, e, k)); + } + y = v[0]; + z = v[n] = int32(v[n] + mx(sum, y, z, n, e, k)); + } + return v; +} + +/** + * Performs XXTEA decryption on a Uint32Array + * @param {Uint32Array} v + * @param {Uint32Array} k + * @returns {Uint32Array} + */ +function decryptUint32Array(v, k) { + const length = v.length; + const n = length - 1; + let y, z, sum, e, p; + y = v[0]; + const q = Math.floor(6 + 52 / length); + for (sum = int32(q * DELTA); sum !== 0; sum = int32(sum - DELTA)) { + e = sum >>> 2 & 3; + for (p = n; p > 0; --p) { + z = v[p - 1]; + y = v[p] = int32(v[p] - mx(sum, y, z, p, e, k)); + } + z = v[n]; + y = v[0] = int32(v[0] - mx(sum, y, z, 0, e, k)); + } + return v; +} + +/** + * Encrypt function + * @param {TypedArray} data + * @param {TypedArray} key + * @returns {Uint8Array} + */ +export function encrypt(data, key) { + if (data === undefined || data === null || data.length === 0) { + return data; + } + return toUint8Array(encryptUint32Array(toUint32Array(data, true), toUint32Array(fixk(key), false)), false); +} + +/** + * Decrypt function + * @param {TypedArray} data + * @param {TypedArray} key + * @returns {Uint8Array} + */ +export function decrypt(data, key) { + if (data === undefined || data === null || data.length === 0) { + return data; + } + return toUint8Array(decryptUint32Array(toUint32Array(data, false), toUint32Array(fixk(key), false)), true); +} diff --git a/src/core/operations/ChaCha.mjs b/src/core/operations/ChaCha.mjs index 40ba46dc..2d186d35 100644 --- a/src/core/operations/ChaCha.mjs +++ b/src/core/operations/ChaCha.mjs @@ -100,7 +100,7 @@ class ChaCha extends Operation { super(); this.name = "ChaCha"; - this.module = "Default"; + this.module = "Ciphers"; this.description = "ChaCha is a stream cipher designed by Daniel J. Bernstein. It is a variant of the Salsa stream cipher. Several parameterizations exist; 'ChaCha' may refer to the original construction, or to the variant as described in RFC-8439. ChaCha is often used with Poly1305, in the ChaCha20-Poly1305 AEAD construction.

Key: ChaCha uses a key of 16 or 32 bytes (128 or 256 bits).

Nonce: ChaCha uses a nonce of 8 or 12 bytes (64 or 96 bits).

Counter: ChaCha uses a counter of 4 or 8 bytes (32 or 64 bits); together, the nonce and counter must add up to 16 bytes. The counter starts at zero at the start of the keystream, and is incremented at every 64 bytes."; this.infoURL = "https://wikipedia.org/wiki/Salsa20#ChaCha_variant"; this.inputType = "string"; diff --git a/src/core/operations/DateTimeDelta.mjs b/src/core/operations/DateTimeDelta.mjs index 35090606..7f82cf01 100644 --- a/src/core/operations/DateTimeDelta.mjs +++ b/src/core/operations/DateTimeDelta.mjs @@ -22,7 +22,6 @@ class DateTimeDelta extends Operation { this.name = "DateTime Delta"; this.module = "Default"; this.description = "Calculates a new DateTime value given an input DateTime value and a time difference (delta) from the input DateTime value."; - this.infoURL = ""; this.inputType = "string"; this.outputType = "html"; this.args = [ diff --git a/src/core/operations/ECDSASign.mjs b/src/core/operations/ECDSASign.mjs new file mode 100644 index 00000000..7b8f57f1 --- /dev/null +++ b/src/core/operations/ECDSASign.mjs @@ -0,0 +1,107 @@ +/** + * @author cplussharp + * @copyright Crown Copyright 2021 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { fromHex } from "../lib/Hex.mjs"; +import { toBase64 } from "../lib/Base64.mjs"; +import r from "jsrsasign"; + +/** + * ECDSA Sign operation + */ +class ECDSASign extends Operation { + + /** + * ECDSASign constructor + */ + constructor() { + super(); + + this.name = "ECDSA Sign"; + this.module = "Ciphers"; + this.description = "Sign a plaintext message with a PEM encoded EC key."; + this.infoURL = "https://wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + name: "ECDSA Private Key (PEM)", + type: "text", + value: "-----BEGIN EC PRIVATE KEY-----" + }, + { + name: "Message Digest Algorithm", + type: "option", + value: [ + "SHA-256", + "SHA-384", + "SHA-512", + "SHA-1", + "MD5" + ] + }, + { + name: "Output Format", + type: "option", + value: [ + "ASN.1 HEX", + "P1363 HEX", + "JSON Web Signature", + "Raw JSON" + ] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const [keyPem, mdAlgo, outputFormat] = args; + + if (keyPem.replace("-----BEGIN EC PRIVATE KEY-----", "").length === 0) { + throw new OperationError("Please enter a private key."); + } + + const internalAlgorithmName = mdAlgo.replace("-", "") + "withECDSA"; + const sig = new r.KJUR.crypto.Signature({ alg: internalAlgorithmName }); + const key = r.KEYUTIL.getKey(keyPem); + if (key.type !== "EC") { + throw new OperationError("Provided key is not an EC key."); + } + if (!key.isPrivate) { + throw new OperationError("Provided key is not a private key."); + } + sig.init(key); + const signatureASN1Hex = sig.signString(input); + + let result; + switch (outputFormat) { + case "ASN.1 HEX": + result = signatureASN1Hex; + break; + case "P1363 HEX": + result = r.KJUR.crypto.ECDSA.asn1SigToConcatSig(signatureASN1Hex); + break; + case "JSON Web Signature": + result = r.KJUR.crypto.ECDSA.asn1SigToConcatSig(signatureASN1Hex); + result = toBase64(fromHex(result), "A-Za-z0-9-_"); // base64url + break; + case "Raw JSON": { + const signatureRS = r.KJUR.crypto.ECDSA.parseSigHexInHexRS(signatureASN1Hex); + result = JSON.stringify(signatureRS); + break; + } + } + + return result; + } +} + +export default ECDSASign; diff --git a/src/core/operations/ECDSASignatureConversion.mjs b/src/core/operations/ECDSASignatureConversion.mjs new file mode 100644 index 00000000..3f6c6bfb --- /dev/null +++ b/src/core/operations/ECDSASignatureConversion.mjs @@ -0,0 +1,146 @@ +/** + * @author cplussharp + * @copyright Crown Copyright 2021 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { fromBase64, toBase64 } from "../lib/Base64.mjs"; +import { fromHex, toHexFast } from "../lib/Hex.mjs"; +import r from "jsrsasign"; + +/** + * ECDSA Sign operation + */ +class ECDSASignatureConversion extends Operation { + + /** + * ECDSASignatureConversion constructor + */ + constructor() { + super(); + + this.name = "ECDSA Signature Conversion"; + this.module = "Ciphers"; + this.description = "Convert an ECDSA signature between hex, asn1 and json."; + this.infoURL = "https://wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + name: "Input Format", + type: "option", + value: [ + "Auto", + "ASN.1 HEX", + "P1363 HEX", + "JSON Web Signature", + "Raw JSON" + ] + }, + { + name: "Output Format", + type: "option", + value: [ + "ASN.1 HEX", + "P1363 HEX", + "JSON Web Signature", + "Raw JSON" + ] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + let inputFormat = args[0]; + const outputFormat = args[1]; + + // detect input format + let inputJson; + if (inputFormat === "Auto") { + try { + inputJson = JSON.parse(input); + if (typeof(inputJson) === "object") { + inputFormat = "Raw JSON"; + } + } catch {} + } + + if (inputFormat === "Auto") { + const hexRegex = /^[a-f\d]{2,}$/gi; + if (hexRegex.test(input)) { + if (input.substring(0, 2) === "30" && r.ASN1HEX.isASN1HEX(input)) { + inputFormat = "ASN.1 HEX"; + } else { + inputFormat = "P1363 HEX"; + } + } + } + + let inputBase64; + if (inputFormat === "Auto") { + try { + inputBase64 = fromBase64(input, "A-Za-z0-9-_", false); + inputFormat = "JSON Web Signature"; + } catch {} + } + + // convert input to ASN.1 hex + let signatureASN1Hex; + switch (inputFormat) { + case "Auto": + throw new OperationError("Signature format could not be detected"); + case "ASN.1 HEX": + signatureASN1Hex = input; + break; + case "P1363 HEX": + signatureASN1Hex = r.KJUR.crypto.ECDSA.concatSigToASN1Sig(input); + break; + case "JSON Web Signature": + if (!inputBase64) inputBase64 = fromBase64(input, "A-Za-z0-9-_"); + signatureASN1Hex = r.KJUR.crypto.ECDSA.concatSigToASN1Sig(toHexFast(inputBase64)); + break; + case "Raw JSON": { + if (!inputJson) inputJson = JSON.parse(input); + if (!inputJson.r) { + throw new OperationError('No "r" value in the signature JSON'); + } + if (!inputJson.s) { + throw new OperationError('No "s" value in the signature JSON'); + } + signatureASN1Hex = r.KJUR.crypto.ECDSA.hexRSSigToASN1Sig(inputJson.r, inputJson.s); + break; + } + } + + // convert ASN.1 hex to output format + let result; + switch (outputFormat) { + case "ASN.1 HEX": + result = signatureASN1Hex; + break; + case "P1363 HEX": + result = r.KJUR.crypto.ECDSA.asn1SigToConcatSig(signatureASN1Hex); + break; + case "JSON Web Signature": + result = r.KJUR.crypto.ECDSA.asn1SigToConcatSig(signatureASN1Hex); + result = toBase64(fromHex(result), "A-Za-z0-9-_"); // base64url + break; + case "Raw JSON": { + const signatureRS = r.KJUR.crypto.ECDSA.parseSigHexInHexRS(signatureASN1Hex); + result = JSON.stringify(signatureRS); + break; + } + } + + return result; + } +} + +export default ECDSASignatureConversion; diff --git a/src/core/operations/ECDSAVerify.mjs b/src/core/operations/ECDSAVerify.mjs new file mode 100644 index 00000000..7e46e867 --- /dev/null +++ b/src/core/operations/ECDSAVerify.mjs @@ -0,0 +1,154 @@ +/** + * @author cplussharp + * @copyright Crown Copyright 2021 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import { fromBase64 } from "../lib/Base64.mjs"; +import { toHexFast } from "../lib/Hex.mjs"; +import r from "jsrsasign"; + +/** + * ECDSA Verify operation + */ +class ECDSAVerify extends Operation { + + /** + * ECDSAVerify constructor + */ + constructor() { + super(); + + this.name = "ECDSA Verify"; + this.module = "Ciphers"; + this.description = "Verify a message against a signature and a public PEM encoded EC key."; + this.infoURL = "https://wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + name: "Input Format", + type: "option", + value: [ + "Auto", + "ASN.1 HEX", + "P1363 HEX", + "JSON Web Signature", + "Raw JSON" + ] + }, + { + name: "Message Digest Algorithm", + type: "option", + value: [ + "SHA-256", + "SHA-384", + "SHA-512", + "SHA-1", + "MD5" + ] + }, + { + name: "ECDSA Public Key (PEM)", + type: "text", + value: "-----BEGIN PUBLIC KEY-----" + }, + { + name: "Message", + type: "text", + value: "" + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + let inputFormat = args[0]; + const [, mdAlgo, keyPem, msg] = args; + + if (keyPem.replace("-----BEGIN PUBLIC KEY-----", "").length === 0) { + throw new OperationError("Please enter a public key."); + } + + // detect input format + let inputJson; + if (inputFormat === "Auto") { + try { + inputJson = JSON.parse(input); + if (typeof(inputJson) === "object") { + inputFormat = "Raw JSON"; + } + } catch {} + } + + if (inputFormat === "Auto") { + const hexRegex = /^[a-f\d]{2,}$/gi; + if (hexRegex.test(input)) { + if (input.substring(0, 2) === "30" && r.ASN1HEX.isASN1HEX(input)) { + inputFormat = "ASN.1 HEX"; + } else { + inputFormat = "P1363 HEX"; + } + } + } + + let inputBase64; + if (inputFormat === "Auto") { + try { + inputBase64 = fromBase64(input, "A-Za-z0-9-_", false); + inputFormat = "JSON Web Signature"; + } catch {} + } + + // convert to ASN.1 signature + let signatureASN1Hex; + switch (inputFormat) { + case "Auto": + throw new OperationError("Signature format could not be detected"); + case "ASN.1 HEX": + signatureASN1Hex = input; + break; + case "P1363 HEX": + signatureASN1Hex = r.KJUR.crypto.ECDSA.concatSigToASN1Sig(input); + break; + case "JSON Web Signature": + if (!inputBase64) inputBase64 = fromBase64(input, "A-Za-z0-9-_"); + signatureASN1Hex = r.KJUR.crypto.ECDSA.concatSigToASN1Sig(toHexFast(inputBase64)); + break; + case "Raw JSON": { + if (!inputJson) inputJson = JSON.parse(input); + if (!inputJson.r) { + throw new OperationError('No "r" value in the signature JSON'); + } + if (!inputJson.s) { + throw new OperationError('No "s" value in the signature JSON'); + } + signatureASN1Hex = r.KJUR.crypto.ECDSA.hexRSSigToASN1Sig(inputJson.r, inputJson.s); + break; + } + } + + // verify signature + const internalAlgorithmName = mdAlgo.replace("-", "") + "withECDSA"; + const sig = new r.KJUR.crypto.Signature({ alg: internalAlgorithmName }); + const key = r.KEYUTIL.getKey(keyPem); + if (key.type !== "EC") { + throw new OperationError("Provided key is not an EC key."); + } + if (!key.isPublic) { + throw new OperationError("Provided key is not a public key."); + } + sig.init(key); + sig.updateString(msg); + const result = sig.verify(signatureASN1Hex); + return result ? "Verified OK" : "Verification Failure"; + } +} + +export default ECDSAVerify; diff --git a/src/core/operations/ExtractHashes.mjs b/src/core/operations/ExtractHashes.mjs index 386aab0e..fd50089f 100644 --- a/src/core/operations/ExtractHashes.mjs +++ b/src/core/operations/ExtractHashes.mjs @@ -21,7 +21,7 @@ class ExtractHashes extends Operation { this.name = "Extract hashes"; this.module = "Regex"; this.description = "Extracts potential hashes based on hash character length"; - this.infoURL = "https://en.wikipedia.org/wiki/Comparison_of_cryptographic_hash_functions"; + this.infoURL = "https://wikipedia.org/wiki/Comparison_of_cryptographic_hash_functions"; this.inputType = "string"; this.outputType = "string"; this.args = [ diff --git a/src/core/operations/FangURL.mjs b/src/core/operations/FangURL.mjs index 93e01770..ad5bf525 100644 --- a/src/core/operations/FangURL.mjs +++ b/src/core/operations/FangURL.mjs @@ -20,6 +20,7 @@ class FangURL extends Operation { this.name = "Fang URL"; this.module = "Default"; this.description = "Takes a 'Defanged' Universal Resource Locator (URL) and 'Fangs' it. Meaning, it removes the alterations (defanged) that render it useless so that it can be used again."; + this.infoURL = "https://isc.sans.edu/forums/diary/Defang+all+the+things/22744/"; this.inputType = "string"; this.outputType = "string"; this.args = [ diff --git a/src/core/operations/FileTree.mjs b/src/core/operations/FileTree.mjs index 8321f8f5..9484313f 100644 --- a/src/core/operations/FileTree.mjs +++ b/src/core/operations/FileTree.mjs @@ -1,6 +1,6 @@ /** * @author sw5678 - * @copyright Crown Copyright 2016 + * @copyright Crown Copyright 2023 * @license Apache-2.0 */ @@ -21,7 +21,8 @@ class FileTree extends Operation { this.name = "File Tree"; this.module = "Default"; - this.description = "Creates file tree from list of file paths (similar to the tree command in Linux)"; + this.description = "Creates a file tree from a list of file paths (similar to the tree command in Linux)"; + this.infoURL = "https://wikipedia.org/wiki/Tree_(command)"; this.inputType = "string"; this.outputType = "string"; this.args = [ diff --git a/src/core/operations/FromFloat.mjs b/src/core/operations/FromFloat.mjs index 4fe5990e..8bf56d81 100644 --- a/src/core/operations/FromFloat.mjs +++ b/src/core/operations/FromFloat.mjs @@ -22,8 +22,8 @@ class FromFloat extends Operation { this.name = "From Float"; this.module = "Default"; - this.description = "Convert from EEE754 Floating Point Numbers"; - this.infoURL = "https://en.wikipedia.org/wiki/IEEE_754"; + this.description = "Convert from IEEE754 Floating Point Numbers"; + this.infoURL = "https://wikipedia.org/wiki/IEEE_754"; this.inputType = "string"; this.outputType = "byteArray"; this.args = [ diff --git a/src/core/operations/GOSTDecrypt.mjs b/src/core/operations/GOSTDecrypt.mjs index 8259a0d4..2e7467da 100644 --- a/src/core/operations/GOSTDecrypt.mjs +++ b/src/core/operations/GOSTDecrypt.mjs @@ -55,22 +55,19 @@ class GOSTDecrypt extends Operation { type: "argSelector", value: [ { - name: "GOST 28147 (Magma, 1989)", - off: [5], - on: [6] + name: "GOST 28147 (1989)", + on: [5] + }, + { + name: "GOST R 34.12 (Magma, 2015)", + off: [5] }, { name: "GOST R 34.12 (Kuznyechik, 2015)", - on: [5], - off: [6] + off: [5] } ] }, - { - name: "Block length", - type: "option", - value: ["64", "128"] - }, { name: "sBox", type: "option", @@ -100,14 +97,30 @@ class GOSTDecrypt extends Operation { * @returns {string} */ async run(input, args) { - const [keyObj, ivObj, inputType, outputType, version, length, sBox, blockMode, keyMeshing, padding] = args; + const [keyObj, ivObj, inputType, outputType, version, sBox, blockMode, keyMeshing, padding] = args; const key = toHexFast(Utils.convertToByteArray(keyObj.string, keyObj.option)); const iv = toHexFast(Utils.convertToByteArray(ivObj.string, ivObj.option)); input = inputType === "Hex" ? input : toHexFast(Utils.strToArrayBuffer(input)); - const versionNum = version === "GOST 28147 (Magma, 1989)" ? 1989 : 2015; - const blockLength = versionNum === 1989 ? 64 : parseInt(length, 10); + let blockLength, versionNum; + switch (version) { + case "GOST 28147 (1989)": + versionNum = 1989; + blockLength = 64; + break; + case "GOST R 34.12 (Magma, 2015)": + versionNum = 2015; + blockLength = 64; + break; + case "GOST R 34.12 (Kuznyechik, 2015)": + versionNum = 2015; + blockLength = 128; + break; + default: + throw new OperationError(`Unknown algorithm version: ${version}`); + } + const sBoxVal = versionNum === 1989 ? sBox : null; const algorithm = { diff --git a/src/core/operations/GOSTEncrypt.mjs b/src/core/operations/GOSTEncrypt.mjs index ce92ecda..82bdaeda 100644 --- a/src/core/operations/GOSTEncrypt.mjs +++ b/src/core/operations/GOSTEncrypt.mjs @@ -55,22 +55,19 @@ class GOSTEncrypt extends Operation { type: "argSelector", value: [ { - name: "GOST 28147 (Magma, 1989)", - off: [5], - on: [6] + name: "GOST 28147 (1989)", + on: [5] + }, + { + name: "GOST R 34.12 (Magma, 2015)", + off: [5] }, { name: "GOST R 34.12 (Kuznyechik, 2015)", - on: [5], - off: [6] + off: [5] } ] }, - { - name: "Block length", - type: "option", - value: ["64", "128"] - }, { name: "sBox", type: "option", @@ -100,14 +97,30 @@ class GOSTEncrypt extends Operation { * @returns {string} */ async run(input, args) { - const [keyObj, ivObj, inputType, outputType, version, length, sBox, blockMode, keyMeshing, padding] = args; + const [keyObj, ivObj, inputType, outputType, version, sBox, blockMode, keyMeshing, padding] = args; const key = toHexFast(Utils.convertToByteArray(keyObj.string, keyObj.option)); const iv = toHexFast(Utils.convertToByteArray(ivObj.string, ivObj.option)); input = inputType === "Hex" ? input : toHexFast(Utils.strToArrayBuffer(input)); - const versionNum = version === "GOST 28147 (Magma, 1989)" ? 1989 : 2015; - const blockLength = versionNum === 1989 ? 64 : parseInt(length, 10); + let blockLength, versionNum; + switch (version) { + case "GOST 28147 (1989)": + versionNum = 1989; + blockLength = 64; + break; + case "GOST R 34.12 (Magma, 2015)": + versionNum = 2015; + blockLength = 64; + break; + case "GOST R 34.12 (Kuznyechik, 2015)": + versionNum = 2015; + blockLength = 128; + break; + default: + throw new OperationError(`Unknown algorithm version: ${version}`); + } + const sBoxVal = versionNum === 1989 ? sBox : null; const algorithm = { diff --git a/src/core/operations/GOSTKeyUnwrap.mjs b/src/core/operations/GOSTKeyUnwrap.mjs index afcd6287..52b0a9ec 100644 --- a/src/core/operations/GOSTKeyUnwrap.mjs +++ b/src/core/operations/GOSTKeyUnwrap.mjs @@ -55,22 +55,19 @@ class GOSTKeyUnwrap extends Operation { type: "argSelector", value: [ { - name: "GOST 28147 (Magma, 1989)", - off: [5], - on: [6] + name: "GOST 28147 (1989)", + on: [5] + }, + { + name: "GOST R 34.12 (Magma, 2015)", + off: [5] }, { name: "GOST R 34.12 (Kuznyechik, 2015)", - on: [5], - off: [6] + off: [5] } ] }, - { - name: "Block length", - type: "option", - value: ["64", "128"] - }, { name: "sBox", type: "option", @@ -90,14 +87,30 @@ class GOSTKeyUnwrap extends Operation { * @returns {string} */ async run(input, args) { - const [keyObj, ukmObj, inputType, outputType, version, length, sBox, keyWrapping] = args; + const [keyObj, ukmObj, inputType, outputType, version, sBox, keyWrapping] = args; const key = toHexFast(Utils.convertToByteArray(keyObj.string, keyObj.option)); const ukm = toHexFast(Utils.convertToByteArray(ukmObj.string, ukmObj.option)); input = inputType === "Hex" ? input : toHexFast(Utils.strToArrayBuffer(input)); - const versionNum = version === "GOST 28147 (Magma, 1989)" ? 1989 : 2015; - const blockLength = versionNum === 1989 ? 64 : parseInt(length, 10); + let blockLength, versionNum; + switch (version) { + case "GOST 28147 (1989)": + versionNum = 1989; + blockLength = 64; + break; + case "GOST R 34.12 (Magma, 2015)": + versionNum = 2015; + blockLength = 64; + break; + case "GOST R 34.12 (Kuznyechik, 2015)": + versionNum = 2015; + blockLength = 128; + break; + default: + throw new OperationError(`Unknown algorithm version: ${version}`); + } + const sBoxVal = versionNum === 1989 ? sBox : null; const algorithm = { diff --git a/src/core/operations/GOSTKeyWrap.mjs b/src/core/operations/GOSTKeyWrap.mjs index 5a3fd4e6..443c9ba0 100644 --- a/src/core/operations/GOSTKeyWrap.mjs +++ b/src/core/operations/GOSTKeyWrap.mjs @@ -55,22 +55,19 @@ class GOSTKeyWrap extends Operation { type: "argSelector", value: [ { - name: "GOST 28147 (Magma, 1989)", - off: [5], - on: [6] + name: "GOST 28147 (1989)", + on: [5] + }, + { + name: "GOST R 34.12 (Magma, 2015)", + off: [5] }, { name: "GOST R 34.12 (Kuznyechik, 2015)", - on: [5], - off: [6] + off: [5] } ] }, - { - name: "Block length", - type: "option", - value: ["64", "128"] - }, { name: "sBox", type: "option", @@ -90,14 +87,30 @@ class GOSTKeyWrap extends Operation { * @returns {string} */ async run(input, args) { - const [keyObj, ukmObj, inputType, outputType, version, length, sBox, keyWrapping] = args; + const [keyObj, ukmObj, inputType, outputType, version, sBox, keyWrapping] = args; const key = toHexFast(Utils.convertToByteArray(keyObj.string, keyObj.option)); const ukm = toHexFast(Utils.convertToByteArray(ukmObj.string, ukmObj.option)); input = inputType === "Hex" ? input : toHexFast(Utils.strToArrayBuffer(input)); - const versionNum = version === "GOST 28147 (Magma, 1989)" ? 1989 : 2015; - const blockLength = versionNum === 1989 ? 64 : parseInt(length, 10); + let blockLength, versionNum; + switch (version) { + case "GOST 28147 (1989)": + versionNum = 1989; + blockLength = 64; + break; + case "GOST R 34.12 (Magma, 2015)": + versionNum = 2015; + blockLength = 64; + break; + case "GOST R 34.12 (Kuznyechik, 2015)": + versionNum = 2015; + blockLength = 128; + break; + default: + throw new OperationError(`Unknown algorithm version: ${version}`); + } + const sBoxVal = versionNum === 1989 ? sBox : null; const algorithm = { diff --git a/src/core/operations/GOSTSign.mjs b/src/core/operations/GOSTSign.mjs index 9195f469..2af850e7 100644 --- a/src/core/operations/GOSTSign.mjs +++ b/src/core/operations/GOSTSign.mjs @@ -55,22 +55,19 @@ class GOSTSign extends Operation { type: "argSelector", value: [ { - name: "GOST 28147 (Magma, 1989)", - off: [5], - on: [6] + name: "GOST 28147 (1989)", + on: [5] + }, + { + name: "GOST R 34.12 (Magma, 2015)", + off: [5] }, { name: "GOST R 34.12 (Kuznyechik, 2015)", - on: [5], - off: [6] + off: [5] } ] }, - { - name: "Block length", - type: "option", - value: ["64", "128"] - }, { name: "sBox", type: "option", @@ -93,14 +90,30 @@ class GOSTSign extends Operation { * @returns {string} */ async run(input, args) { - const [keyObj, ivObj, inputType, outputType, version, length, sBox, macLength] = args; + const [keyObj, ivObj, inputType, outputType, version, sBox, macLength] = args; const key = toHexFast(Utils.convertToByteArray(keyObj.string, keyObj.option)); const iv = toHexFast(Utils.convertToByteArray(ivObj.string, ivObj.option)); input = inputType === "Hex" ? input : toHexFast(Utils.strToArrayBuffer(input)); - const versionNum = version === "GOST 28147 (Magma, 1989)" ? 1989 : 2015; - const blockLength = versionNum === 1989 ? 64 : parseInt(length, 10); + let blockLength, versionNum; + switch (version) { + case "GOST 28147 (1989)": + versionNum = 1989; + blockLength = 64; + break; + case "GOST R 34.12 (Magma, 2015)": + versionNum = 2015; + blockLength = 64; + break; + case "GOST R 34.12 (Kuznyechik, 2015)": + versionNum = 2015; + blockLength = 128; + break; + default: + throw new OperationError(`Unknown algorithm version: ${version}`); + } + const sBoxVal = versionNum === 1989 ? sBox : null; const algorithm = { diff --git a/src/core/operations/GOSTVerify.mjs b/src/core/operations/GOSTVerify.mjs index a270e7c5..2fa362fb 100644 --- a/src/core/operations/GOSTVerify.mjs +++ b/src/core/operations/GOSTVerify.mjs @@ -56,22 +56,19 @@ class GOSTVerify extends Operation { type: "argSelector", value: [ { - name: "GOST 28147 (Magma, 1989)", - off: [5], - on: [6] + name: "GOST 28147 (1989)", + on: [5] + }, + { + name: "GOST R 34.12 (Magma, 2015)", + off: [5] }, { name: "GOST R 34.12 (Kuznyechik, 2015)", - on: [5], - off: [6] + off: [5] } ] }, - { - name: "Block length", - type: "option", - value: ["64", "128"] - }, { name: "sBox", type: "option", @@ -86,15 +83,31 @@ class GOSTVerify extends Operation { * @returns {string} */ async run(input, args) { - const [keyObj, ivObj, macObj, inputType, version, length, sBox] = args; + const [keyObj, ivObj, macObj, inputType, version, sBox] = args; const key = toHexFast(Utils.convertToByteArray(keyObj.string, keyObj.option)); const iv = toHexFast(Utils.convertToByteArray(ivObj.string, ivObj.option)); const mac = toHexFast(Utils.convertToByteArray(macObj.string, macObj.option)); input = inputType === "Hex" ? input : toHexFast(Utils.strToArrayBuffer(input)); - const versionNum = version === "GOST 28147 (Magma, 1989)" ? 1989 : 2015; - const blockLength = versionNum === 1989 ? 64 : parseInt(length, 10); + let blockLength, versionNum; + switch (version) { + case "GOST 28147 (1989)": + versionNum = 1989; + blockLength = 64; + break; + case "GOST R 34.12 (Magma, 2015)": + versionNum = 2015; + blockLength = 64; + break; + case "GOST R 34.12 (Kuznyechik, 2015)": + versionNum = 2015; + blockLength = 128; + break; + default: + throw new OperationError(`Unknown algorithm version: ${version}`); + } + const sBoxVal = versionNum === 1989 ? sBox : null; const algorithm = { diff --git a/src/core/operations/GenerateECDSAKeyPair.mjs b/src/core/operations/GenerateECDSAKeyPair.mjs new file mode 100644 index 00000000..14714a02 --- /dev/null +++ b/src/core/operations/GenerateECDSAKeyPair.mjs @@ -0,0 +1,102 @@ +/** + * @author cplussharp + * @copyright Crown Copyright 2021 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import { cryptNotice } from "../lib/Crypt.mjs"; +import r from "jsrsasign"; + +/** + * Generate ECDSA Key Pair operation + */ +class GenerateECDSAKeyPair extends Operation { + + /** + * GenerateECDSAKeyPair constructor + */ + constructor() { + super(); + + this.name = "Generate ECDSA Key Pair"; + this.module = "Ciphers"; + this.description = `Generate an ECDSA key pair with a given Curve.

${cryptNotice}`; + this.infoURL = "https://wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + name: "Elliptic Curve", + type: "option", + value: [ + "P-256", + "P-384", + "P-521" + ] + }, + { + name: "Output Format", + type: "option", + value: [ + "PEM", + "DER", + "JWK" + ] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + async run(input, args) { + const [curveName, outputFormat] = args; + + return new Promise((resolve, reject) => { + let internalCurveName; + switch (curveName) { + case "P-256": + internalCurveName = "secp256r1"; + break; + case "P-384": + internalCurveName = "secp384r1"; + break; + case "P-521": + internalCurveName = "secp521r1"; + break; + } + const keyPair = r.KEYUTIL.generateKeypair("EC", internalCurveName); + + let pubKey; + let privKey; + let result; + switch (outputFormat) { + case "PEM": + pubKey = r.KEYUTIL.getPEM(keyPair.pubKeyObj).replace(/\r/g, ""); + privKey = r.KEYUTIL.getPEM(keyPair.prvKeyObj, "PKCS8PRV").replace(/\r/g, ""); + result = pubKey + "\n" + privKey; + break; + case "DER": + result = keyPair.prvKeyObj.prvKeyHex; + break; + case "JWK": + pubKey = r.KEYUTIL.getJWKFromKey(keyPair.pubKeyObj); + pubKey.key_ops = ["verify"]; // eslint-disable-line camelcase + pubKey.kid = "PublicKey"; + privKey = r.KEYUTIL.getJWKFromKey(keyPair.prvKeyObj); + privKey.key_ops = ["sign"]; // eslint-disable-line camelcase + privKey.kid = "PrivateKey"; + result = JSON.stringify({keys: [privKey, pubKey]}, null, 4); + break; + } + + resolve(result); + }); + } + +} + +export default GenerateECDSAKeyPair; diff --git a/src/core/operations/JA4ServerFingerprint.mjs b/src/core/operations/JA4ServerFingerprint.mjs new file mode 100644 index 00000000..662285a8 --- /dev/null +++ b/src/core/operations/JA4ServerFingerprint.mjs @@ -0,0 +1,66 @@ +/** + * @author n1474335 [n1474335@gmail.com] + * @copyright Crown Copyright 2024 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import {toJA4S} from "../lib/JA4.mjs"; + +/** + * JA4Server Fingerprint operation + */ +class JA4ServerFingerprint extends Operation { + + /** + * JA4ServerFingerprint constructor + */ + constructor() { + super(); + + this.name = "JA4Server Fingerprint"; + this.module = "Crypto"; + this.description = "Generates a JA4Server Fingerprint (JA4S) to help identify TLS servers or sessions based on hashing together values from the Server Hello.

Input: A hex stream of the TLS or QUIC Server Hello packet application layer."; + this.infoURL = "https://medium.com/foxio/ja4-network-fingerprinting-9376fe9ca637"; + this.inputType = "string"; + this.outputType = "string"; + this.args = [ + { + name: "Input format", + type: "option", + value: ["Hex", "Base64", "Raw"] + }, + { + name: "Output format", + type: "option", + value: ["JA4S", "JA4S Raw", "Both"] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const [inputFormat, outputFormat] = args; + input = Utils.convertToByteArray(input, inputFormat); + const ja4s = toJA4S(new Uint8Array(input)); + + // Output + switch (outputFormat) { + case "JA4S": + return ja4s.JA4S; + case "JA4S Raw": + return ja4s.JA4S_r; + case "Both": + default: + return `JA4S: ${ja4s.JA4S}\nJA4S_r: ${ja4s.JA4S_r}`; + } + } + +} + +export default JA4ServerFingerprint; diff --git a/src/core/operations/JWKToPem.mjs b/src/core/operations/JWKToPem.mjs new file mode 100644 index 00000000..c8c00270 --- /dev/null +++ b/src/core/operations/JWKToPem.mjs @@ -0,0 +1,80 @@ +/** + * @author cplussharp + * @copyright Crown Copyright 2021 + * @license Apache-2.0 + */ + +import r from "jsrsasign"; +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; + +/** + * PEM to JWK operation + */ +class PEMToJWK extends Operation { + + /** + * PEMToJWK constructor + */ + constructor() { + super(); + + this.name = "JWK to PEM"; + this.module = "PublicKey"; + this.description = "Converts Keys in JSON Web Key format to PEM format (PKCS#8)."; + this.infoURL = "https://datatracker.ietf.org/doc/html/rfc7517"; + this.inputType = "string"; + this.outputType = "string"; + this.args = []; + this.checks = [ + { + "pattern": "\"kty\":\\s*\"(EC|RSA)\"", + "flags": "gm", + "args": [] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const inputJson = JSON.parse(input); + + let keys = []; + if (Array.isArray(inputJson)) { + // list of keys => transform all keys + keys = inputJson; + } else if (Array.isArray(inputJson.keys)) { + // JSON Web Key Set => transform all keys + keys = inputJson.keys; + } else if (typeof inputJson === "object") { + // single key + keys.push(inputJson); + } else { + throw new OperationError("Input is not a JSON Web Key"); + } + + let output = ""; + for (let i=0; i 0) { + output += "\n"; + } + output += JSON.stringify(jwk); + } else if (match[1] === "CERTIFICATE") { + const cert = new r.X509(); + cert.readCertPEM(pem); + const key = cert.getPublicKey(); + const jwk = r.KEYUTIL.getJWKFromKey(key); + if (output.length > 0) { + output += "\n"; + } + output += JSON.stringify(jwk); + } else { + throw new OperationError(`Unsupported PEM type '${match[1]}'`); + } + } + return output; + } +} + +export default PEMToJWK; diff --git a/src/core/operations/ParseCSR.mjs b/src/core/operations/ParseCSR.mjs index ad891902..6ab44cb2 100644 --- a/src/core/operations/ParseCSR.mjs +++ b/src/core/operations/ParseCSR.mjs @@ -22,7 +22,7 @@ class ParseCSR extends Operation { this.name = "Parse CSR"; this.module = "PublicKey"; this.description = "Parse Certificate Signing Request (CSR) for an X.509 certificate"; - this.infoURL = "https://en.wikipedia.org/wiki/Certificate_signing_request"; + this.infoURL = "https://wikipedia.org/wiki/Certificate_signing_request"; this.inputType = "string"; this.outputType = "string"; this.args = [ diff --git a/src/core/operations/PubKeyFromCert.mjs b/src/core/operations/PubKeyFromCert.mjs new file mode 100644 index 00000000..0233b04a --- /dev/null +++ b/src/core/operations/PubKeyFromCert.mjs @@ -0,0 +1,68 @@ +/** + * @author cplussharp + * @copyright Crown Copyright 2023 + * @license Apache-2.0 + */ + +import r from "jsrsasign"; +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; + +/** + * Public Key from Certificate operation + */ +class PubKeyFromCert extends Operation { + + /** + * PubKeyFromCert constructor + */ + constructor() { + super(); + + this.name = "Public Key from Certificate"; + this.module = "PublicKey"; + this.description = "Extracts the Public Key from a Certificate."; + this.infoURL = "https://en.wikipedia.org/wiki/X.509"; + this.inputType = "string"; + this.outputType = "string"; + this.args = []; + this.checks = []; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + let output = ""; + let match; + const regex = /-----BEGIN CERTIFICATE-----/g; + while ((match = regex.exec(input)) !== null) { + // find corresponding end tag + const indexBase64 = match.index + match[0].length; + const footer = "-----END CERTIFICATE-----"; + const indexFooter = input.indexOf(footer, indexBase64); + if (indexFooter === -1) { + throw new OperationError(`PEM footer '${footer}' not found`); + } + + const certPem = input.substring(match.index, indexFooter + footer.length); + const cert = new r.X509(); + cert.readCertPEM(certPem); + let pubKey; + try { + pubKey = cert.getPublicKey(); + } catch { + throw new OperationError("Unsupported public key type"); + } + const pubKeyPem = r.KEYUTIL.getPEM(pubKey); + + // PEM ends with '\n', so a new key always starts on a new line + output += pubKeyPem; + } + return output; + } +} + +export default PubKeyFromCert; diff --git a/src/core/operations/PubKeyFromPrivKey.mjs b/src/core/operations/PubKeyFromPrivKey.mjs new file mode 100644 index 00000000..5a08882b --- /dev/null +++ b/src/core/operations/PubKeyFromPrivKey.mjs @@ -0,0 +1,82 @@ +/** + * @author cplussharp + * @copyright Crown Copyright 2023 + * @license Apache-2.0 + */ + +import r from "jsrsasign"; +import Operation from "../Operation.mjs"; +import OperationError from "../errors/OperationError.mjs"; + +/** + * Public Key from Private Key operation + */ +class PubKeyFromPrivKey extends Operation { + + /** + * PubKeyFromPrivKey constructor + */ + constructor() { + super(); + + this.name = "Public Key from Private Key"; + this.module = "PublicKey"; + this.description = "Extracts the Public Key from a Private Key."; + this.infoURL = "https://en.wikipedia.org/wiki/PKCS_8"; + this.inputType = "string"; + this.outputType = "string"; + this.args = []; + this.checks = []; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + let output = ""; + let match; + const regex = /-----BEGIN ((RSA |EC |DSA )?PRIVATE KEY)-----/g; + while ((match = regex.exec(input)) !== null) { + // find corresponding end tag + const indexBase64 = match.index + match[0].length; + const footer = `-----END ${match[1]}-----`; + const indexFooter = input.indexOf(footer, indexBase64); + if (indexFooter === -1) { + throw new OperationError(`PEM footer '${footer}' not found`); + } + + const privKeyPem = input.substring(match.index, indexFooter + footer.length); + let privKey; + try { + privKey = r.KEYUTIL.getKey(privKeyPem); + } catch (err) { + throw new OperationError(`Unsupported key type: ${err}`); + } + let pubKey; + if (privKey.type && privKey.type === "EC") { + pubKey = new r.KJUR.crypto.ECDSA({ curve: privKey.curve }); + pubKey.setPublicKeyHex(privKey.generatePublicKeyHex()); + } else if (privKey.type && privKey.type === "DSA") { + if (!privKey.y) { + throw new OperationError(`DSA Private Key in PKCS#8 is not supported`); + } + pubKey = new r.KJUR.crypto.DSA(); + pubKey.setPublic(privKey.p, privKey.q, privKey.g, privKey.y); + } else if (privKey.n && privKey.e) { + pubKey = new r.RSAKey(); + pubKey.setPublic(privKey.n, privKey.e); + } else { + throw new OperationError(`Unsupported key type`); + } + const pubKeyPem = r.KEYUTIL.getPEM(pubKey); + + // PEM ends with '\n', so a new key always starts on a new line + output += pubKeyPem; + } + return output; + } +} + +export default PubKeyFromPrivKey; diff --git a/src/core/operations/RAKE.mjs b/src/core/operations/RAKE.mjs index d1165b51..1470f5f0 100644 --- a/src/core/operations/RAKE.mjs +++ b/src/core/operations/RAKE.mjs @@ -101,22 +101,17 @@ class RAKE extends Operation { phrases = phrases.filter(subArray => subArray.length > 0); // Remove duplicate phrases - const uniquePhrases = [...new Set(phrases.map(function (phrase) { - return phrase.join(" "); - }))]; - phrases = uniquePhrases.map(function (phrase) { - return phrase.split(" "); - }); + phrases = phrases.unique(); // Generate word_degree_matrix and populate - const wordDegreeMatrix = Array.from(Array(tokens.length), _ => Array(tokens.length).fill(0)); - phrases.forEach(function (phrase) { - phrase.forEach(function (word1) { - phrase.forEach(function (word2) { + const wordDegreeMatrix = Array(tokens.length).fill().map(() => Array(tokens.length).fill(0)); + for (const phrase of phrases) { + for (const word1 of phrase) { + for (const word2 of phrase) { wordDegreeMatrix[tokens.indexOf(word1)][tokens.indexOf(word2)]++; - }); - }); - }); + } + } + } // Calculate degree score for each token const degreeScores = Array(tokens.length).fill(0); diff --git a/src/core/operations/RegularExpression.mjs b/src/core/operations/RegularExpression.mjs index 18d3fda9..9ea17e83 100644 --- a/src/core/operations/RegularExpression.mjs +++ b/src/core/operations/RegularExpression.mjs @@ -67,6 +67,10 @@ class RegularExpression extends Operation { name: "MAC address", value: "[A-Fa-f\\d]{2}(?:[:-][A-Fa-f\\d]{2}){5}" }, + { + name: "UUID", + value: "[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}" + }, { name: "Date (yyyy-mm-dd)", value: "((?:19|20)\\d\\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])" @@ -83,10 +87,6 @@ class RegularExpression extends Operation { name: "Strings", value: "[A-Za-z\\d/\\-:.,_$%\\x27\"()<>= !\\[\\]{}@]{4,}" }, - { - name: "UUID (any version)", - value: "[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}" - }, ], "target": 1 }, diff --git a/src/core/operations/RisonDecode.mjs b/src/core/operations/RisonDecode.mjs index 1b9741a8..d4e36f80 100644 --- a/src/core/operations/RisonDecode.mjs +++ b/src/core/operations/RisonDecode.mjs @@ -20,7 +20,7 @@ class RisonDecode extends Operation { super(); this.name = "Rison Decode"; - this.module = "Default"; + this.module = "Encodings"; this.description = "Rison, a data serialization format optimized for compactness in URIs. Rison is a slight variation of JSON that looks vastly superior after URI encoding. Rison still expresses exactly the same set of data structures as JSON, so data can be translated back and forth without loss or guesswork."; this.infoURL = "https://github.com/Nanonid/rison"; this.inputType = "string"; @@ -29,11 +29,7 @@ class RisonDecode extends Operation { { name: "Decode Option", type: "editableOption", - value: [ - { name: "Decode", value: "Decode", }, - { name: "Decode Object", value: "Decode Object", }, - { name: "Decode Array", value: "Decode Array", }, - ] + value: ["Decode", "Decode Object", "Decode Array"] }, ]; } @@ -52,8 +48,9 @@ class RisonDecode extends Operation { return rison.decode_object(input); case "Decode Array": return rison.decode_array(input); + default: + throw new OperationError("Invalid Decode option"); } - throw new OperationError("Invalid Decode option"); } } diff --git a/src/core/operations/RisonEncode.mjs b/src/core/operations/RisonEncode.mjs index 36a61017..12b13b66 100644 --- a/src/core/operations/RisonEncode.mjs +++ b/src/core/operations/RisonEncode.mjs @@ -20,7 +20,7 @@ class RisonEncode extends Operation { super(); this.name = "Rison Encode"; - this.module = "Default"; + this.module = "Encodings"; this.description = "Rison, a data serialization format optimized for compactness in URIs. Rison is a slight variation of JSON that looks vastly superior after URI encoding. Rison still expresses exactly the same set of data structures as JSON, so data can be translated back and forth without loss or guesswork."; this.infoURL = "https://github.com/Nanonid/rison"; this.inputType = "Object"; @@ -28,13 +28,8 @@ class RisonEncode extends Operation { this.args = [ { name: "Encode Option", - type: "editableOption", - value: [ - { name: "Encode", value: "Encode", }, - { name: "Encode Object", value: "Encode Object", }, - { name: "Encode Array", value: "Encode Array", }, - { name: "Encode URI", value: "Encode URI", } - ] + type: "option", + value: ["Encode", "Encode Object", "Encode Array", "Encode URI"] }, ]; } @@ -55,8 +50,9 @@ class RisonEncode extends Operation { return rison.encode_array(input); case "Encode URI": return rison.encode_uri(input); + default: + throw new OperationError("Invalid encode option"); } - throw new OperationError("Invalid encode option"); } } diff --git a/src/core/operations/Salsa20.mjs b/src/core/operations/Salsa20.mjs index a95dd5d3..7a76cf26 100644 --- a/src/core/operations/Salsa20.mjs +++ b/src/core/operations/Salsa20.mjs @@ -22,7 +22,7 @@ class Salsa20 extends Operation { super(); this.name = "Salsa20"; - this.module = "Default"; + this.module = "Ciphers"; this.description = "Salsa20 is a stream cipher designed by Daniel J. Bernstein and submitted to the eSTREAM project; Salsa20/8 and Salsa20/12 are round-reduced variants. It is closely related to the ChaCha stream cipher.

Key: Salsa20 uses a key of 16 or 32 bytes (128 or 256 bits).

Nonce: Salsa20 uses a nonce of 8 bytes (64 bits).

Counter: Salsa uses a counter of 8 bytes (64 bits). The counter starts at zero at the start of the keystream, and is incremented at every 64 bytes."; this.infoURL = "https://wikipedia.org/wiki/Salsa20"; this.inputType = "string"; diff --git a/src/core/operations/ToFloat.mjs b/src/core/operations/ToFloat.mjs index b9aef638..e0c70bc6 100644 --- a/src/core/operations/ToFloat.mjs +++ b/src/core/operations/ToFloat.mjs @@ -23,8 +23,8 @@ class ToFloat extends Operation { this.name = "To Float"; this.module = "Default"; - this.description = "Convert to EEE754 Floating Point Numbers"; - this.infoURL = "https://en.wikipedia.org/wiki/IEEE_754"; + this.description = "Convert to IEEE754 Floating Point Numbers"; + this.infoURL = "https://wikipedia.org/wiki/IEEE_754"; this.inputType = "byteArray"; this.outputType = "string"; this.args = [ diff --git a/src/core/operations/XSalsa20.mjs b/src/core/operations/XSalsa20.mjs index 32e8a0ba..d289585b 100644 --- a/src/core/operations/XSalsa20.mjs +++ b/src/core/operations/XSalsa20.mjs @@ -22,7 +22,7 @@ class XSalsa20 extends Operation { super(); this.name = "XSalsa20"; - this.module = "Default"; + this.module = "Ciphers"; this.description = "XSalsa20 is a variant of the Salsa20 stream cipher designed by Daniel J. Bernstein; XSalsa uses longer nonces.

Key: XSalsa20 uses a key of 16 or 32 bytes (128 or 256 bits).

Nonce: XSalsa20 uses a nonce of 24 bytes (192 bits).

Counter: XSalsa uses a counter of 8 bytes (64 bits). The counter starts at zero at the start of the keystream, and is incremented at every 64 bytes."; this.infoURL = "https://en.wikipedia.org/wiki/Salsa20#XSalsa20_with_192-bit_nonce"; this.inputType = "string"; diff --git a/src/core/operations/XXTEA.mjs b/src/core/operations/XXTEA.mjs deleted file mode 100644 index 1a0a4368..00000000 --- a/src/core/operations/XXTEA.mjs +++ /dev/null @@ -1,182 +0,0 @@ -/** - * @author devcydo [devcydo@gmail.com] - * @author Ma Bingyao [mabingyao@gmail.com] - * @copyright Crown Copyright 2022 - * @license Apache-2.0 - */ - -import Operation from "../Operation.mjs"; -import OperationError from "../errors/OperationError.mjs"; -import {toBase64} from "../lib/Base64.mjs"; -import Utils from "../Utils.mjs"; - -/** - * XXTEA Encrypt operation - */ -class XXTEAEncrypt extends Operation { - - /** - * XXTEAEncrypt constructor - */ - constructor() { - super(); - - this.name = "XXTEA"; - this.module = "Default"; - this.description = "Corrected Block TEA (often referred to as XXTEA) is a block cipher designed to correct weaknesses in the original Block TEA. XXTEA operates on variable-length blocks that are some arbitrary multiple of 32 bits in size (minimum 64 bits). The number of full cycles depends on the block size, but there are at least six (rising to 32 for small block sizes). The original Block TEA applies the XTEA round function to each word in the block and combines it additively with its leftmost neighbour. Slow diffusion rate of the decryption process was immediately exploited to break the cipher. Corrected Block TEA uses a more involved round function which makes use of both immediate neighbours in processing each word in the block."; - this.infoURL = "https://wikipedia.org/wiki/XXTEA"; - this.inputType = "string"; - this.outputType = "string"; - this.args = [ - { - "name": "Key", - "type": "string", - "value": "", - }, - ]; - } - - /** - * @param {string} input - * @param {Object[]} args - * @returns {string} - */ - run(input, args) { - let key = args[0]; - - if (input === undefined || input === null || input.length === 0) { - throw new OperationError("Invalid input length (0)"); - } - - if (key === undefined || key === null || key.length === 0) { - throw new OperationError("Invalid key length (0)"); - } - - input = Utils.convertToByteString(input, "utf8"); - key = Utils.convertToByteString(key, "utf8"); - - input = this.convertToUint32Array(input, true); - key = this.fixLength(this.convertToUint32Array(key, false)); - - let encrypted = this.encryptUint32Array(input, key); - - encrypted = toBase64(this.toBinaryString(encrypted, false)); - - return encrypted; - } - - /** - * Convert Uint32Array to binary string - * - * @param {Uint32Array} v - * @param {Boolean} includeLength - * @returns {string} - */ - toBinaryString(v, includeLENGTH) { - const LENGTH = v.length; - let n = LENGTH << 2; - if (includeLENGTH) { - const M = v[LENGTH - 1]; - n -= 4; - if ((M < n - 3) || (M > n)) { - return null; - } - n = M; - } - for (let i = 0; i < LENGTH; i++) { - v[i] = String.fromCharCode( - v[i] & 0xFF, - v[i] >>> 8 & 0xFF, - v[i] >>> 16 & 0xFF, - v[i] >>> 24 & 0xFF - ); - } - const RESULT = v.join(""); - if (includeLENGTH) { - return RESULT.substring(0, n); - } - return RESULT; - } - - /** - * @param {number} sum - * @param {number} y - * @param {number} z - * @param {number} p - * @param {number} e - * @param {number} k - * @returns {number} - */ - mx(sum, y, z, p, e, k) { - return ((z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4)) ^ ((sum ^ y) + (k[p & 3 ^ e] ^ z)); - } - - - /** - * Encrypt Uint32Array - * - * @param {Uint32Array} v - * @param {number} k - * @returns {Uint32Array} - */ - encryptUint32Array(v, k) { - const LENGTH = v.length; - const N = LENGTH - 1; - let y, z, sum, e, p, q; - z = v[N]; - sum = 0; - for (q = Math.floor(6 + 52 / LENGTH) | 0; q > 0; --q) { - sum = (sum + 0x9E3779B9) & 0xFFFFFFFF; - e = sum >>> 2 & 3; - for (p = 0; p < N; ++p) { - y = v[p + 1]; - z = v[p] = (v[p] + this.mx(sum, y, z, p, e, k)) & 0xFFFFFFFF; - } - y = v[0]; - z = v[N] = (v[N] + this.mx(sum, y, z, N, e, k)) & 0xFFFFFFFF; - } - return v; - } - - /** - * Fixes the Uint32Array lenght to 4 - * - * @param {Uint32Array} k - * @returns {Uint32Array} - */ - fixLength(k) { - if (k.length < 4) { - k.length = 4; - } - return k; - } - - /** - * Convert string to Uint32Array - * - * @param {string} bs - * @param {Boolean} includeLength - * @returns {Uint32Array} - */ - convertToUint32Array(bs, includeLength) { - const LENGTH = bs.length; - let n = LENGTH >> 2; - if ((LENGTH & 3) !== 0) { - ++n; - } - let v; - if (includeLength) { - v = new Array(n + 1); - v[n] = LENGTH; - } else { - v = new Array(n); - } - for (let i = 0; i < LENGTH; ++i) { - v[i >> 2] |= bs.charCodeAt(i) << ((i & 3) << 3); - } - return v; - } - -} - -export default XXTEAEncrypt; diff --git a/src/core/operations/XXTEADecrypt.mjs b/src/core/operations/XXTEADecrypt.mjs new file mode 100644 index 00000000..496e5409 --- /dev/null +++ b/src/core/operations/XXTEADecrypt.mjs @@ -0,0 +1,57 @@ +/** + * @author devcydo [devcydo@gmail.com] + * @author Ma Bingyao [mabingyao@gmail.com] + * @author n1474335 [n1474335@gmail.com] + * @copyright Crown Copyright 2024 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import OperationError from "../errors/OperationError.mjs"; +import {decrypt} from "../lib/XXTEA.mjs"; + +/** + * XXTEA Decrypt operation + */ +class XXTEADecrypt extends Operation { + + /** + * XXTEADecrypt constructor + */ + constructor() { + super(); + + this.name = "XXTEA Decrypt"; + this.module = "Ciphers"; + this.description = "Corrected Block TEA (often referred to as XXTEA) is a block cipher designed to correct weaknesses in the original Block TEA. XXTEA operates on variable-length blocks that are some arbitrary multiple of 32 bits in size (minimum 64 bits). The number of full cycles depends on the block size, but there are at least six (rising to 32 for small block sizes). The original Block TEA applies the XTEA round function to each word in the block and combines it additively with its leftmost neighbour. Slow diffusion rate of the decryption process was immediately exploited to break the cipher. Corrected Block TEA uses a more involved round function which makes use of both immediate neighbours in processing each word in the block."; + this.infoURL = "https://wikipedia.org/wiki/XXTEA"; + this.inputType = "ArrayBuffer"; + this.outputType = "ArrayBuffer"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = new Uint8Array(Utils.convertToByteArray(args[0].string, args[0].option)); + try { + return decrypt(new Uint8Array(input), key).buffer; + } catch (err) { + throw new OperationError("Unable to decrypt using this key"); + } + } + +} + +export default XXTEADecrypt; diff --git a/src/core/operations/XXTEAEncrypt.mjs b/src/core/operations/XXTEAEncrypt.mjs new file mode 100644 index 00000000..85379de0 --- /dev/null +++ b/src/core/operations/XXTEAEncrypt.mjs @@ -0,0 +1,52 @@ +/** + * @author devcydo [devcydo@gmail.com] + * @author Ma Bingyao [mabingyao@gmail.com] + * @author n1474335 [n1474335@gmail.com] + * @copyright Crown Copyright 2024 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; +import Utils from "../Utils.mjs"; +import {encrypt} from "../lib/XXTEA.mjs"; + +/** + * XXTEA Encrypt operation + */ +class XXTEAEncrypt extends Operation { + + /** + * XXTEAEncrypt constructor + */ + constructor() { + super(); + + this.name = "XXTEA Encrypt"; + this.module = "Ciphers"; + this.description = "Corrected Block TEA (often referred to as XXTEA) is a block cipher designed to correct weaknesses in the original Block TEA. XXTEA operates on variable-length blocks that are some arbitrary multiple of 32 bits in size (minimum 64 bits). The number of full cycles depends on the block size, but there are at least six (rising to 32 for small block sizes). The original Block TEA applies the XTEA round function to each word in the block and combines it additively with its leftmost neighbour. Slow diffusion rate of the decryption process was immediately exploited to break the cipher. Corrected Block TEA uses a more involved round function which makes use of both immediate neighbours in processing each word in the block."; + this.infoURL = "https://wikipedia.org/wiki/XXTEA"; + this.inputType = "ArrayBuffer"; + this.outputType = "ArrayBuffer"; + this.args = [ + { + "name": "Key", + "type": "toggleString", + "value": "", + "toggleValues": ["Hex", "UTF8", "Latin1", "Base64"] + }, + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {string} + */ + run(input, args) { + const key = new Uint8Array(Utils.convertToByteArray(args[0].string, args[0].option)); + return encrypt(new Uint8Array(input), key).buffer; + } + +} + +export default XXTEAEncrypt; diff --git a/src/web/App.mjs b/src/web/App.mjs index 53070e26..3ebfe1be 100755 --- a/src/web/App.mjs +++ b/src/web/App.mjs @@ -39,7 +39,6 @@ class App { this.baking = false; this.autoBake_ = false; - this.autoBakePause = false; this.progress = 0; this.ingId = 0; @@ -155,12 +154,12 @@ class App { * Runs Auto Bake if it is set. */ autoBake() { - // If autoBakePause is set, we are loading a full recipe (and potentially input), so there is no - // need to set the staleness indicator. Just exit and wait until auto bake is called after loading - // has completed. - if (this.autoBakePause) return false; + if (this.baking) { + this.manager.worker.cancelBakeForAutoBake(); + this.baking = false; + } - if (this.autoBake_ && !this.baking) { + if (this.autoBake_) { log.debug("Auto-baking"); this.manager.worker.bakeInputs({ nums: [this.manager.tabs.getActiveTab("input")], @@ -473,7 +472,6 @@ class App { * @fires Manager#statechange */ loadURIParams(params=this.getURIParams()) { - this.autoBakePause = true; this.uriParams = params; // Read in recipe from URI params @@ -502,7 +500,7 @@ class App { // Input Character Encoding // Must be set before the input is loaded if (this.uriParams.ienc) { - this.manager.input.chrEncChange(parseInt(this.uriParams.ienc, 10), true); + this.manager.input.chrEncChange(parseInt(this.uriParams.ienc, 10), true, true); } // Output Character Encoding @@ -540,7 +538,6 @@ class App { this.manager.options.changeTheme(Utils.escapeHtml(this.uriParams.theme)); } - this.autoBakePause = false; window.dispatchEvent(this.manager.statechange); } @@ -574,10 +571,6 @@ class App { setRecipeConfig(recipeConfig) { document.getElementById("rec-list").innerHTML = null; - // Pause auto-bake while loading but don't modify `this.autoBake_` - // otherwise `manualBake` cannot trigger. - this.autoBakePause = true; - for (let i = 0; i < recipeConfig.length; i++) { const item = this.manager.recipe.addOperation(recipeConfig[i].op); @@ -612,9 +605,6 @@ class App { this.progress = 0; } - - // Unpause auto bake - this.autoBakePause = false; } diff --git a/src/web/HTMLCategory.mjs b/src/web/HTMLCategory.mjs index 0414fd71..b61a6740 100755 --- a/src/web/HTMLCategory.mjs +++ b/src/web/HTMLCategory.mjs @@ -42,6 +42,9 @@ class HTMLCategory { let html = `
${this.name} +
    `; diff --git a/src/web/HTMLOperation.mjs b/src/web/HTMLOperation.mjs index ae61b58d..30cfd1d9 100755 --- a/src/web/HTMLOperation.mjs +++ b/src/web/HTMLOperation.mjs @@ -85,6 +85,7 @@ class HTMLOperation {
    pause not_interested + keyboard_arrow_up
     
    `; diff --git a/src/web/Manager.mjs b/src/web/Manager.mjs index b02a7eee..2020b2a0 100755 --- a/src/web/Manager.mjs +++ b/src/web/Manager.mjs @@ -139,6 +139,7 @@ class Manager { document.getElementById("load-delete-button").addEventListener("click", this.controls.loadDeleteClick.bind(this.controls)); document.getElementById("load-name").addEventListener("change", this.controls.loadNameChange.bind(this.controls)); document.getElementById("load-button").addEventListener("click", this.controls.loadButtonClick.bind(this.controls)); + document.getElementById("hide-icon").addEventListener("click", this.controls.hideRecipeArgsClick.bind(this.recipe)); document.getElementById("support").addEventListener("click", this.controls.supportButtonClick.bind(this.controls)); this.addMultiEventListeners("#save-texts textarea", "keyup paste", this.controls.saveTextChange, this.controls); @@ -154,6 +155,7 @@ class Manager { // Recipe this.addDynamicListener(".arg:not(select)", "input", this.recipe.ingChange, this.recipe); this.addDynamicListener(".arg[type=checkbox], .arg[type=radio], select.arg", "change", this.recipe.ingChange, this.recipe); + this.addDynamicListener(".hide-args-icon", "click", this.recipe.hideArgsClick, this.recipe); this.addDynamicListener(".disable-icon", "click", this.recipe.disableClick, this.recipe); this.addDynamicListener(".breakpoint", "click", this.recipe.breakpointClick, this.recipe); this.addDynamicListener("#rec-list li.operation", "dblclick", this.recipe.operationDblclick, this.recipe); @@ -227,6 +229,7 @@ class Manager { this.addDynamicListener(".option-item input[type=checkbox]", "change", this.options.switchChange, this.options); this.addDynamicListener(".option-item input[type=checkbox]#wordWrap", "change", this.options.setWordWrap, this.options); this.addDynamicListener(".option-item input[type=checkbox]#useMetaKey", "change", this.bindings.updateKeybList, this.bindings); + this.addDynamicListener(".option-item input[type=checkbox]#showCatCount", "change", this.ops.setCatCount, this.ops); this.addDynamicListener(".option-item input[type=number]", "keyup", this.options.numberChange, this.options); this.addDynamicListener(".option-item input[type=number]", "change", this.options.numberChange, this.options); this.addDynamicListener(".option-item select", "change", this.options.selectChange, this.options); diff --git a/src/web/html/index.html b/src/web/html/index.html index 5c3c3263..38bf7ccc 100755 --- a/src/web/html/index.html +++ b/src/web/html/index.html @@ -1,10 +1,10 @@ -
    -
    +
    @@ -280,17 +284,17 @@ - - - - @@ -518,6 +522,13 @@ Keep the current tab in sync between the input and output
    + +
    + +