pqc-scan 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +117 -2
  3. package/dist/cli.js +89 -0
  4. package/dist/core/cache.js +105 -0
  5. package/dist/core/finding.js +6 -0
  6. package/dist/core/language.js +1 -0
  7. package/dist/core/match.js +30 -0
  8. package/dist/core/matcher.js +49 -0
  9. package/dist/core/parallel.js +92 -0
  10. package/dist/core/rules.js +53 -0
  11. package/dist/core/scan-worker.js +21 -0
  12. package/dist/core/scan.js +164 -0
  13. package/dist/core/syntax.js +61 -0
  14. package/dist/core/tree-sitter.js +21 -0
  15. package/dist/core/types.js +2 -0
  16. package/dist/core/walk.js +28 -0
  17. package/dist/core/wrappers.js +259 -0
  18. package/dist/languages/c/adapter.js +165 -0
  19. package/dist/languages/c/api.js +3 -0
  20. package/dist/languages/cpp/adapter.js +216 -0
  21. package/dist/languages/go/adapter.js +246 -0
  22. package/dist/languages/index.js +7 -0
  23. package/dist/languages/javascript/adapter.js +325 -0
  24. package/dist/languages/rust/adapter.js +276 -0
  25. package/dist/output/baseline.js +51 -0
  26. package/dist/output/cbom.js +145 -0
  27. package/dist/output/json.js +9 -0
  28. package/dist/output/sarif.js +73 -0
  29. package/dist/output/text.js +37 -0
  30. package/grammars/LICENSE-tree-sitter-c +21 -0
  31. package/grammars/LICENSE-tree-sitter-cpp +21 -0
  32. package/grammars/LICENSE-tree-sitter-go +21 -0
  33. package/grammars/LICENSE-tree-sitter-rust +21 -0
  34. package/grammars/tree-sitter-c.wasm +0 -0
  35. package/grammars/tree-sitter-cpp.wasm +0 -0
  36. package/grammars/tree-sitter-go.wasm +0 -0
  37. package/grammars/tree-sitter-rust.wasm +0 -0
  38. package/package.json +62 -4
  39. package/rules/c/README.md +54 -0
  40. package/rules/c/botan.yaml +166 -0
  41. package/rules/c/gnutls.yaml +130 -0
  42. package/rules/c/libsodium.yaml +87 -0
  43. package/rules/c/mbedtls.yaml +214 -0
  44. package/rules/c/openssl.yaml +350 -0
  45. package/rules/c/psa-crypto.yaml +116 -0
  46. package/rules/c/wolfssl.yaml +247 -0
  47. package/rules/cpp/README.md +62 -0
  48. package/rules/cpp/botan.yaml +251 -0
  49. package/rules/cpp/cryptopp.yaml +264 -0
  50. package/rules/go/README.md +64 -0
  51. package/rules/go/circl.yaml +137 -0
  52. package/rules/go/jwt.yaml +120 -0
  53. package/rules/go/stdlib.yaml +391 -0
  54. package/rules/go/x-crypto.yaml +239 -0
  55. package/rules/javascript/README.md +35 -0
  56. package/rules/javascript/jsonwebtoken.yaml +42 -0
  57. package/rules/javascript/jws.yaml +66 -0
  58. package/rules/javascript/node-crypto.yaml +198 -0
  59. package/rules/javascript/webcrypto-polyfills.yaml +3 -0
  60. package/rules/rust/README.md +63 -0
  61. package/rules/rust/jsonwebtoken.yaml +50 -0
  62. package/rules/rust/openssl.yaml +468 -0
  63. package/rules/rust/random.yaml +11 -0
  64. package/rules/rust/ring.yaml +348 -0
  65. package/rules/rust/rustcrypto.yaml +499 -0
  66. package/rules/rust/rustls.yaml +74 -0
  67. package/rules/wrappers.md +46 -0
  68. package/schema/cyclonedx/README.md +5 -0
  69. package/schema/cyclonedx/cryptography-defs.json +4228 -0
  70. package/schema/report-v1.schema.json +55 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # pqc-scan
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```
4
+ /\_/\
5
+ ( 0.1 ) [ pqc-scan • Post-Quantum Cryptography Scanner ]
6
+ > ^ < Finds the cryptography in your JavaScript, TypeScript, C, C++, Rust and Go
7
+ ---------------------------------------------------------
8
+ Looks for what quantum computers will break (NIST FIPS 203/204/205)
9
+ ```
10
+
11
+ **pqc-scan reads your source code, lists the places it uses cryptography, and tells you which of those uses a future quantum computer could break.**
12
+
13
+ *Cryptography* is the mathematics that keeps data secret (encryption), proves who sent something (digital signatures) and fingerprints data (hashing). Each use relies on a specific method, called an *algorithm*, such as RSA or SHA-256. This tool finds the calls to cryptography libraries and reports which algorithm each one uses, or says that it cannot tell.
14
+
15
+ ## In short
16
+
17
+ - **The problem:** RSA and elliptic-curve cryptography are the most widely used methods for digital signatures and for setting up encrypted connections. A large enough quantum computer could break both. None exists yet.
18
+ - **Why act now:** an attacker can record encrypted data today and decrypt it once such a computer exists. NIST calls this "harvest now, decrypt later".
19
+ - **What this tool does:** it finds the uses of cryptography it can recognise in your code (see [Languages](#languages)) and labels each one ❌ breakable by a quantum computer, ✅ believed safe, 🔍 needs a human decision, or ⚠️ could not be determined.
20
+ - **What it does not do:** it never says your code is "quantum safe". It reports only what it can read in the code, and says so when it cannot tell.
21
+ - **Safe to run:** it does not change your code, run it, or send anything over the internet. The only file it writes is the cache, and only if you ask for one with `--cache`.
22
+
23
+ ## Why quantum computers matter
24
+
25
+ Against ordinary computers, a 2048-bit RSA key is rated by NIST at 112 bits of security: the best known attack needs on the order of 2^112 operations, which is out of reach. In 1994 Peter Shor published a method (Shor's algorithm) that would let a large enough quantum computer break RSA and elliptic-curve cryptography.
26
+
27
+ - Today's quantum computers are small. Google's [Willow chip](https://blog.google/technology/research/google-willow-quantum-chip/) (December 2024) has 105 qubits (quantum bits), and they still make errors.
28
+ - A [2025 paper](https://arxiv.org/abs/2505.15917) by Craig Gidney of Google estimated that a 2048-bit RSA key could be broken in under a week by fewer than one million qubits, assuming each operation fails about 1 time in 1,000.
29
+ - The US standards body NIST will deprecate RSA, elliptic-curve and Diffie-Hellman methods after 2030 and disallow them after 2035, at every key size ([NIST IR 8547](https://csrc.nist.gov/pubs/ir/8547/final), October 2026).
30
+
31
+ NIST has published replacements believed to resist quantum computers: ML-KEM (FIPS 203, for agreeing on secret keys), and ML-DSA (FIPS 204) and SLH-DSA (FIPS 205) for signatures. NIST notes that past moves to new algorithms took 10 to 20 years, and recommends beginning with an inventory of the cryptography in use. pqc-scan builds the part of that inventory found in your source code.
32
+
33
+ ## Try it
34
+
35
+ You need [Node.js](https://nodejs.org) 22 or newer. `npm install` downloads about 150 MB: the C, C++, Rust and Go parsers (72 MB), TypeScript (23 MB, used to read JavaScript and TypeScript), and the tools that run the tests.
36
+
37
+ ```sh
38
+ git clone https://github.com/Giddywiddit/pqc-scan.git
39
+ cd pqc-scan
40
+ npm install
41
+ npm run scan -- path/to/your/project
42
+ ```
43
+
44
+ Example result:
45
+
46
+ ```
47
+ Cryptography found:
48
+ ------------------------------------------------------------------------
49
+ ✅ index.ts:3 SHA-256 observed-resistant
50
+ ❌ keys.js:3 RSA vulnerable
51
+ ℹ️ A quantum computer could work out the private key from the public key (using Shor's algorithm). Plan to replace this key type.
52
+ ------------------------------------------------------------------------
53
+ 2 finding(s): 1 vulnerable, 0 needs-review, 0 unresolved, 1 observed-resistant.
54
+
55
+ 🚨 Quantum risk found: the ❌ items use cryptography a quantum computer could break. Plan their migration.
56
+ ```
57
+
58
+ | Option | What it does |
59
+ |---|---|
60
+ | `--json` | Prints the results as JSON for other programs. The format is described by [`schema/report-v1.schema.json`](schema/report-v1.schema.json); its `schemaVersion` changes only when a change could break a program that reads it. |
61
+ | `--quiet` | Hides the cat banner. |
62
+ | `--sarif <file>` | Also writes the ❌, 🔍 and ⚠️ findings to `<file>` in SARIF 2.1.0, the format GitHub code scanning reads, so they appear as alerts on pull requests. ✅ findings are left out, since they need no action. |
63
+ | `--cbom <file>` | Also writes the full inventory to `<file>` as a cryptography bill of materials (CBOM) in CycloneDX 1.7, the format standardised as ECMA-424: one entry per algorithm, with every file and line where it is used, its CycloneDX family and type, and its NIST quantum security category where a NIST standard states one (0 for methods a quantum computer could break). |
64
+ | `--write-baseline <file>` | Also writes every finding to `<file>`, to accept the current findings for now. |
65
+ | `--baseline <file>` | Leaves out the findings listed in `<file>`, so the exit status is 1 only for new ones. A finding is recognised by its rule, file and the text of its line, so it still matches after code above it moves. |
66
+ | `--cache <file>` | Saves each file's results in `<file>` and reuses them on the next run while the file is unchanged. The saved results are discarded whenever the scanner or its rules change. Anyone who can change the cache file can change the results, so keep it outside the folder you scan (the tool refuses a cache inside it), or set the environment variable `PQC_SCAN_CACHE_KEY` to a secret: the cache is then signed, and a cache that was changed or signed with another key is not used. |
67
+ | `--max-file-size <MB>` | Files larger than this (default 20 MB) are not read, and are reported as ⚠️ not scanned. |
68
+
69
+ Exit status: 0 when every finding is ✅ or nothing was found, 1 when any finding is ❌, 🔍 or ⚠️, and 2 when the scan could not run (for example, the path does not exist).
70
+
71
+ ## What the labels mean
72
+
73
+ | Label | Meaning | What you should do |
74
+ |---|---|---|
75
+ | ❌ `vulnerable` | RSA, DSA, elliptic-curve methods (such as ECDSA, Ed25519, ECDH and X25519) or Diffie-Hellman. Shor's algorithm breaks these. | Plan to replace it with a NIST post-quantum method. |
76
+ | ✅ `observed-resistant` | A method believed to withstand quantum computers, such as SHA-256, 256-bit AES or ML-KEM. | Nothing. This describes that one line, not your whole program. |
77
+ | 🔍 `needs-review` | Known exactly, but acceptable only by judgement. Examples: 128-bit AES, which NIST still accepts but some organisations replace with 256-bit AES for a larger safety margin against quantum attacks; SHA-224, whose 112-bit collision strength is a security level NIST plans to disallow in 2030; and MD5 and SHA-1, which are broken even by ordinary computers. | A person decides. |
78
+ | ⚠️ `unresolved` | The code picks the method in a way the tool cannot read, such as a setting read at run time or a value passed into a function. | Look at that line by hand. |
79
+
80
+ ## Languages
81
+
82
+ | Language | Libraries | Details |
83
+ |---|---|---|
84
+ | JavaScript / TypeScript | Node.js crypto, WebCrypto, jsonwebtoken, jws | [rules/javascript](rules/javascript/README.md) |
85
+ | C | OpenSSL, libsodium, Mbed TLS, PSA Crypto, wolfSSL, GnuTLS, Botan | [rules/c](rules/c/README.md) |
86
+ | C++ | Crypto++, Botan, and every C library above | [rules/cpp](rules/cpp/README.md) |
87
+ | Rust | RustCrypto, ring, aws-lc-rs, the openssl crate, rustls, jsonwebtoken | [rules/rust](rules/rust/README.md) |
88
+ | Go | The standard library (including TLS), golang.org/x/crypto (including SSH), CIRCL, golang-jwt, and every C library above through cgo | [rules/go](rules/go/README.md) |
89
+
90
+ Python and Java are planned. Each language page lists what is matched, its limits, and the real projects it was tested on.
91
+
92
+ ## What it cannot see
93
+
94
+ The tool reads code without running it, so it has blind spots. Read these before trusting a result.
95
+
96
+ - **A clean result does not mean "no cryptography".** Cryptography reached in a way the tool cannot follow is missed. Each language page lists those ways.
97
+ - **Only the languages and libraries listed above are covered.** Cryptography inside a package you installed is scanned only if you scan that package's code.
98
+ - **Cryptography a project writes itself**, under its own function names, is not recognised.
99
+ - **It does not inspect** server settings, certificate files or compiled programs. In C, C++, Rust (the openssl crate and rustls) and Go (crypto/tls and x/crypto/ssh), it flags where TLS (the encryption behind HTTPS) or SSH is set up, so you can check the settings yourself.
100
+
101
+ The limits listed on each language page are pinned by automated tests, so they cannot change without anyone noticing.
102
+
103
+ ## How we know it is reliable
104
+
105
+ - **Over 3,000 automated tests** run on every change, including a generated test for every function and algorithm the tool recognises.
106
+ - **Names are checked against the real thing:** the JavaScript names against Node.js itself and the JWT standards (RFC 7518 and RFC 8037) in automated tests, the C and C++ names against each library's header files, the Rust names against each crate's source code, and the Go names against Go's list of every exported name and each library's source code, when the rules were written.
107
+ - **Real projects:** it was run on well-known open-source projects in each language, and its results were compared with a separate text search of the same code. The language pages list the projects and the numbers.
108
+ - **Every fixed bug becomes a permanent test.**
109
+
110
+ Which algorithms count as risky is a judgement call. The decisions are written openly in the [`rules/`](rules/) folder so you can read them and disagree with them.
111
+
112
+ ## Contributing
113
+
114
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for how the code is organised, how to add a library or a language, and how the tests work.
115
+
116
+ ## Licence
117
+
118
+ Released under the [Apache License 2.0](LICENSE).
package/dist/cli.js ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, statSync, writeFileSync } from 'node:fs';
3
+ import { parseArgs } from 'node:util';
4
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
5
+ import { loadRules } from "./core/rules.js";
6
+ import { ResultCache } from "./core/cache.js";
7
+ import { scanInParallel } from "./core/parallel.js";
8
+ import { loadLanguages } from "./core/scan.js";
9
+ import { fingerprints, readBaseline, toBaseline } from "./output/baseline.js";
10
+ import { toCbom } from "./output/cbom.js";
11
+ import { toReport } from "./output/json.js";
12
+ import { toSarif } from "./output/sarif.js";
13
+ import { MASCOT_BANNER, printTable } from "./output/text.js";
14
+ const { values, positionals } = parseArgs({
15
+ allowPositionals: true,
16
+ strict: false,
17
+ options: { json: { type: 'boolean' }, quiet: { type: 'boolean', short: 'q' }, 'no-banner': { type: 'boolean' }, cache: { type: 'string' }, 'max-file-size': { type: 'string' }, sarif: { type: 'string' }, cbom: { type: 'string' }, baseline: { type: 'string' }, 'write-baseline': { type: 'string' } },
18
+ });
19
+ const json = values.json === true;
20
+ const quiet = values.quiet === true || values['no-banner'] === true;
21
+ const target = positionals[0];
22
+ const showBanner = !json && !quiet;
23
+ if (!target) {
24
+ if (showBanner)
25
+ console.log(MASCOT_BANNER);
26
+ console.error('Usage: pqc-scan <path> [--json] [--quiet] [--sarif <file>] [--cbom <file>] [--baseline <file>] [--write-baseline <file>] [--cache <file>] [--max-file-size <MB>]');
27
+ process.exit(2);
28
+ }
29
+ for (const [option, example] of [['cache', '~/.cache/pqc-scan.json'], ['sarif', 'pqc-scan.sarif'], ['cbom', 'cbom.json'], ['baseline', 'pqc-scan-baseline.json'], ['write-baseline', 'pqc-scan-baseline.json']]) {
30
+ if (values[option] !== undefined && typeof values[option] !== 'string') {
31
+ console.error(`pqc-scan: --${option} needs a file name, for example --${option} ${example}`);
32
+ process.exit(2);
33
+ }
34
+ }
35
+ const maxFileSize = values['max-file-size'] === undefined ? undefined : Number(values['max-file-size']);
36
+ if (maxFileSize !== undefined && !(maxFileSize > 0)) {
37
+ console.error('pqc-scan: --max-file-size needs a size in MB greater than 0, for example --max-file-size 50');
38
+ process.exit(2);
39
+ }
40
+ const path = resolve(target);
41
+ if (!existsSync(path)) {
42
+ console.error(`pqc-scan: path not found: ${path}`);
43
+ process.exit(2);
44
+ }
45
+ // A cache inside the folder being scanned could come from the code itself (a commit in a pull request), and a planted
46
+ // cache can hide findings. It is allowed there only when signed with a key (PQC_SCAN_CACHE_KEY) the code cannot know.
47
+ const cacheKey = process.env.PQC_SCAN_CACHE_KEY;
48
+ const cachePath = typeof values.cache === 'string' ? resolve(values.cache) : undefined;
49
+ if (cachePath && !cacheKey) {
50
+ const folder = statSync(path).isDirectory() ? path : dirname(path);
51
+ const inside = relative(folder, cachePath);
52
+ if (!inside.startsWith('..') && !isAbsolute(inside)) {
53
+ console.error(`pqc-scan: the cache file is inside the folder being scanned (${cachePath}). A cache there could be changed by the code being scanned to hide findings. Keep it outside, for example --cache ~/.cache/pqc-scan.json, or set PQC_SCAN_CACHE_KEY to sign it.`);
54
+ process.exit(2);
55
+ }
56
+ }
57
+ if (showBanner)
58
+ console.log(MASCOT_BANNER);
59
+ await loadLanguages();
60
+ const cache = cachePath ? new ResultCache(cachePath, cacheKey) : undefined;
61
+ if (cache?.warning)
62
+ console.error(`pqc-scan: ${cache.warning}`);
63
+ let baseline;
64
+ try {
65
+ baseline = typeof values.baseline === 'string' ? readBaseline(resolve(values.baseline)) : undefined;
66
+ }
67
+ catch (error) {
68
+ console.error(`pqc-scan: ${error instanceof Error ? error.message : String(error)}`);
69
+ process.exit(2);
70
+ }
71
+ const findings = await scanInParallel(path, loadRules(), { cache, maxFileBytes: maxFileSize === undefined ? undefined : maxFileSize * 1024 * 1024 });
72
+ cache?.save();
73
+ const prints = baseline || values.sarif || values['write-baseline'] ? fingerprints(findings, path) : [];
74
+ if (typeof values['write-baseline'] === 'string')
75
+ writeFileSync(resolve(values['write-baseline']), `${JSON.stringify(toBaseline(findings, prints), null, 2)}\n`);
76
+ if (typeof values.sarif === 'string')
77
+ writeFileSync(resolve(values.sarif), JSON.stringify(toSarif(findings, prints, baseline)));
78
+ // The CBOM is the full inventory: every finding, whatever the baseline says.
79
+ if (typeof values.cbom === 'string')
80
+ writeFileSync(resolve(values.cbom), `${JSON.stringify(toCbom(findings, path), null, 2)}\n`);
81
+ // With a baseline, the findings it lists are left out of the output and do not change the exit status.
82
+ const shown = baseline ? findings.filter((_, index) => !baseline.has(prints[index])) : findings;
83
+ const known = baseline ? findings.length - shown.length : undefined;
84
+ if (json)
85
+ console.log(JSON.stringify(toReport(shown, known), null, 2));
86
+ else
87
+ printTable(shown, known);
88
+ // exitCode, not exit(): exiting at once would cut off output still being written to a pipe.
89
+ process.exitCode = shown.some((item) => item.status !== 'observed-resistant') ? 1 : 0;
@@ -0,0 +1,105 @@
1
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const projectRoot = fileURLToPath(new URL('../../', import.meta.url));
7
+ /** The scanner's own code: `src` when working on it, `dist` in the published package. */
8
+ const codeFolder = fileURLToPath(new URL('../', import.meta.url)).slice(projectRoot.length).replace(/[\\/]$/, '');
9
+ const require = createRequire(import.meta.url);
10
+ /**
11
+ * A fingerprint of everything that decides what a scan finds: the scanner's own code, its rules, the grammars and the
12
+ * exact versions of the packages it reads code with. When any of them changes, every cached result is thrown away.
13
+ */
14
+ function toolVersion() {
15
+ const hash = createHash('sha256');
16
+ const add = (directory) => {
17
+ for (const entry of readdirSync(join(projectRoot, directory), { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
18
+ const path = join(directory, entry.name);
19
+ if (entry.isDirectory())
20
+ add(path);
21
+ else
22
+ hash.update(path).update(readFileSync(join(projectRoot, path)));
23
+ }
24
+ };
25
+ add(codeFolder);
26
+ add('rules');
27
+ if (existsSync(join(projectRoot, 'grammars')))
28
+ add('grammars');
29
+ hash.update(readFileSync(join(projectRoot, 'package.json')));
30
+ for (const name of ['typescript', 'web-tree-sitter', 'yaml', 'tree-sitter-c', 'tree-sitter-cpp', 'tree-sitter-rust', 'tree-sitter-go']) {
31
+ try {
32
+ hash.update(`${name}@${JSON.parse(readFileSync(require.resolve(`${name}/package.json`), 'utf8')).version}`);
33
+ }
34
+ catch {
35
+ // The grammar packages are not installed with the published package, which carries their files in grammars/.
36
+ }
37
+ }
38
+ return hash.digest('hex');
39
+ }
40
+ /**
41
+ * Per-file findings saved between runs, keyed by a SHA-256 fingerprint of the file's name and contents. Only the
42
+ * files of the latest scan are kept, so the cache does not grow without limit.
43
+ *
44
+ * Whoever can write the cache file can change what a scan reports, so a cache is only as trustworthy as the place it
45
+ * is kept. With a key, the cache is signed (HMAC-SHA256) and a cache that was changed, or signed with another key, is
46
+ * thrown away: then only someone who has the key can write a cache this scanner will use.
47
+ */
48
+ export class ResultCache {
49
+ version = toolVersion();
50
+ path;
51
+ key;
52
+ previous;
53
+ current = {};
54
+ /** Why an existing cache file was not used, if it was not. */
55
+ warning;
56
+ constructor(path, key) {
57
+ this.path = path;
58
+ this.key = key || undefined;
59
+ let stored;
60
+ let warning;
61
+ try {
62
+ const saved = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : undefined;
63
+ if (saved && this.key && (typeof saved.mac !== 'string' || !this.signatureMatches(saved.body, saved.mac))) {
64
+ warning = `the cache ${path} is not signed with this PQC_SCAN_CACHE_KEY, so it was not used.`;
65
+ }
66
+ else if (saved) {
67
+ stored = JSON.parse(saved.body);
68
+ }
69
+ }
70
+ catch {
71
+ stored = undefined; // An unreadable cache is ignored and rewritten.
72
+ }
73
+ this.warning = warning;
74
+ this.previous = stored?.version === this.version ? stored.files : {};
75
+ }
76
+ sign(body) {
77
+ return createHmac('sha256', this.key).update(body).digest('hex');
78
+ }
79
+ signatureMatches(body, mac) {
80
+ if (typeof body !== 'string')
81
+ return false;
82
+ const expected = Buffer.from(this.sign(body), 'hex');
83
+ const given = Buffer.from(mac, 'hex');
84
+ return given.length === expected.length && timingSafeEqual(given, expected);
85
+ }
86
+ static key(name, text) {
87
+ return createHash('sha256').update(name).update('\0').update(text).digest('hex');
88
+ }
89
+ get(key) {
90
+ const found = Object.hasOwn(this.previous, key) ? this.previous[key] : undefined;
91
+ if (found)
92
+ this.current[key] = found;
93
+ return found;
94
+ }
95
+ set(key, findings) {
96
+ this.current[key] = findings;
97
+ }
98
+ /** Writes to a temporary file first, so an interrupted run never leaves a half-written cache. */
99
+ save() {
100
+ const temporary = `${this.path}.${process.pid}.tmp`;
101
+ const body = JSON.stringify({ version: this.version, files: this.current });
102
+ writeFileSync(temporary, JSON.stringify({ body, ...(this.key ? { mac: this.sign(body) } : {}) }));
103
+ renameSync(temporary, this.path);
104
+ }
105
+ }
@@ -0,0 +1,6 @@
1
+ /** Shared markers: the cross-file check in core recognises a "decided by the caller" finding by these. */
2
+ export const UNRESOLVED_ALGORITHM_NOTE = 'The algorithm comes from a value the tool cannot read here, such as a variable or a setting; check this line by hand.';
3
+ export const ESCAPING_REFERENCE_RULE_ID = 'crypto-reference-escapes';
4
+ export function finding(file, line, ruleId, category, algorithm, status, note, trace = []) {
5
+ return { file, line, ruleId, category, algorithm, status, note, trace };
6
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import { UNRESOLVED_ALGORITHM_NOTE, finding } from "./finding.js";
2
+ /**
3
+ * Turns one call that matched `rule` into findings. Shared by every language so the meaning of a rule is identical
4
+ * everywhere. `resolve` is called only for rules that take the algorithm from an argument.
5
+ */
6
+ export function ruleFindings(rule, file, line, trace, resolve) {
7
+ // `ignore` rules operate on an existing key; the algorithm is reported where the key is created or imported.
8
+ if (rule.ignore)
9
+ return [];
10
+ if (rule.algorithm && rule.status)
11
+ return [finding(file, line, rule.id, rule.category, rule.algorithm, rule.status, rule.note, trace)];
12
+ if (!rule.algorithmFrom)
13
+ return [finding(file, line, rule.id, rule.category, null, 'unresolved', rule.note, trace)];
14
+ const { names, qualifiers } = resolve();
15
+ if (!names)
16
+ return [finding(file, line, rule.id, rule.category, null, 'unresolved', UNRESOLVED_ALGORITHM_NOTE, trace)];
17
+ const values = rule.values ?? {};
18
+ return names.map((value) => {
19
+ const match = lookup(values, value, qualifiers);
20
+ return match
21
+ ? finding(file, line, rule.id, rule.category, match.algorithm, match.status, match.note, trace)
22
+ : finding(file, line, rule.id, rule.category, null, 'unresolved', `Algorithm "${value}" has no rule.`, trace);
23
+ });
24
+ }
25
+ /** Finds a value in a rule table: qualified forms first (`aes-gcm-256`), then exact, then lower case. */
26
+ export function lookup(values, value, qualifiers = []) {
27
+ const base = value.toLowerCase();
28
+ const key = [...qualifiers.map((item) => `${base}-${item.toLowerCase()}`), value, base].find((candidate) => Object.hasOwn(values, candidate));
29
+ return key === undefined ? undefined : values[key];
30
+ }
@@ -0,0 +1,49 @@
1
+ import { ruleFindings } from "./match.js";
2
+ export function indexRules(groups) {
3
+ const index = { functions: new Map(), names: new Map(), mirrors: new Map() };
4
+ for (const group of groups) {
5
+ for (const rule of group.rules) {
6
+ for (const name of rule.functions)
7
+ if (!index.functions.has(name))
8
+ index.functions.set(name, rule);
9
+ for (const name of rule.names ?? [])
10
+ if (!index.names.has(name))
11
+ index.names.set(name, rule);
12
+ }
13
+ for (const [from, to] of Object.entries(group.mirrors ?? {}))
14
+ index.mirrors.set(from, to);
15
+ }
16
+ return index;
17
+ }
18
+ /**
19
+ * Collects one file's findings. A name used twice on one line (`std::unique_ptr<SHA256> p(new SHA256)`) is one use;
20
+ * every call is its own finding. The lines reported are remembered so the parse-error check does not repeat them.
21
+ */
22
+ export class LineReporter {
23
+ seen = new Set();
24
+ file;
25
+ findings;
26
+ reportedLines;
27
+ // Plain fields, not constructor parameter properties: worker threads load this file with Node's type stripping,
28
+ // which does not support them.
29
+ constructor(file, findings = [], reportedLines = new Set()) {
30
+ this.file = file;
31
+ this.findings = findings;
32
+ this.reportedLines = reportedLines;
33
+ }
34
+ /** A use of a name: reported once per rule and line. */
35
+ name(rule, line, note) {
36
+ if (this.seen.has(`${line} ${rule.id}`))
37
+ return;
38
+ this.add(rule, line, ruleFindings(rule, this.file, line, [{ note }], () => ({ names: null, qualifiers: [] })));
39
+ }
40
+ /** A call, whose findings the caller has worked out from its arguments. */
41
+ call(rule, line, findings) {
42
+ this.add(rule, line, findings);
43
+ }
44
+ add(rule, line, findings) {
45
+ this.seen.add(`${line} ${rule.id}`);
46
+ this.reportedLines.add(line);
47
+ this.findings.push(...findings);
48
+ }
49
+ }