ssh-keyaudit-lite 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PyForge (https://py-forge.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,6 @@
1
+ include LICENSE
2
+ include README.md
3
+ include pyproject.toml
4
+ include ssh_keyaudit_lite.py
5
+ include test_ssh_keyaudit_lite.py
6
+ recursive-include fixtures *
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: ssh-keyaudit-lite
3
+ Version: 0.1.0
4
+ Summary: Audit an SSH authorized_keys file: SHA256 fingerprints, key type, bits, comment; flags DSA, weak RSA and comment-less keys. Read-only.
5
+ Author: Alessio Auretto
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/alessio1999xx-debug/ssh-keyaudit-lite
8
+ Project-URL: Pro version, https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory
9
+ Keywords: ssh,authorized-keys,ssh-keys,ssh-key-audit,fingerprint,openssh,security,sysadmin,cli,stdlib
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Operating System :: POSIX
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: System :: Systems Administration
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.9
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Dynamic: license-file
28
+
29
+ # ssh-keyaudit-lite: audit authorized_keys for weak SSH keys, read-only
30
+
31
+ ssh-keyaudit-lite helps with a quick audit of authorized_keys on one machine: it reads one `authorized_keys` file and prints, for every key, the SHA256 fingerprint (same format as `ssh-keygen -lf`), the key type, the key size in bits and the comment. It flags DSA keys, RSA keys below 3072 bits, keys with no comment, and lines that are not valid keys. It exits `1` when something is flagged, so it fits a cron job or a pre-check script. It never edits the file. One file, Python 3.9+ standard library only, MIT.
32
+
33
+ Need to audit a whole fleet, find keys reused across hosts, map keys to owners, or get a removal plan? That is the full [SSH KeyAudit](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) (one-time payment, yours to keep, no subscription). A table later in this README lists what lite does and what the paid tool adds. Or get every PyForge tool, current and future, with the [All-Access Pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) ($99, one payment).
34
+
35
+ - Optional `pip install`, or just download the one file. No config, no state, no network access.
36
+ - Reads one file (default `~/.ssh/authorized_keys`, or a path you pass, or `-` for stdin). Nothing is written.
37
+ - Understands `authorized_keys` options (`from="..."`, `command="..."`, `no-pty`, ...), comments, blank lines and OpenSSH certificates.
38
+ - Fingerprints are computed in Python from the key data; no `ssh-keygen` needed.
39
+ - Flags: `--min-rsa-bits`, `--demo`, `--version`. After `pip install`, use `ssh-keyaudit-lite` in place of `python3 ssh_keyaudit_lite.py`.
40
+
41
+ ![Real terminal demo of `python3 ssh_keyaudit_lite.py --demo`: it flags a weak RSA key, a key with no comment, a DSA key, and an invalid line.](docs/demo.gif)
42
+
43
+ Recorded on November 24, 2026 with asciinema + agg; real command and output, no simulated results. [Recording source](docs/demo.cast) · [Capture script](docs/record-demo.py).
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install ssh-keyaudit-lite
49
+ ssh-keyaudit-lite --help
50
+ ```
51
+
52
+ Or download the single file (Python 3.9+, stdlib only, no extra packages):
53
+
54
+ ```bash
55
+ curl -fsSLO https://raw.githubusercontent.com/alessio1999xx-debug/ssh-keyaudit-lite/main/ssh_keyaudit_lite.py
56
+ python3 ssh_keyaudit_lite.py --help
57
+ ```
58
+
59
+ ## See the output first (offline demo)
60
+
61
+ ```bash
62
+ python3 ssh_keyaudit_lite.py --demo
63
+ # ssh-keyaudit-lite 0.1.0: demo (built-in sample authorized_keys)
64
+ #
65
+ # OK line 2: 256 SHA256:ehngEyw0ibJhOPXM8qj4kHqp7PMOVB8whu2zTPeF2Dc alice@laptop (ED25519)
66
+ # FLAG line 3: 1024 SHA256:8r4r4yg1OcSAK7Bz9sMFslRJNPLryUYiOko0gbhQGOw bob@old-laptop (RSA)
67
+ # - WEAK_RSA: RSA key is 1024 bits, below 3072
68
+ # FLAG line 4: 256 SHA256:qoGqsyZZLKieeTNmmTa5cxqEaRS0oE9CI9MpxJV+VpE no comment (ED25519)
69
+ # - NO_COMMENT: no comment, so the key owner cannot be told from the file
70
+ # FLAG line 5: 1024 SHA256:1+DAnFbM29PkFgyIxsfhJPVm0c/YXZ4Zr1hP+xtf7qI legacy-ci (DSA)
71
+ # - DSA_KEY: DSA keys are deprecated (disabled by default since OpenSSH 7.0, removed in OpenSSH 10.0)
72
+ # FLAG line 6: invalid line
73
+ # - INVALID_LINE: invalid base64 key data (Only base64 data is allowed)
74
+ #
75
+ # 4 key(s): 1 OK, 3 flagged (1 DSA, 1 RSA < 3072 bits, 1 no comment); 1 invalid line(s).
76
+ # Read-only: the file was not changed.
77
+ ```
78
+
79
+ The demo uses a built-in sample file with public test keys.
80
+
81
+ ## Audit your authorized_keys file
82
+
83
+ ```bash
84
+ python3 ssh_keyaudit_lite.py # ~/.ssh/authorized_keys
85
+ python3 ssh_keyaudit_lite.py /home/deploy/.ssh/authorized_keys
86
+ sudo python3 ssh_keyaudit_lite.py /root/.ssh/authorized_keys
87
+ cat authorized_keys | python3 ssh_keyaudit_lite.py - # stdin
88
+ python3 ssh_keyaudit_lite.py --min-rsa-bits 2048 # your own RSA threshold
89
+ ```
90
+
91
+ The part after `line N:` is the same text `ssh-keygen -lf` prints for that key (`<bits> SHA256:<fingerprint> <comment> (<TYPE>)`), so you can match it against `ssh-keygen -lf ~/.ssh/id_ed25519.pub` on the client side.
92
+
93
+ ## What gets flagged
94
+
95
+ | Finding | Meaning |
96
+ | --- | --- |
97
+ | `DSA_KEY` | `ssh-dss` key. DSA has been disabled by default since OpenSSH 7.0 and is removed in OpenSSH 10.0 |
98
+ | `WEAK_RSA` | RSA key smaller than `--min-rsa-bits` (default 3072, the same default as the full SSH KeyAudit) |
99
+ | `NO_COMMENT` | Key without a comment, so you cannot tell from the file whose key it is |
100
+ | `INVALID_LINE` | Line that is not a valid key: unknown type, bad base64, truncated key data, or a type that does not match the key data |
101
+
102
+ Key types read: RSA, DSA, ECDSA (P-256/384/521), Ed25519, the FIDO `sk-` variants, and their OpenSSH certificates (the fingerprint shown for a certificate is the certified key's, as `ssh-keygen -l` does).
103
+
104
+ ## Exit codes for cron
105
+
106
+ | Exit code | Meaning |
107
+ | --- | --- |
108
+ | `0` | No findings (or no keys in the file) |
109
+ | `1` | At least one key or line was flagged |
110
+ | `2` | File not readable, or bad arguments |
111
+
112
+ ```bash
113
+ # crontab: check every Monday at 07:00, keep the last report
114
+ 0 7 * * 1 python3 /opt/ssh_keyaudit_lite.py /home/deploy/.ssh/authorized_keys > /var/log/ssh-keyaudit-lite.txt 2>&1
115
+ ```
116
+
117
+ ## Already using ssh-keygen -l?
118
+
119
+ `ssh-keygen -lf` already lists type, bits, SHA256 fingerprint and comment for every key in the file. It wins when that is all you need and OpenSSH is installed. This tool adds structured FLAG/OK findings — DSA, RSA below `--min-rsa-bits` (default 3072), missing comments, invalid lines — a cron exit code `1` on findings, and it does not need `ssh-keygen`. It is not a replacement for `ssh-audit`, which checks server/protocol config, not `authorized_keys`.
120
+
121
+ ## ssh-keyaudit-lite vs SSH KeyAudit
122
+
123
+ ssh-keyaudit-lite reads one local `authorized_keys` file and prints a plain-text list. That's it.
124
+
125
+ The full [SSH KeyAudit](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) scans a list of hosts through your own `ssh` client (it reads every readable `authorized_keys` on each host), finds the same key on several hosts, maps keys to owners from a simple owners file, flags offboarded and unknown owners and keys without restricting options, compares against the previous run, and writes a removal script that you review and run yourself. One-time payment, yours to keep. No subscription.
126
+
127
+ Lite is not a strict subset: the `NO_COMMENT` flag and the `0` / `1` exit code on findings are not in the paid tool.
128
+
129
+ | Capability | Lite (free) | Paid SSH KeyAudit |
130
+ | --- | --- | --- |
131
+ | One local `authorized_keys` file (or stdin) | Yes | Yes |
132
+ | SHA256 fingerprint, type, bits, comment | Yes | Yes |
133
+ | DSA keys, RSA below a threshold (default 3072) | Yes | Yes |
134
+ | Invalid lines reported | Yes | Yes |
135
+ | Keys without a comment | Yes | No |
136
+ | Fleet scan of many hosts through your own `ssh` (`--hosts`) | No | Yes |
137
+ | Same key reused across hosts | No | Yes |
138
+ | Owner mapping, offboarded / unknown owners (`--owners`) | No | Yes |
139
+ | Keys without restricting options (`from=`, `command=`, ...) | No | Yes |
140
+ | Diff against the previous run (`--out-state`, `--diff`) | No | Yes |
141
+ | Removal plan script you review and run (`--out-plan`, never run by the tool) | No | Yes |
142
+ | Output | Plain text | Text or JSON (`--json`) |
143
+ | Exit code `1` when something is flagged | Yes | No (exits `0` with findings) |
144
+
145
+ Neither version edits `authorized_keys` files by itself.
146
+
147
+ > Need the full version? **SSH KeyAudit** on PyForge:
148
+ > [py-forge.com/products/ssh-keyaudit-fleet-key-inventory](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite)
149
+ >
150
+ > Or get every PyForge tool, current and future, with the All-Access Pass ($99, one payment):
151
+ > [py-forge.com/pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite)
152
+
153
+ ## Tests
154
+
155
+ ```bash
156
+ python3 test_ssh_keyaudit_lite.py
157
+ ```
158
+
159
+ The tests are offline. The fixture keys in `fixtures/` are public keys generated with `ssh-keygen` (private halves discarded), with the recorded `ssh-keygen -lf` output. When `ssh-keygen` is installed the tests also compare against a live `ssh-keygen -lf` run.
160
+
161
+ ## License
162
+
163
+ MIT (this lite version). The full SSH KeyAudit is sold separately under its own license.
@@ -0,0 +1,135 @@
1
+ # ssh-keyaudit-lite: audit authorized_keys for weak SSH keys, read-only
2
+
3
+ ssh-keyaudit-lite helps with a quick audit of authorized_keys on one machine: it reads one `authorized_keys` file and prints, for every key, the SHA256 fingerprint (same format as `ssh-keygen -lf`), the key type, the key size in bits and the comment. It flags DSA keys, RSA keys below 3072 bits, keys with no comment, and lines that are not valid keys. It exits `1` when something is flagged, so it fits a cron job or a pre-check script. It never edits the file. One file, Python 3.9+ standard library only, MIT.
4
+
5
+ Need to audit a whole fleet, find keys reused across hosts, map keys to owners, or get a removal plan? That is the full [SSH KeyAudit](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) (one-time payment, yours to keep, no subscription). A table later in this README lists what lite does and what the paid tool adds. Or get every PyForge tool, current and future, with the [All-Access Pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) ($99, one payment).
6
+
7
+ - Optional `pip install`, or just download the one file. No config, no state, no network access.
8
+ - Reads one file (default `~/.ssh/authorized_keys`, or a path you pass, or `-` for stdin). Nothing is written.
9
+ - Understands `authorized_keys` options (`from="..."`, `command="..."`, `no-pty`, ...), comments, blank lines and OpenSSH certificates.
10
+ - Fingerprints are computed in Python from the key data; no `ssh-keygen` needed.
11
+ - Flags: `--min-rsa-bits`, `--demo`, `--version`. After `pip install`, use `ssh-keyaudit-lite` in place of `python3 ssh_keyaudit_lite.py`.
12
+
13
+ ![Real terminal demo of `python3 ssh_keyaudit_lite.py --demo`: it flags a weak RSA key, a key with no comment, a DSA key, and an invalid line.](docs/demo.gif)
14
+
15
+ Recorded on November 24, 2026 with asciinema + agg; real command and output, no simulated results. [Recording source](docs/demo.cast) · [Capture script](docs/record-demo.py).
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install ssh-keyaudit-lite
21
+ ssh-keyaudit-lite --help
22
+ ```
23
+
24
+ Or download the single file (Python 3.9+, stdlib only, no extra packages):
25
+
26
+ ```bash
27
+ curl -fsSLO https://raw.githubusercontent.com/alessio1999xx-debug/ssh-keyaudit-lite/main/ssh_keyaudit_lite.py
28
+ python3 ssh_keyaudit_lite.py --help
29
+ ```
30
+
31
+ ## See the output first (offline demo)
32
+
33
+ ```bash
34
+ python3 ssh_keyaudit_lite.py --demo
35
+ # ssh-keyaudit-lite 0.1.0: demo (built-in sample authorized_keys)
36
+ #
37
+ # OK line 2: 256 SHA256:ehngEyw0ibJhOPXM8qj4kHqp7PMOVB8whu2zTPeF2Dc alice@laptop (ED25519)
38
+ # FLAG line 3: 1024 SHA256:8r4r4yg1OcSAK7Bz9sMFslRJNPLryUYiOko0gbhQGOw bob@old-laptop (RSA)
39
+ # - WEAK_RSA: RSA key is 1024 bits, below 3072
40
+ # FLAG line 4: 256 SHA256:qoGqsyZZLKieeTNmmTa5cxqEaRS0oE9CI9MpxJV+VpE no comment (ED25519)
41
+ # - NO_COMMENT: no comment, so the key owner cannot be told from the file
42
+ # FLAG line 5: 1024 SHA256:1+DAnFbM29PkFgyIxsfhJPVm0c/YXZ4Zr1hP+xtf7qI legacy-ci (DSA)
43
+ # - DSA_KEY: DSA keys are deprecated (disabled by default since OpenSSH 7.0, removed in OpenSSH 10.0)
44
+ # FLAG line 6: invalid line
45
+ # - INVALID_LINE: invalid base64 key data (Only base64 data is allowed)
46
+ #
47
+ # 4 key(s): 1 OK, 3 flagged (1 DSA, 1 RSA < 3072 bits, 1 no comment); 1 invalid line(s).
48
+ # Read-only: the file was not changed.
49
+ ```
50
+
51
+ The demo uses a built-in sample file with public test keys.
52
+
53
+ ## Audit your authorized_keys file
54
+
55
+ ```bash
56
+ python3 ssh_keyaudit_lite.py # ~/.ssh/authorized_keys
57
+ python3 ssh_keyaudit_lite.py /home/deploy/.ssh/authorized_keys
58
+ sudo python3 ssh_keyaudit_lite.py /root/.ssh/authorized_keys
59
+ cat authorized_keys | python3 ssh_keyaudit_lite.py - # stdin
60
+ python3 ssh_keyaudit_lite.py --min-rsa-bits 2048 # your own RSA threshold
61
+ ```
62
+
63
+ The part after `line N:` is the same text `ssh-keygen -lf` prints for that key (`<bits> SHA256:<fingerprint> <comment> (<TYPE>)`), so you can match it against `ssh-keygen -lf ~/.ssh/id_ed25519.pub` on the client side.
64
+
65
+ ## What gets flagged
66
+
67
+ | Finding | Meaning |
68
+ | --- | --- |
69
+ | `DSA_KEY` | `ssh-dss` key. DSA has been disabled by default since OpenSSH 7.0 and is removed in OpenSSH 10.0 |
70
+ | `WEAK_RSA` | RSA key smaller than `--min-rsa-bits` (default 3072, the same default as the full SSH KeyAudit) |
71
+ | `NO_COMMENT` | Key without a comment, so you cannot tell from the file whose key it is |
72
+ | `INVALID_LINE` | Line that is not a valid key: unknown type, bad base64, truncated key data, or a type that does not match the key data |
73
+
74
+ Key types read: RSA, DSA, ECDSA (P-256/384/521), Ed25519, the FIDO `sk-` variants, and their OpenSSH certificates (the fingerprint shown for a certificate is the certified key's, as `ssh-keygen -l` does).
75
+
76
+ ## Exit codes for cron
77
+
78
+ | Exit code | Meaning |
79
+ | --- | --- |
80
+ | `0` | No findings (or no keys in the file) |
81
+ | `1` | At least one key or line was flagged |
82
+ | `2` | File not readable, or bad arguments |
83
+
84
+ ```bash
85
+ # crontab: check every Monday at 07:00, keep the last report
86
+ 0 7 * * 1 python3 /opt/ssh_keyaudit_lite.py /home/deploy/.ssh/authorized_keys > /var/log/ssh-keyaudit-lite.txt 2>&1
87
+ ```
88
+
89
+ ## Already using ssh-keygen -l?
90
+
91
+ `ssh-keygen -lf` already lists type, bits, SHA256 fingerprint and comment for every key in the file. It wins when that is all you need and OpenSSH is installed. This tool adds structured FLAG/OK findings — DSA, RSA below `--min-rsa-bits` (default 3072), missing comments, invalid lines — a cron exit code `1` on findings, and it does not need `ssh-keygen`. It is not a replacement for `ssh-audit`, which checks server/protocol config, not `authorized_keys`.
92
+
93
+ ## ssh-keyaudit-lite vs SSH KeyAudit
94
+
95
+ ssh-keyaudit-lite reads one local `authorized_keys` file and prints a plain-text list. That's it.
96
+
97
+ The full [SSH KeyAudit](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) scans a list of hosts through your own `ssh` client (it reads every readable `authorized_keys` on each host), finds the same key on several hosts, maps keys to owners from a simple owners file, flags offboarded and unknown owners and keys without restricting options, compares against the previous run, and writes a removal script that you review and run yourself. One-time payment, yours to keep. No subscription.
98
+
99
+ Lite is not a strict subset: the `NO_COMMENT` flag and the `0` / `1` exit code on findings are not in the paid tool.
100
+
101
+ | Capability | Lite (free) | Paid SSH KeyAudit |
102
+ | --- | --- | --- |
103
+ | One local `authorized_keys` file (or stdin) | Yes | Yes |
104
+ | SHA256 fingerprint, type, bits, comment | Yes | Yes |
105
+ | DSA keys, RSA below a threshold (default 3072) | Yes | Yes |
106
+ | Invalid lines reported | Yes | Yes |
107
+ | Keys without a comment | Yes | No |
108
+ | Fleet scan of many hosts through your own `ssh` (`--hosts`) | No | Yes |
109
+ | Same key reused across hosts | No | Yes |
110
+ | Owner mapping, offboarded / unknown owners (`--owners`) | No | Yes |
111
+ | Keys without restricting options (`from=`, `command=`, ...) | No | Yes |
112
+ | Diff against the previous run (`--out-state`, `--diff`) | No | Yes |
113
+ | Removal plan script you review and run (`--out-plan`, never run by the tool) | No | Yes |
114
+ | Output | Plain text | Text or JSON (`--json`) |
115
+ | Exit code `1` when something is flagged | Yes | No (exits `0` with findings) |
116
+
117
+ Neither version edits `authorized_keys` files by itself.
118
+
119
+ > Need the full version? **SSH KeyAudit** on PyForge:
120
+ > [py-forge.com/products/ssh-keyaudit-fleet-key-inventory](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite)
121
+ >
122
+ > Or get every PyForge tool, current and future, with the All-Access Pass ($99, one payment):
123
+ > [py-forge.com/pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite)
124
+
125
+ ## Tests
126
+
127
+ ```bash
128
+ python3 test_ssh_keyaudit_lite.py
129
+ ```
130
+
131
+ The tests are offline. The fixture keys in `fixtures/` are public keys generated with `ssh-keygen` (private halves discarded), with the recorded `ssh-keygen -lf` output. When `ssh-keygen` is installed the tests also compare against a live `ssh-keygen -lf` run.
132
+
133
+ ## License
134
+
135
+ MIT (this lite version). The full SSH KeyAudit is sold separately under its own license.
@@ -0,0 +1,11 @@
1
+ # Sample authorized_keys for ssh-keyaudit-lite tests (public keys only, private halves discarded)
2
+
3
+ ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF2qygAXG2+jbV8W50Nq9rY7zGDvoLFg2K2z/DAYZMh3 alice@laptop
4
+ from="10.0.0.0/8",no-agent-forwarding ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDf1whlEwjvnsN7IGa+42mS3b8n68tD6m8oPqjnqeNU0lV4W/qIpjN0kDoOk6H/c4/kAyDuCYBdqN0JoXQtzR1dEBOAkKcegtTOY7jur6gF1j5MnvHYWV2hi+QWRT+9yMS4uD9KMGznurrI2sICIuiQ+79lz3RYJRikzhkXZBnMD/pPkMkkt/lOlZ91NFrRI3OMzmwyBgYK6bwQmCRdvsifPHaJoGOyZDDlIlZohAbibqvQlMMnDFEamcLO4JaU/xO5128LaZk5wnGDTfnMlX6EAk0LLuAi56219zegqpxj7OgDyF6Tamx0aAik207EJOpoSs1TRIlT5+zEV9NwJaLBPM7Y8Setedqsi0GWgJ27xwY11orQUCyHtZY2+2PPjMKqli5DCnkfhy8Go4Pcfa9LoZ6nLrBPZEejAP2YIqP87xBZnJlRHBiI1Q3DL0s6Qz+MA1uQ/6F89Uwi9pOrPhbgG3ptnOTNxQTvethHGX6cNCJ8hRjWjOr8EqjCMqntnJNwvFreUt+SC/nd0f5UNaaOVOkK2rmvxNCFBn/cXmtFv1NXz5dMcvERrAYtJEeW7tuVG2MujP33pmHk2CsraNM86TbVS9Cclii5+lSPTlL/jY2LuKbQEpGrvn892xdEmT7IWVajFCLggS3oBoZdzpc0501H9Wwp/RAchLlhrwKwEQ== backup-operator
5
+ command="/usr/local/bin/backup --mode \"full run\"",no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQChHGCMksuqc8MEwPhKkdR6NwSB5V+lDNEFACUvkGJnw53MZkgDpCPtb20n+r0dRplLaCDqTjtAC+9uDp4cyz1FrLGUnCUXn7JfK3ejsrGhuA6Y8XAXVIzl6z4JZrm3rrKkjtVDuYkb8eMB1W3tg1c8UXFBIVVRJYPLQCRZSQMmtor41hwW4TqA0gnW4ECDrdoS6J92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ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF2qygAXG2+jbV8W50Nq9rY7zGDvoLFg2K2z/DAYZMh3 alice@laptop
@@ -0,0 +1,10 @@
1
+ ed25519.pub 256 SHA256:ehngEyw0ibJhOPXM8qj4kHqp7PMOVB8whu2zTPeF2Dc alice@laptop (ED25519)
2
+ rsa4096.pub 4096 SHA256:YE8FEFZjODLOjYm/My9iTHTaPVIoNfzVnpIc7ODEK6k backup-operator (RSA)
3
+ rsa1024.pub 1024 SHA256:8r4r4yg1OcSAK7Bz9sMFslRJNPLryUYiOko0gbhQGOw bob@old-laptop (RSA)
4
+ rsa2048.pub 2048 SHA256:/1/QEpOeQVtvWZuT+6rQxa8iV09ZBUbt10r506bfYSo ci-deploy (RSA)
5
+ ecdsa256.pub 256 SHA256:cADIGwFYcKmqONSPo1TvGvPPYPRql0loouUXQr+NPGk carol@desk (ECDSA)
6
+ ecdsa384.pub 384 SHA256:BOVTTha9Oo+JVnOfyusmiL8oQPbxB+oYJ/7N/1cfrvQ dave@desk (ECDSA)
7
+ ecdsa521.pub 521 SHA256:XPaW0JDPhuLcQavVxz1/lhzZzpo6Vh1MlfACaNlr2b0 erin@desk (ECDSA)
8
+ nocomment.pub 256 SHA256:qoGqsyZZLKieeTNmmTa5cxqEaRS0oE9CI9MpxJV+VpE no comment (ED25519)
9
+ dsa1024.pub 1024 SHA256:1+DAnFbM29PkFgyIxsfhJPVm0c/YXZ4Zr1hP+xtf7qI legacy-ci (DSA)
10
+ ed25519-cert.pub 256 SHA256:ehngEyw0ibJhOPXM8qj4kHqp7PMOVB8whu2zTPeF2Dc alice@laptop (ED25519-CERT)
@@ -0,0 +1 @@
1
+ ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA6yhSu/pEz3TK/5/D3Sxc78vKyb+m4DuFhEdDaux0cL
@@ -0,0 +1 @@
1
+ ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCjbTjcefm9hye2rZNztr7v23FSCwNngeMq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OrPhbgG3ptnOTNxQTvethHGX6cNCJ8hRjWjOr8EqjCMqntnJNwvFreUt+SC/nd0f5UNaaOVOkK2rmvxNCFBn/cXmtFv1NXz5dMcvERrAYtJEeW7tuVG2MujP33pmHk2CsraNM86TbVS9Cclii5+lSPTlL/jY2LuKbQEpGrvn892xdEmT7IWVajFCLggS3oBoZdzpc0501H9Wwp/RAchLlhrwKwEQ== backup-operator
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ssh-keyaudit-lite"
7
+ version = "0.1.0"
8
+ description = "Audit an SSH authorized_keys file: SHA256 fingerprints, key type, bits, comment; flags DSA, weak RSA and comment-less keys. Read-only."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [{name = "Alessio Auretto"}]
14
+ keywords = [
15
+ "ssh",
16
+ "authorized-keys",
17
+ "ssh-keys",
18
+ "ssh-key-audit",
19
+ "fingerprint",
20
+ "openssh",
21
+ "security",
22
+ "sysadmin",
23
+ "cli",
24
+ "stdlib",
25
+ ]
26
+ classifiers = [
27
+ "Development Status :: 4 - Beta",
28
+ "Environment :: Console",
29
+ "Intended Audience :: Developers",
30
+ "Intended Audience :: System Administrators",
31
+ "Operating System :: POSIX",
32
+ "Programming Language :: Python :: 3",
33
+ "Programming Language :: Python :: 3.9",
34
+ "Programming Language :: Python :: 3.10",
35
+ "Programming Language :: Python :: 3.11",
36
+ "Programming Language :: Python :: 3.12",
37
+ "Programming Language :: Python :: 3.13",
38
+ "Topic :: Security",
39
+ "Topic :: System :: Systems Administration",
40
+ "Topic :: Utilities",
41
+ ]
42
+
43
+ [project.urls]
44
+ Homepage = "https://github.com/alessio1999xx-debug/ssh-keyaudit-lite"
45
+ "Pro version" = "https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory"
46
+
47
+ [project.scripts]
48
+ ssh-keyaudit-lite = "ssh_keyaudit_lite:main"
49
+
50
+ [tool.setuptools]
51
+ py-modules = ["ssh_keyaudit_lite"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: ssh-keyaudit-lite
3
+ Version: 0.1.0
4
+ Summary: Audit an SSH authorized_keys file: SHA256 fingerprints, key type, bits, comment; flags DSA, weak RSA and comment-less keys. Read-only.
5
+ Author: Alessio Auretto
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/alessio1999xx-debug/ssh-keyaudit-lite
8
+ Project-URL: Pro version, https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory
9
+ Keywords: ssh,authorized-keys,ssh-keys,ssh-key-audit,fingerprint,openssh,security,sysadmin,cli,stdlib
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Operating System :: POSIX
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: System :: Systems Administration
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.9
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Dynamic: license-file
28
+
29
+ # ssh-keyaudit-lite: audit authorized_keys for weak SSH keys, read-only
30
+
31
+ ssh-keyaudit-lite helps with a quick audit of authorized_keys on one machine: it reads one `authorized_keys` file and prints, for every key, the SHA256 fingerprint (same format as `ssh-keygen -lf`), the key type, the key size in bits and the comment. It flags DSA keys, RSA keys below 3072 bits, keys with no comment, and lines that are not valid keys. It exits `1` when something is flagged, so it fits a cron job or a pre-check script. It never edits the file. One file, Python 3.9+ standard library only, MIT.
32
+
33
+ Need to audit a whole fleet, find keys reused across hosts, map keys to owners, or get a removal plan? That is the full [SSH KeyAudit](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) (one-time payment, yours to keep, no subscription). A table later in this README lists what lite does and what the paid tool adds. Or get every PyForge tool, current and future, with the [All-Access Pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) ($99, one payment).
34
+
35
+ - Optional `pip install`, or just download the one file. No config, no state, no network access.
36
+ - Reads one file (default `~/.ssh/authorized_keys`, or a path you pass, or `-` for stdin). Nothing is written.
37
+ - Understands `authorized_keys` options (`from="..."`, `command="..."`, `no-pty`, ...), comments, blank lines and OpenSSH certificates.
38
+ - Fingerprints are computed in Python from the key data; no `ssh-keygen` needed.
39
+ - Flags: `--min-rsa-bits`, `--demo`, `--version`. After `pip install`, use `ssh-keyaudit-lite` in place of `python3 ssh_keyaudit_lite.py`.
40
+
41
+ ![Real terminal demo of `python3 ssh_keyaudit_lite.py --demo`: it flags a weak RSA key, a key with no comment, a DSA key, and an invalid line.](docs/demo.gif)
42
+
43
+ Recorded on November 24, 2026 with asciinema + agg; real command and output, no simulated results. [Recording source](docs/demo.cast) · [Capture script](docs/record-demo.py).
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install ssh-keyaudit-lite
49
+ ssh-keyaudit-lite --help
50
+ ```
51
+
52
+ Or download the single file (Python 3.9+, stdlib only, no extra packages):
53
+
54
+ ```bash
55
+ curl -fsSLO https://raw.githubusercontent.com/alessio1999xx-debug/ssh-keyaudit-lite/main/ssh_keyaudit_lite.py
56
+ python3 ssh_keyaudit_lite.py --help
57
+ ```
58
+
59
+ ## See the output first (offline demo)
60
+
61
+ ```bash
62
+ python3 ssh_keyaudit_lite.py --demo
63
+ # ssh-keyaudit-lite 0.1.0: demo (built-in sample authorized_keys)
64
+ #
65
+ # OK line 2: 256 SHA256:ehngEyw0ibJhOPXM8qj4kHqp7PMOVB8whu2zTPeF2Dc alice@laptop (ED25519)
66
+ # FLAG line 3: 1024 SHA256:8r4r4yg1OcSAK7Bz9sMFslRJNPLryUYiOko0gbhQGOw bob@old-laptop (RSA)
67
+ # - WEAK_RSA: RSA key is 1024 bits, below 3072
68
+ # FLAG line 4: 256 SHA256:qoGqsyZZLKieeTNmmTa5cxqEaRS0oE9CI9MpxJV+VpE no comment (ED25519)
69
+ # - NO_COMMENT: no comment, so the key owner cannot be told from the file
70
+ # FLAG line 5: 1024 SHA256:1+DAnFbM29PkFgyIxsfhJPVm0c/YXZ4Zr1hP+xtf7qI legacy-ci (DSA)
71
+ # - DSA_KEY: DSA keys are deprecated (disabled by default since OpenSSH 7.0, removed in OpenSSH 10.0)
72
+ # FLAG line 6: invalid line
73
+ # - INVALID_LINE: invalid base64 key data (Only base64 data is allowed)
74
+ #
75
+ # 4 key(s): 1 OK, 3 flagged (1 DSA, 1 RSA < 3072 bits, 1 no comment); 1 invalid line(s).
76
+ # Read-only: the file was not changed.
77
+ ```
78
+
79
+ The demo uses a built-in sample file with public test keys.
80
+
81
+ ## Audit your authorized_keys file
82
+
83
+ ```bash
84
+ python3 ssh_keyaudit_lite.py # ~/.ssh/authorized_keys
85
+ python3 ssh_keyaudit_lite.py /home/deploy/.ssh/authorized_keys
86
+ sudo python3 ssh_keyaudit_lite.py /root/.ssh/authorized_keys
87
+ cat authorized_keys | python3 ssh_keyaudit_lite.py - # stdin
88
+ python3 ssh_keyaudit_lite.py --min-rsa-bits 2048 # your own RSA threshold
89
+ ```
90
+
91
+ The part after `line N:` is the same text `ssh-keygen -lf` prints for that key (`<bits> SHA256:<fingerprint> <comment> (<TYPE>)`), so you can match it against `ssh-keygen -lf ~/.ssh/id_ed25519.pub` on the client side.
92
+
93
+ ## What gets flagged
94
+
95
+ | Finding | Meaning |
96
+ | --- | --- |
97
+ | `DSA_KEY` | `ssh-dss` key. DSA has been disabled by default since OpenSSH 7.0 and is removed in OpenSSH 10.0 |
98
+ | `WEAK_RSA` | RSA key smaller than `--min-rsa-bits` (default 3072, the same default as the full SSH KeyAudit) |
99
+ | `NO_COMMENT` | Key without a comment, so you cannot tell from the file whose key it is |
100
+ | `INVALID_LINE` | Line that is not a valid key: unknown type, bad base64, truncated key data, or a type that does not match the key data |
101
+
102
+ Key types read: RSA, DSA, ECDSA (P-256/384/521), Ed25519, the FIDO `sk-` variants, and their OpenSSH certificates (the fingerprint shown for a certificate is the certified key's, as `ssh-keygen -l` does).
103
+
104
+ ## Exit codes for cron
105
+
106
+ | Exit code | Meaning |
107
+ | --- | --- |
108
+ | `0` | No findings (or no keys in the file) |
109
+ | `1` | At least one key or line was flagged |
110
+ | `2` | File not readable, or bad arguments |
111
+
112
+ ```bash
113
+ # crontab: check every Monday at 07:00, keep the last report
114
+ 0 7 * * 1 python3 /opt/ssh_keyaudit_lite.py /home/deploy/.ssh/authorized_keys > /var/log/ssh-keyaudit-lite.txt 2>&1
115
+ ```
116
+
117
+ ## Already using ssh-keygen -l?
118
+
119
+ `ssh-keygen -lf` already lists type, bits, SHA256 fingerprint and comment for every key in the file. It wins when that is all you need and OpenSSH is installed. This tool adds structured FLAG/OK findings — DSA, RSA below `--min-rsa-bits` (default 3072), missing comments, invalid lines — a cron exit code `1` on findings, and it does not need `ssh-keygen`. It is not a replacement for `ssh-audit`, which checks server/protocol config, not `authorized_keys`.
120
+
121
+ ## ssh-keyaudit-lite vs SSH KeyAudit
122
+
123
+ ssh-keyaudit-lite reads one local `authorized_keys` file and prints a plain-text list. That's it.
124
+
125
+ The full [SSH KeyAudit](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite) scans a list of hosts through your own `ssh` client (it reads every readable `authorized_keys` on each host), finds the same key on several hosts, maps keys to owners from a simple owners file, flags offboarded and unknown owners and keys without restricting options, compares against the previous run, and writes a removal script that you review and run yourself. One-time payment, yours to keep. No subscription.
126
+
127
+ Lite is not a strict subset: the `NO_COMMENT` flag and the `0` / `1` exit code on findings are not in the paid tool.
128
+
129
+ | Capability | Lite (free) | Paid SSH KeyAudit |
130
+ | --- | --- | --- |
131
+ | One local `authorized_keys` file (or stdin) | Yes | Yes |
132
+ | SHA256 fingerprint, type, bits, comment | Yes | Yes |
133
+ | DSA keys, RSA below a threshold (default 3072) | Yes | Yes |
134
+ | Invalid lines reported | Yes | Yes |
135
+ | Keys without a comment | Yes | No |
136
+ | Fleet scan of many hosts through your own `ssh` (`--hosts`) | No | Yes |
137
+ | Same key reused across hosts | No | Yes |
138
+ | Owner mapping, offboarded / unknown owners (`--owners`) | No | Yes |
139
+ | Keys without restricting options (`from=`, `command=`, ...) | No | Yes |
140
+ | Diff against the previous run (`--out-state`, `--diff`) | No | Yes |
141
+ | Removal plan script you review and run (`--out-plan`, never run by the tool) | No | Yes |
142
+ | Output | Plain text | Text or JSON (`--json`) |
143
+ | Exit code `1` when something is flagged | Yes | No (exits `0` with findings) |
144
+
145
+ Neither version edits `authorized_keys` files by itself.
146
+
147
+ > Need the full version? **SSH KeyAudit** on PyForge:
148
+ > [py-forge.com/products/ssh-keyaudit-fleet-key-inventory](https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite)
149
+ >
150
+ > Or get every PyForge tool, current and future, with the All-Access Pass ($99, one payment):
151
+ > [py-forge.com/pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite)
152
+
153
+ ## Tests
154
+
155
+ ```bash
156
+ python3 test_ssh_keyaudit_lite.py
157
+ ```
158
+
159
+ The tests are offline. The fixture keys in `fixtures/` are public keys generated with `ssh-keygen` (private halves discarded), with the recorded `ssh-keygen -lf` output. When `ssh-keygen` is installed the tests also compare against a live `ssh-keygen -lf` run.
160
+
161
+ ## License
162
+
163
+ MIT (this lite version). The full SSH KeyAudit is sold separately under its own license.
@@ -0,0 +1,23 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ ssh_keyaudit_lite.py
6
+ test_ssh_keyaudit_lite.py
7
+ fixtures/authorized_keys_sample
8
+ fixtures/dsa1024.pub
9
+ fixtures/ecdsa256.pub
10
+ fixtures/ecdsa384.pub
11
+ fixtures/ecdsa521.pub
12
+ fixtures/ed25519-cert.pub
13
+ fixtures/ed25519.pub
14
+ fixtures/expected_fingerprints.txt
15
+ fixtures/nocomment.pub
16
+ fixtures/rsa1024.pub
17
+ fixtures/rsa2048.pub
18
+ fixtures/rsa4096.pub
19
+ ssh_keyaudit_lite.egg-info/PKG-INFO
20
+ ssh_keyaudit_lite.egg-info/SOURCES.txt
21
+ ssh_keyaudit_lite.egg-info/dependency_links.txt
22
+ ssh_keyaudit_lite.egg-info/entry_points.txt
23
+ ssh_keyaudit_lite.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ssh-keyaudit-lite = ssh_keyaudit_lite:main
@@ -0,0 +1 @@
1
+ ssh_keyaudit_lite
@@ -0,0 +1,361 @@
1
+ #!/usr/bin/env python3
2
+ """ssh-keyaudit-lite: audit one SSH authorized_keys file (read-only).
3
+
4
+ Reads a single authorized_keys file (default ~/.ssh/authorized_keys) and prints,
5
+ for every key, the SHA256 fingerprint in the same format as `ssh-keygen -lf`,
6
+ the key type, the key size in bits and the comment. It flags DSA keys, RSA
7
+ keys below a minimum size (default 3072 bits), keys without a comment, and
8
+ lines that are not valid keys. It never edits the file.
9
+
10
+ Python 3.9+ standard library only. MIT license.
11
+
12
+ Exit codes: 0 = no findings, 1 = at least one key or line was flagged,
13
+ 2 = error (file not readable, bad arguments).
14
+
15
+ Full version (fleet scan over your own ssh, keys reused across hosts, owner
16
+ mapping, offboarded/unknown owners, removal plan script, JSON report):
17
+ https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite
18
+ """
19
+
20
+ import argparse
21
+ import base64
22
+ import binascii
23
+ import hashlib
24
+ import os
25
+ import sys
26
+ from typing import Dict, List, Optional, Tuple
27
+
28
+ __version__ = "0.1.0"
29
+
30
+ DEFAULT_FILE = os.path.join("~", ".ssh", "authorized_keys")
31
+ DEFAULT_MIN_RSA_BITS = 3072
32
+ PRO_URL = (
33
+ "https://py-forge.com/products/ssh-keyaudit-fleet-key-inventory"
34
+ "?utm_source=github&utm_medium=readme&utm_campaign=ssh-keyaudit-lite"
35
+ )
36
+
37
+ CERT_SUFFIX = "-cert-v01@openssh.com"
38
+ BASE_KEY_TYPES = (
39
+ "ssh-rsa",
40
+ "ssh-dss",
41
+ "ssh-ed25519",
42
+ "ecdsa-sha2-nistp256",
43
+ "ecdsa-sha2-nistp384",
44
+ "ecdsa-sha2-nistp521",
45
+ "sk-ssh-ed25519@openssh.com",
46
+ "sk-ecdsa-sha2-nistp256@openssh.com",
47
+ )
48
+ KNOWN_KEY_TYPES = set(BASE_KEY_TYPES)
49
+ for _t in BASE_KEY_TYPES:
50
+ KNOWN_KEY_TYPES.add(_t.replace("@openssh.com", "") + CERT_SUFFIX)
51
+
52
+ # Short type names as printed by `ssh-keygen -l`
53
+ TYPE_LABELS = {
54
+ "ssh-rsa": "RSA",
55
+ "ssh-dss": "DSA",
56
+ "ssh-ed25519": "ED25519",
57
+ "ecdsa-sha2-nistp256": "ECDSA",
58
+ "ecdsa-sha2-nistp384": "ECDSA",
59
+ "ecdsa-sha2-nistp521": "ECDSA",
60
+ "sk-ssh-ed25519@openssh.com": "ED25519-SK",
61
+ "sk-ecdsa-sha2-nistp256@openssh.com": "ECDSA-SK",
62
+ }
63
+ ECDSA_BITS = {"nistp256": 256, "nistp384": 384, "nistp521": 521}
64
+ # number of public-key fields that follow the nonce in a certificate blob
65
+ CERT_KEY_FIELDS = {"ssh-rsa": 2, "ssh-dss": 4, "ssh-ed25519": 1,
66
+ "sk-ssh-ed25519": 2, "sk-ecdsa-sha2-nistp256": 3}
67
+
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # SSH wire format and fingerprints
71
+ # ---------------------------------------------------------------------------
72
+
73
+ def read_wire_bytes(buf: bytes, offset: int) -> Tuple[bytes, int]:
74
+ """Read one length-prefixed string / mpint from an SSH wire-format buffer."""
75
+ if offset + 4 > len(buf):
76
+ raise ValueError("key data truncated (field length)")
77
+ length = int.from_bytes(buf[offset:offset + 4], "big")
78
+ offset += 4
79
+ if offset + length > len(buf):
80
+ raise ValueError("key data truncated (field data)")
81
+ return buf[offset:offset + length], offset + length
82
+
83
+
84
+ def _plain_key_blob(key_type: str, raw: bytes, offset: int) -> Tuple[str, bytes]:
85
+ """For an OpenSSH certificate, rebuild the plain public key blob that
86
+ `ssh-keygen -l` fingerprints. Plain keys are returned unchanged."""
87
+ if not key_type.endswith(CERT_SUFFIX):
88
+ return key_type, raw
89
+ base = key_type[:-len(CERT_SUFFIX)]
90
+ plain_type = base + "@openssh.com" if base.startswith("sk-") else base
91
+ count = CERT_KEY_FIELDS.get(base, 2 if base.startswith("ecdsa-sha2-") else 0)
92
+ if not count:
93
+ raise ValueError("unsupported certificate type")
94
+ _nonce, offset = read_wire_bytes(raw, offset)
95
+ fields = [plain_type.encode("ascii")]
96
+ for _ in range(count):
97
+ field, offset = read_wire_bytes(raw, offset)
98
+ fields.append(field)
99
+ return plain_type, b"".join(len(f).to_bytes(4, "big") + f for f in fields)
100
+
101
+
102
+ def _key_bits(key_type: str, blob: bytes, offset: int) -> int:
103
+ """Key size in bits as `ssh-keygen -l` reports it (plain key types only)."""
104
+ if key_type == "ssh-rsa":
105
+ _e, offset = read_wire_bytes(blob, offset)
106
+ n, _ = read_wire_bytes(blob, offset)
107
+ if not n:
108
+ raise ValueError("empty RSA modulus")
109
+ return int.from_bytes(n, "big").bit_length()
110
+ if key_type == "ssh-dss":
111
+ p, _ = read_wire_bytes(blob, offset)
112
+ return int.from_bytes(p, "big").bit_length()
113
+ if key_type in ("ssh-ed25519", "sk-ssh-ed25519@openssh.com"):
114
+ pub, _ = read_wire_bytes(blob, offset)
115
+ if len(pub) != 32:
116
+ raise ValueError("ed25519 public key must be 32 bytes")
117
+ return 256
118
+ if key_type.startswith(("ecdsa-sha2-", "sk-ecdsa-sha2-")):
119
+ curve, offset = read_wire_bytes(blob, offset)
120
+ point, _ = read_wire_bytes(blob, offset)
121
+ if not point:
122
+ raise ValueError("empty ECDSA public point")
123
+ return ECDSA_BITS.get(curve.decode("ascii", "replace"), 0)
124
+ return 0
125
+
126
+
127
+ def sha256_fingerprint(blob: bytes) -> str:
128
+ """OpenSSH SHA256 fingerprint: base64 of the SHA-256 digest, no padding."""
129
+ return "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode("ascii").rstrip("=")
130
+
131
+
132
+ def type_label(key_type: str) -> str:
133
+ """`ssh-keygen -l` style label: RSA, ED25519, ECDSA-SK, RSA-CERT, ..."""
134
+ if key_type.endswith(CERT_SUFFIX):
135
+ base = key_type[:-len(CERT_SUFFIX)]
136
+ base = base + "@openssh.com" if base.startswith("sk-") else base
137
+ return TYPE_LABELS.get(base, "UNKNOWN") + "-CERT"
138
+ return TYPE_LABELS.get(key_type, "UNKNOWN")
139
+
140
+
141
+ def parse_key_blob(b64_key: str, declared_type: Optional[str] = None) -> Dict[str, object]:
142
+ """Decode a base64 OpenSSH public key and return type, bits and fingerprint.
143
+ On a problem the result carries an "error" entry."""
144
+ try:
145
+ raw = base64.b64decode(b64_key.strip(), validate=True)
146
+ except (binascii.Error, ValueError) as exc:
147
+ return {"error": "invalid base64 key data (%s)" % exc}
148
+ try:
149
+ type_bytes, offset = read_wire_bytes(raw, 0)
150
+ key_type = type_bytes.decode("ascii")
151
+ except (ValueError, UnicodeDecodeError) as exc:
152
+ return {"error": "corrupt key data (%s)" % exc}
153
+ if declared_type and declared_type != key_type:
154
+ return {"error": "key type in line (%s) does not match the key data (%s)"
155
+ % (declared_type, key_type)}
156
+ try:
157
+ plain_type, plain_blob = _plain_key_blob(key_type, raw, offset)
158
+ _t, plain_offset = read_wire_bytes(plain_blob, 0)
159
+ bits = _key_bits(plain_type, plain_blob, plain_offset)
160
+ except ValueError as exc:
161
+ return {"error": "corrupt %s key data (%s)" % (key_type, exc)}
162
+ return {
163
+ "type": key_type,
164
+ "plain_type": plain_type,
165
+ "label": type_label(key_type),
166
+ "bits": bits,
167
+ "fingerprint": sha256_fingerprint(plain_blob),
168
+ }
169
+
170
+
171
+ # ---------------------------------------------------------------------------
172
+ # authorized_keys parsing
173
+ # ---------------------------------------------------------------------------
174
+
175
+ def split_fields(line: str) -> List[str]:
176
+ """Split on whitespace, keeping quoted option values (command="a b") together."""
177
+ fields: List[str] = []
178
+ cur: List[str] = []
179
+ in_quotes = escaped = False
180
+ for ch in line:
181
+ if escaped:
182
+ cur.append(ch)
183
+ escaped = False
184
+ elif ch == "\\" and in_quotes:
185
+ cur.append(ch)
186
+ escaped = True
187
+ elif ch == '"':
188
+ in_quotes = not in_quotes
189
+ cur.append(ch)
190
+ elif ch.isspace() and not in_quotes:
191
+ if cur:
192
+ fields.append("".join(cur))
193
+ cur = []
194
+ else:
195
+ cur.append(ch)
196
+ if cur:
197
+ fields.append("".join(cur))
198
+ return fields
199
+
200
+
201
+ def parse_line(line: str) -> Optional[Dict[str, object]]:
202
+ """Parse one authorized_keys line: [options] keytype base64 [comment].
203
+ Returns None for blank lines and # comments."""
204
+ line = line.strip().lstrip("\ufeff").strip()
205
+ if not line or line.startswith("#"):
206
+ return None
207
+ fields = split_fields(line)
208
+ options = ""
209
+ idx = 0
210
+ if fields and fields[0] not in KNOWN_KEY_TYPES:
211
+ options = fields[0]
212
+ idx = 1
213
+ if idx + 1 >= len(fields) or fields[idx] not in KNOWN_KEY_TYPES:
214
+ return {"error": "not a recognised key line (no supported key type + key data)"}
215
+ info = parse_key_blob(fields[idx + 1], declared_type=fields[idx])
216
+ info["options"] = options
217
+ info["comment"] = " ".join(fields[idx + 2:])
218
+ return info
219
+
220
+
221
+ def check_key(info: Dict[str, object], min_rsa_bits: int = DEFAULT_MIN_RSA_BITS) -> List[str]:
222
+ """Return the findings for one parsed line (empty list = OK)."""
223
+ if info.get("error"):
224
+ return ["INVALID_LINE: %s" % info["error"]]
225
+ findings: List[str] = []
226
+ plain_type = info.get("plain_type")
227
+ bits = int(info.get("bits") or 0)
228
+ if plain_type == "ssh-dss":
229
+ findings.append("DSA_KEY: DSA keys are deprecated (disabled by default since OpenSSH 7.0, removed in OpenSSH 10.0)")
230
+ elif plain_type == "ssh-rsa" and 0 < bits < min_rsa_bits:
231
+ findings.append("WEAK_RSA: RSA key is %d bits, below %d" % (bits, min_rsa_bits))
232
+ if not info.get("comment"):
233
+ findings.append("NO_COMMENT: no comment, so the key owner cannot be told from the file")
234
+ return findings
235
+
236
+
237
+ def audit_text(text: str, min_rsa_bits: int = DEFAULT_MIN_RSA_BITS) -> List[Dict[str, object]]:
238
+ """Audit the content of one authorized_keys file. Returns one entry per
239
+ non-blank, non-comment line, with "line" (1-based) and "findings"."""
240
+ results: List[Dict[str, object]] = []
241
+ for lineno, raw in enumerate(text.splitlines(), 1):
242
+ info = parse_line(raw)
243
+ if info is None:
244
+ continue
245
+ info["line"] = lineno
246
+ info["findings"] = check_key(info, min_rsa_bits)
247
+ results.append(info)
248
+ return results
249
+
250
+
251
+ def keygen_style(info: Dict[str, object]) -> str:
252
+ """'<bits> SHA256:<fp> <comment> (<TYPE>)', the `ssh-keygen -lf` line format."""
253
+ return "%s %s %s (%s)" % (info["bits"], info["fingerprint"],
254
+ info.get("comment") or "no comment", info["label"])
255
+
256
+
257
+ # ---------------------------------------------------------------------------
258
+ # report and CLI
259
+ # ---------------------------------------------------------------------------
260
+
261
+ def render_report(source: str, results: List[Dict[str, object]], min_rsa_bits: int) -> str:
262
+ out = ["ssh-keyaudit-lite %s: %s" % (__version__, source), ""]
263
+ if not results:
264
+ out.append(" No keys found.")
265
+ for r in results:
266
+ if r.get("error"):
267
+ out.append(" FLAG line %d: invalid line" % r["line"])
268
+ else:
269
+ status = "FLAG" if r["findings"] else "OK "
270
+ out.append(" %s line %d: %s" % (status, r["line"], keygen_style(r)))
271
+ for f in r["findings"]:
272
+ out.append(" - %s" % f)
273
+ keys = [r for r in results if not r.get("error")]
274
+ invalid = len(results) - len(keys)
275
+ flagged = sum(1 for r in keys if r["findings"])
276
+ counts = []
277
+ for code, label in (("DSA_KEY", "DSA"), ("WEAK_RSA", "RSA < %d bits" % min_rsa_bits),
278
+ ("NO_COMMENT", "no comment")):
279
+ n = sum(1 for r in keys if any(f.startswith(code) for f in r["findings"]))
280
+ if n:
281
+ counts.append("%d %s" % (n, label))
282
+ out.append("")
283
+ out.append("%d key(s): %d OK, %d flagged%s; %d invalid line(s)."
284
+ % (len(keys), len(keys) - flagged, flagged,
285
+ " (" + ", ".join(counts) + ")" if counts else "", invalid))
286
+ out.append("Read-only: the file was not changed.")
287
+ return "\n".join(out)
288
+
289
+
290
+ DEMO_AUTHORIZED_KEYS = "\n".join([
291
+ "# demo authorized_keys (public test keys, private halves discarded)",
292
+ "ssh-ed25519 " + (
293
+ "AAAAC3NzaC1lZDI1NTE5AAAAIF2qygAXG2+jbV8W50Nq9rY7zGDvoLFg2K2z/DAY"
294
+ "ZMh3"
295
+ ) + " alice@laptop",
296
+ 'from="10.0.0.0/8",no-pty ssh-rsa ' + (
297
+ "AAAAB3NzaC1yc2EAAAADAQABAAAAgQCjbTjcefm9hye2rZNztr7v23FSCwNngeMq"
298
+ "ImppI8cEyH5xHVF7GLGca1lZDFbOJU3ZkfLLknR1TPG8W3vi3xtEvLlw3Vwkb9b4"
299
+ "9N81hHTFH5D6bQ8pb7rF4l4p1Br2X5Z6fgiJS7aqM9FTonTGVXaMnMWOfYCnPVx1"
300
+ "/w37tUbv/Q=="
301
+ ) + " bob@old-laptop",
302
+ "ssh-ed25519 " + (
303
+ "AAAAC3NzaC1lZDI1NTE5AAAAIA6yhSu/pEz3TK/5/D3Sxc78vKyb+m4DuFhEdDau"
304
+ "x0cL"
305
+ ),
306
+ "ssh-dss " + (
307
+ "AAAAB3NzaC1kc3MAAACBAKyASLUAE09CXhic4BA00UHmyZOueeR1BsYo9gzzONyb"
308
+ "0JVyVWHON2/rjg7RkX0p6/jTYGyuBbAoaIvqEkFn5Dw7mABOJ/at/N+X4asbBkyn"
309
+ "7cPX/NcPxFDKKIrvtBp3Rf5Rpt/Y4Xc84xo7wWnwdauBQzaNEjWxA4uMmsg7h3Oj"
310
+ "AAAAFQDXfMZ7YOGMSLPO4hhtsBQFVjpMcwAAAIEAo9VT55CfHG4jZLS8d8B+Fnm1"
311
+ "H7I/kp6vZuzw5JosgXC/n91+Fxvo1l2447cAZZKv4a0BGE6XLb1maBPdpPH1l9IV"
312
+ "v5sx8wE51xGLQYUgcxL28i1ct44faN9CKMSmpbkUlmByMJsxBGya0ZgIaybrcFh5"
313
+ "Ptcrpuhhnp6b5jnsMGwAAACBAIIiFRI0Qjazx0I2siq1y0r7beU9hZxxCEqb0F8f"
314
+ "cAElcG6P1vFZ8VNQX8l+RVnrbTAjqtqYomgXXBW8zyst89ytbkG3Y1EDz3fQrnnc"
315
+ "f5JHlY0WdXwfyyYxk67piAL5ZL3XUBK9e8IiARIMfj3+ds1H4tvXeKZkNj10rdQ9"
316
+ "kSTl"
317
+ ) + " legacy-ci",
318
+ "ssh-rsa not-a-real-key broken-paste",
319
+ ])
320
+
321
+
322
+ def main(argv: Optional[List[str]] = None) -> int:
323
+ parser = argparse.ArgumentParser(
324
+ prog="ssh-keyaudit-lite",
325
+ description="Audit one SSH authorized_keys file: SHA256 fingerprints (ssh-keygen -lf format), "
326
+ "key type, bits and comment; flags DSA keys, weak RSA keys and keys without a comment. "
327
+ "Read-only.",
328
+ epilog="Fleet scan, owner mapping, removal plan and JSON report: " + PRO_URL,
329
+ )
330
+ parser.add_argument("file", nargs="?", default=None,
331
+ help="authorized_keys file to audit (default: ~/.ssh/authorized_keys; '-' reads stdin)")
332
+ parser.add_argument("--min-rsa-bits", type=int, default=DEFAULT_MIN_RSA_BITS, metavar="N",
333
+ help="flag RSA keys smaller than N bits (default: %d)" % DEFAULT_MIN_RSA_BITS)
334
+ parser.add_argument("--demo", action="store_true", help="audit a built-in sample file (offline)")
335
+ parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
336
+ args = parser.parse_args(argv)
337
+
338
+ if args.min_rsa_bits < 0:
339
+ parser.error("--min-rsa-bits must be 0 or more")
340
+
341
+ if args.demo:
342
+ source, text = "demo (built-in sample authorized_keys)", DEMO_AUTHORIZED_KEYS
343
+ elif args.file == "-":
344
+ source, text = "<stdin>", sys.stdin.read()
345
+ else:
346
+ path = os.path.expanduser(args.file or DEFAULT_FILE)
347
+ source = path
348
+ try:
349
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
350
+ text = fh.read()
351
+ except OSError as exc:
352
+ sys.stderr.write("ssh-keyaudit-lite: cannot read %s: %s\n" % (path, exc.strerror or exc))
353
+ return 2
354
+
355
+ results = audit_text(text, args.min_rsa_bits)
356
+ print(render_report(source, results, args.min_rsa_bits))
357
+ return 1 if any(r["findings"] for r in results) else 0
358
+
359
+
360
+ if __name__ == "__main__":
361
+ sys.exit(main())
@@ -0,0 +1,265 @@
1
+ """Offline tests for ssh-keyaudit-lite.
2
+
3
+ Fixture keys in fixtures/ are public keys generated with ssh-keygen (private
4
+ halves discarded). fixtures/expected_fingerprints.txt holds the matching
5
+ `ssh-keygen -lf` output. When ssh-keygen is installed, the tests also compare
6
+ against a live `ssh-keygen -lf` run.
7
+ """
8
+ import io
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import unittest
15
+ from contextlib import redirect_stderr, redirect_stdout
16
+
17
+ import ssh_keyaudit_lite as ska
18
+
19
+ HERE = os.path.dirname(os.path.abspath(__file__))
20
+ FIX = os.path.join(HERE, "fixtures")
21
+ SAMPLE = os.path.join(FIX, "authorized_keys_sample")
22
+
23
+
24
+ def read(name):
25
+ with open(os.path.join(FIX, name), encoding="utf-8") as fh:
26
+ return fh.read()
27
+
28
+
29
+ def expected():
30
+ out = {}
31
+ for line in read("expected_fingerprints.txt").splitlines():
32
+ name, rest = line.split(" ", 1)
33
+ out[name] = rest
34
+ return out
35
+
36
+
37
+ def run(*argv, stdin=None):
38
+ out, err = io.StringIO(), io.StringIO()
39
+ old_stdin = sys.stdin
40
+ if stdin is not None:
41
+ sys.stdin = io.StringIO(stdin)
42
+ try:
43
+ with redirect_stdout(out), redirect_stderr(err):
44
+ code = ska.main(list(argv))
45
+ finally:
46
+ sys.stdin = old_stdin
47
+ return code, out.getvalue(), err.getvalue()
48
+
49
+
50
+ def ssh_keygen_lf(path):
51
+ """Live `ssh-keygen -lf` output, or None when ssh-keygen is missing or rejects the key."""
52
+ exe = shutil.which("ssh-keygen")
53
+ if not exe:
54
+ return None
55
+ proc = subprocess.run([exe, "-lf", path], stdout=subprocess.PIPE,
56
+ stderr=subprocess.PIPE, universal_newlines=True)
57
+ if proc.returncode != 0:
58
+ return None
59
+ return proc.stdout.strip()
60
+
61
+
62
+ class FingerprintTests(unittest.TestCase):
63
+ def test_each_fixture_matches_recorded_ssh_keygen_output(self):
64
+ exp = expected()
65
+ self.assertGreaterEqual(len(exp), 10)
66
+ for name, want in exp.items():
67
+ with self.subTest(key=name):
68
+ results = ska.audit_text(read(name))
69
+ self.assertEqual(len(results), 1)
70
+ self.assertEqual(ska.keygen_style(results[0]), want)
71
+
72
+ def test_each_fixture_matches_live_ssh_keygen(self):
73
+ if not shutil.which("ssh-keygen"):
74
+ self.skipTest("ssh-keygen not installed")
75
+ checked = 0
76
+ for name in expected():
77
+ live = ssh_keygen_lf(os.path.join(FIX, name))
78
+ if live is None: # e.g. DSA on OpenSSH 10+, which dropped DSA support
79
+ continue
80
+ with self.subTest(key=name):
81
+ self.assertEqual(ska.keygen_style(ska.audit_text(read(name))[0]), live)
82
+ checked += 1
83
+ self.assertGreaterEqual(checked, 8)
84
+
85
+ def test_sample_file_matches_live_ssh_keygen_line_by_line(self):
86
+ live = ssh_keygen_lf(SAMPLE)
87
+ if live is None:
88
+ self.skipTest("ssh-keygen not installed")
89
+ ours = [ska.keygen_style(r) for r in ska.audit_text(read("authorized_keys_sample"))]
90
+ live_lines = live.splitlines()
91
+ # older ssh-keygen versions also print the DSA key; newer ones skip it
92
+ if len(live_lines) == len(ours) - 1:
93
+ ours = [o for o in ours if not o.endswith("(DSA)")]
94
+ self.assertEqual(ours, live_lines)
95
+
96
+ def test_types_and_bits(self):
97
+ cases = {
98
+ "ed25519.pub": ("ED25519", 256), "rsa4096.pub": ("RSA", 4096),
99
+ "rsa1024.pub": ("RSA", 1024), "rsa2048.pub": ("RSA", 2048),
100
+ "ecdsa256.pub": ("ECDSA", 256), "ecdsa384.pub": ("ECDSA", 384),
101
+ "ecdsa521.pub": ("ECDSA", 521), "dsa1024.pub": ("DSA", 1024),
102
+ "ed25519-cert.pub": ("ED25519-CERT", 256),
103
+ }
104
+ for name, (label, bits) in cases.items():
105
+ with self.subTest(key=name):
106
+ r = ska.audit_text(read(name))[0]
107
+ self.assertEqual((r["label"], r["bits"]), (label, bits))
108
+
109
+ def test_certificate_fingerprint_is_the_certified_key(self):
110
+ plain = ska.audit_text(read("ed25519.pub"))[0]["fingerprint"]
111
+ cert = ska.audit_text(read("ed25519-cert.pub"))[0]["fingerprint"]
112
+ self.assertEqual(plain, cert)
113
+
114
+
115
+ class ParsingTests(unittest.TestCase):
116
+ def setUp(self):
117
+ self.results = ska.audit_text(read("authorized_keys_sample"))
118
+
119
+ def test_blank_and_comment_lines_are_skipped_and_line_numbers_kept(self):
120
+ self.assertEqual([r["line"] for r in self.results], [3, 4, 5, 7, 8, 9, 10])
121
+
122
+ def test_options_prefixed_lines(self):
123
+ by_line = {r["line"]: r for r in self.results}
124
+ self.assertEqual(by_line[4]["options"], 'from="10.0.0.0/8",no-agent-forwarding')
125
+ self.assertEqual(by_line[4]["comment"], "backup-operator")
126
+ self.assertTrue(by_line[5]["options"].startswith('command="/usr/local/bin/backup --mode \\"full run\\""'))
127
+ self.assertEqual(by_line[5]["comment"], "ci-deploy key")
128
+ self.assertEqual(by_line[5]["bits"], 2048)
129
+
130
+ def test_comment_less_key(self):
131
+ r = ska.audit_text(read("nocomment.pub"))[0]
132
+ self.assertEqual(r["comment"], "")
133
+ self.assertIn("no comment (ED25519)", ska.keygen_style(r))
134
+
135
+ def test_bom_crlf_and_tabs(self):
136
+ key = read("ed25519.pub").split()
137
+ text = "\ufeff" + key[0] + "\t" + key[1] + "\t alice@laptop\r\n\r\n"
138
+ r = ska.audit_text(text)
139
+ self.assertEqual(len(r), 1)
140
+ self.assertEqual(r[0]["comment"], "alice@laptop")
141
+ self.assertEqual(r[0]["findings"], [])
142
+
143
+ def test_invalid_lines(self):
144
+ key = read("ed25519.pub").split()[1]
145
+ rsa = read("rsa2048.pub").split()[1]
146
+ text = "\n".join([
147
+ "ssh-ed25519 !!!notbase64!!! bad",
148
+ "garbage line here",
149
+ "ssh-rsa " + key + " type-mismatch",
150
+ "ssh-ed25519 " + key[:20] + " truncated",
151
+ "ssh-rsa " + rsa[:60] + " truncated-rsa",
152
+ "ssh-ed25519",
153
+ ])
154
+ results = ska.audit_text(text)
155
+ self.assertEqual(len(results), 6)
156
+ for r in results:
157
+ self.assertIn("error", r)
158
+ self.assertTrue(r["findings"][0].startswith("INVALID_LINE"))
159
+ self.assertIn("does not match", results[2]["error"])
160
+
161
+ def test_split_fields_keeps_quoted_spaces(self):
162
+ self.assertEqual(ska.split_fields('command="a b",no-pty ssh-ed25519 AAAA c d'),
163
+ ['command="a b",no-pty', "ssh-ed25519", "AAAA", "c", "d"])
164
+
165
+
166
+ class FindingTests(unittest.TestCase):
167
+ def findings(self, name, **kw):
168
+ return ska.audit_text(read(name), **kw)[0]["findings"]
169
+
170
+ def test_dsa_flagged(self):
171
+ self.assertTrue(self.findings("dsa1024.pub")[0].startswith("DSA_KEY"))
172
+
173
+ def test_rsa_threshold_default_3072(self):
174
+ self.assertTrue(self.findings("rsa1024.pub")[0].startswith("WEAK_RSA"))
175
+ self.assertTrue(self.findings("rsa2048.pub")[0].startswith("WEAK_RSA"))
176
+ self.assertEqual(self.findings("rsa4096.pub"), [])
177
+
178
+ def test_rsa_threshold_configurable(self):
179
+ self.assertEqual(self.findings("rsa2048.pub", min_rsa_bits=2048), [])
180
+ self.assertTrue(self.findings("rsa1024.pub", min_rsa_bits=2048)[0].startswith("WEAK_RSA"))
181
+
182
+ def test_no_comment_flagged(self):
183
+ self.assertEqual([f.split(":")[0] for f in self.findings("nocomment.pub")], ["NO_COMMENT"])
184
+
185
+ def test_modern_keys_ok(self):
186
+ for name in ("ed25519.pub", "ecdsa256.pub", "ecdsa384.pub", "ecdsa521.pub", "ed25519-cert.pub"):
187
+ with self.subTest(key=name):
188
+ self.assertEqual(self.findings(name), [])
189
+
190
+
191
+ class CliTests(unittest.TestCase):
192
+ def test_sample_file_exit_1_and_summary(self):
193
+ code, out, _ = run(SAMPLE)
194
+ self.assertEqual(code, 1)
195
+ self.assertIn("7 key(s): 3 OK, 4 flagged (1 DSA, 2 RSA < 3072 bits, 1 no comment); 0 invalid line(s).", out)
196
+ self.assertIn("OK line 3: 256 SHA256:ehngEyw0ibJhOPXM8qj4kHqp7PMOVB8whu2zTPeF2Dc alice@laptop (ED25519)", out)
197
+
198
+ def test_clean_file_exit_0(self):
199
+ code, out, _ = run(os.path.join(FIX, "ed25519.pub"))
200
+ self.assertEqual(code, 0)
201
+ self.assertIn("1 key(s): 1 OK, 0 flagged; 0 invalid line(s).", out)
202
+
203
+ def test_min_rsa_bits_option(self):
204
+ code, out, _ = run("--min-rsa-bits", "1024", os.path.join(FIX, "rsa1024.pub"))
205
+ self.assertEqual(code, 0)
206
+
207
+ def test_missing_file_exit_2(self):
208
+ code, _, err = run(os.path.join(FIX, "does-not-exist"))
209
+ self.assertEqual(code, 2)
210
+ self.assertIn("cannot read", err)
211
+
212
+ def test_empty_file_exit_0(self):
213
+ with tempfile.NamedTemporaryFile("w", suffix="_ak", delete=False) as fh:
214
+ fh.write("# only a comment\n\n")
215
+ try:
216
+ code, out, _ = run(fh.name)
217
+ finally:
218
+ os.unlink(fh.name)
219
+ self.assertEqual(code, 0)
220
+ self.assertIn("No keys found.", out)
221
+
222
+ def test_default_path_is_home_authorized_keys(self):
223
+ tmp = tempfile.mkdtemp()
224
+ try:
225
+ os.makedirs(os.path.join(tmp, ".ssh"))
226
+ shutil.copy(os.path.join(FIX, "ecdsa256.pub"), os.path.join(tmp, ".ssh", "authorized_keys"))
227
+ old = os.environ.get("HOME")
228
+ os.environ["HOME"] = tmp
229
+ try:
230
+ code, out, _ = run()
231
+ finally:
232
+ if old is None:
233
+ del os.environ["HOME"]
234
+ else:
235
+ os.environ["HOME"] = old
236
+ finally:
237
+ shutil.rmtree(tmp)
238
+ self.assertEqual(code, 0)
239
+ self.assertIn(os.path.join(tmp, ".ssh", "authorized_keys"), out)
240
+ self.assertIn("carol@desk (ECDSA)", out)
241
+
242
+ def test_stdin(self):
243
+ code, out, _ = run("-", stdin=read("rsa1024.pub"))
244
+ self.assertEqual(code, 1)
245
+ self.assertIn("<stdin>", out)
246
+ self.assertIn("WEAK_RSA", out)
247
+
248
+ def test_demo(self):
249
+ code, out, _ = run("--demo")
250
+ self.assertEqual(code, 1)
251
+ self.assertIn("4 key(s): 1 OK, 3 flagged (1 DSA, 1 RSA < 3072 bits, 1 no comment); 1 invalid line(s).", out)
252
+
253
+ def test_file_is_not_modified(self):
254
+ before = os.stat(SAMPLE).st_mtime_ns, read("authorized_keys_sample")
255
+ run(SAMPLE)
256
+ self.assertEqual(before, (os.stat(SAMPLE).st_mtime_ns, read("authorized_keys_sample")))
257
+
258
+ def test_version(self):
259
+ with self.assertRaises(SystemExit) as cm:
260
+ run("--version")
261
+ self.assertEqual(cm.exception.code, 0)
262
+
263
+
264
+ if __name__ == "__main__":
265
+ unittest.main(verbosity=2)