ssh-keyaudit-lite 0.1.0__py3-none-any.whl
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.
- ssh_keyaudit_lite-0.1.0.dist-info/METADATA +163 -0
- ssh_keyaudit_lite-0.1.0.dist-info/RECORD +7 -0
- ssh_keyaudit_lite-0.1.0.dist-info/WHEEL +5 -0
- ssh_keyaudit_lite-0.1.0.dist-info/entry_points.txt +2 -0
- ssh_keyaudit_lite-0.1.0.dist-info/licenses/LICENSE +21 -0
- ssh_keyaudit_lite-0.1.0.dist-info/top_level.txt +1 -0
- ssh_keyaudit_lite.py +361 -0
|
@@ -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
|
+

|
|
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,7 @@
|
|
|
1
|
+
ssh_keyaudit_lite.py,sha256=7WBqHoTx0iCu9EBpibzLMTDLWzQxynqdFhLc--iMdxU,15067
|
|
2
|
+
ssh_keyaudit_lite-0.1.0.dist-info/licenses/LICENSE,sha256=hHuiZGVU1W0vbSggaTAy28kRUnwp6e85CqEFKsatpcE,1087
|
|
3
|
+
ssh_keyaudit_lite-0.1.0.dist-info/METADATA,sha256=tFglZ4D3M30a21tO699x5dj6XJPm0k5tBcC-O4ynYjc,9627
|
|
4
|
+
ssh_keyaudit_lite-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
ssh_keyaudit_lite-0.1.0.dist-info/entry_points.txt,sha256=R8Rdp_q8zMZzE7JWfPmlYaSqm2jBpoZzUUorKKwH4_Q,61
|
|
6
|
+
ssh_keyaudit_lite-0.1.0.dist-info/top_level.txt,sha256=WVZQlCa8eym3X54mjbOb-FaP4oy4yeA7feGSOZ8GjMY,18
|
|
7
|
+
ssh_keyaudit_lite-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
ssh_keyaudit_lite
|
ssh_keyaudit_lite.py
ADDED
|
@@ -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())
|