certinspect 2.4.0__tar.gz → 2.4.1__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.
Files changed (30) hide show
  1. {certinspect-2.4.0/src/certinspect.egg-info → certinspect-2.4.1}/PKG-INFO +68 -31
  2. {certinspect-2.4.0 → certinspect-2.4.1}/README.md +67 -30
  3. {certinspect-2.4.0 → certinspect-2.4.1}/pyproject.toml +1 -1
  4. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/__init__.py +1 -1
  5. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/args.py +8 -3
  6. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/cli.py +7 -1
  7. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/formatter.py +18 -11
  8. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/parser.py +4 -4
  9. {certinspect-2.4.0 → certinspect-2.4.1/src/certinspect.egg-info}/PKG-INFO +68 -31
  10. {certinspect-2.4.0 → certinspect-2.4.1}/tests/test_cli.py +115 -0
  11. {certinspect-2.4.0 → certinspect-2.4.1}/tests/test_formatter.py +77 -0
  12. {certinspect-2.4.0 → certinspect-2.4.1}/LICENSE +0 -0
  13. {certinspect-2.4.0 → certinspect-2.4.1}/setup.cfg +0 -0
  14. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/completion.py +0 -0
  15. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/config.py +0 -0
  16. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/discover.py +0 -0
  17. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/exit_codes.py +0 -0
  18. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/fetch.py +0 -0
  19. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/httpfetch.py +0 -0
  20. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/models.py +0 -0
  21. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/render.py +0 -0
  22. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect/revocation.py +0 -0
  23. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect.egg-info/SOURCES.txt +0 -0
  24. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect.egg-info/dependency_links.txt +0 -0
  25. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect.egg-info/entry_points.txt +0 -0
  26. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect.egg-info/requires.txt +0 -0
  27. {certinspect-2.4.0 → certinspect-2.4.1}/src/certinspect.egg-info/top_level.txt +0 -0
  28. {certinspect-2.4.0 → certinspect-2.4.1}/tests/test_discover.py +0 -0
  29. {certinspect-2.4.0 → certinspect-2.4.1}/tests/test_fetch.py +0 -0
  30. {certinspect-2.4.0 → certinspect-2.4.1}/tests/test_parser.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: certinspect
3
- Version: 2.4.0
3
+ Version: 2.4.1
4
4
  Summary: Command-line TLS certificate inspector
5
5
  Author-email: Michele Angrisano <michele.angrisano@gmail.com>
6
6
  License-Expression: MIT
@@ -488,11 +488,11 @@ certinspect internal.example.lan --verify --cafile ./internal-ca.pem
488
488
 
489
489
  ### Catch a revoked certificate
490
490
 
491
- `--verify` queries OCSP and falls back to the CRL; a revoked leaf fails with
492
- exit `6`:
491
+ Verification is on by default: it queries OCSP and falls back to the CRL, and a
492
+ revoked leaf fails with exit `6`:
493
493
 
494
494
  ```bash
495
- certinspect revoked.example.com --verify
495
+ certinspect revoked.example.com
496
496
  ```
497
497
 
498
498
  ### Spot an expired intermediate before it breaks the chain
@@ -659,7 +659,7 @@ certinspect example.com --export ./example.com.pem
659
659
  | `--summary` | Print a one-line tally (valid/expiring/expired/errors) to stderr; counts every target before filtering. |
660
660
  | `--field NAME` | Print only the given field(s), one tab-separated line per target (repeatable; `target` for the host). For scripting without a JSON tool. |
661
661
  | `--exit-zero` | Always exit 0, even on problems or fetch errors. Report-only mode for dashboards/CI that read the output, not the exit code. |
662
- | `--export PATH` | Save the inspected certificate as a PEM file at PATH. |
662
+ | `--export PATH` | Save the inspected certificate as a PEM file at PATH. Single target only. |
663
663
  | `--starttls {smtp,imap,pop3,ftp}` | Upgrade a plaintext connection to TLS before inspecting (standard port unless `--port` is given). |
664
664
  | `--exporter {nagios,prometheus}` | Emit machine-readable monitoring output (ignores `--quiet`). |
665
665
  | `--concurrency N` | Inspect up to N hosts in parallel in batch mode (default: 1; order is preserved). Also governs `--discover`'s per-domain concurrency. |
@@ -707,6 +707,10 @@ SAN:
707
707
  ```
708
708
 
709
709
  Passing several hosts prints one `=== host ===` block per target (batch mode).
710
+ A target on a non-default port is labelled `host:port` (e.g.
711
+ `=== example.com:8443 ===`) there and in every other output, the
712
+ `--state-file` and the Prometheus `target` label, so several services on the
713
+ same host stay apart.
710
714
 
711
715
  ### `--file PATH` — inspect a local certificate
712
716
 
@@ -816,6 +820,10 @@ The `status` field mirrors the human report's `Status` line (`VALID`,
816
820
  honors `--days` / `--critical-days`, so a JSON consumer gets the verdict
817
821
  without re-deriving it from the dates.
818
822
 
823
+ `key.type` is the key family (`RSA`, `EC`, `DSA`, `Ed25519` or `Ed448`).
824
+ EdDSA keys have a fixed size, so for them `key.size` is `null` (`n/a` in the
825
+ text report).
826
+
819
827
  Need the pre-2.0 flat array (no envelope, dates via `str()`, integer serial)?
820
828
  Pass `--schema 1`:
821
829
 
@@ -892,6 +900,19 @@ $ certinspect --file ./bundle.pem --verify
892
900
  Chain trusted: True
893
901
  ```
894
902
 
903
+ For a host, revocation is checked over OCSP first, falling back to the CRL. An
904
+ answer only counts when it is authentic: the OCSP response must be about this
905
+ certificate and signed by its issuer (or by a responder the issuer delegated
906
+ with the OCSP Signing EKU); the CRL must be signed by the issuer, name it and
907
+ cover this kind of certificate. The issuer itself, taken from the verified
908
+ chain or downloaded from the certificate's AIA URL, must have signed the leaf.
909
+ Anything else is reported as `UNAVAILABLE` — a browser-like soft-fail that
910
+ leaves the exit code alone; add
911
+ [`--require-revocation-check`](#--require-revocation-check) to make it fail.
912
+ The OCSP, CRL and issuer URLs come from the certificate, so certinspect
913
+ refuses to fetch loopback, link-local (cloud metadata) or other internal
914
+ addresses — also after an HTTP redirect — and caps each response at 16 MB.
915
+
895
916
  ### `--chain`
896
917
 
897
918
  ```console
@@ -1172,13 +1193,13 @@ you had passed the flags yourself.
1172
1193
 
1173
1194
  Each stricter tier is a superset of the one below it:
1174
1195
 
1175
- | Check (flag) | `lenient` | `standard` | `strict` |
1176
- | --------------------------------------------- | :-------: | :--------: | :---------: |
1177
- | Minimum TLS version (`--min-tls-version`) | TLSv1.2 | TLSv1.2 | **TLSv1.3** |
1178
- | Fail on weak crypto (`--fail-weak`) | yes | yes | yes |
1179
- | Minimum key size (`--min-key-size`) | — | 2048 bit | 2048 bit |
1180
- | Require CT SCTs (`--require-sct`) | — | — | yes |
1181
- | CA/Browser Forum validity cap (`--cab-forum`) | — | — | yes |
1196
+ | Check (flag) | `lenient` | `standard` | `strict` |
1197
+ | --------------------------------------------- | :-------: | :----------------: | :----------------: |
1198
+ | Minimum TLS version (`--min-tls-version`) | TLSv1.2 | TLSv1.2 | **TLSv1.3** |
1199
+ | Fail on weak crypto (`--fail-weak`) | yes | yes | yes |
1200
+ | Minimum key size (`--min-key-size`) | — | 2048 bit (RSA/DSA) | 2048 bit (RSA/DSA) |
1201
+ | Require CT SCTs (`--require-sct`) | — | — | yes |
1202
+ | CA/Browser Forum validity cap (`--cab-forum`) | — | — | yes |
1182
1203
 
1183
1204
  Precedence and edge cases a sysadmin should know:
1184
1205
 
@@ -1287,7 +1308,9 @@ summary: 1 valid · 0 expiring · 0 expired · 1 error (2 targets)
1287
1308
  Print only the fields you ask for, one tab-separated line per target, so you
1288
1309
  can pull values straight into a script without a JSON tool. Repeat `--field`
1289
1310
  for several columns; the pseudo-field `target` is the inspected host and list
1290
- fields (like `san`) are comma-joined.
1311
+ fields (like `san`) are comma-joined. Any key of the `--json --schema 1`
1312
+ output is a valid name (e.g. `issuer`, `key_type`, `key_size`,
1313
+ `revocation_status`).
1291
1314
 
1292
1315
  ```console
1293
1316
  $ certinspect example.com github.com --field target --field days_to_expire --field status
@@ -1316,7 +1339,9 @@ $ echo $?
1316
1339
 
1317
1340
  ### `--export PATH`
1318
1341
 
1319
- Save the fetched certificate as PEM and still print the report.
1342
+ Save the fetched certificate as PEM and still print the report. It takes a
1343
+ single target; with several (hosts, `--file`s or a `--discover` result) the
1344
+ command stops with a usage error rather than overwriting the same file.
1320
1345
 
1321
1346
  ```console
1322
1347
  $ certinspect example.com --export ./fetched.pem
@@ -1393,7 +1418,7 @@ Machine-readable monitoring output (full examples in
1393
1418
 
1394
1419
  ```console
1395
1420
  $ certinspect example.com --exporter nagios
1396
- OK: example.com certificate VALID (64 days to expiry) | days=64;30;0
1421
+ OK: example.com certificate VALID (64 days to expiry) | days=64;30:;0:
1397
1422
  ```
1398
1423
 
1399
1424
  ### `--version`
@@ -1450,7 +1475,10 @@ Status: EXPIRING
1450
1475
  ```
1451
1476
 
1452
1477
  The state file is always brought up to date, whether or not `--only-changed`
1453
- is given, so the next run has a fresh baseline to compare against.
1478
+ is given, so the next run has a fresh baseline to compare against. A target
1479
+ that cannot be reached keeps its last known status, so a transient outage is
1480
+ reported as an error on that run (exit code 1) but not as a change once the
1481
+ host is back; a target removed from the list is dropped from the file.
1454
1482
 
1455
1483
  ### `--print-completion {bash,zsh}`
1456
1484
 
@@ -1485,10 +1513,15 @@ host is CRITICAL:
1485
1513
 
1486
1514
  ```console
1487
1515
  $ certinspect example.com expired.example.com --exporter nagios
1488
- OK: example.com certificate VALID (217 days to expiry) | days=217;30;0
1489
- CRITICAL: expired.example.com certificate EXPIRED (-3 days to expiry) | days=-3;30;0
1516
+ OK: example.com certificate VALID (217 days to expiry) | days=217;30:;0:
1517
+ CRITICAL: expired.example.com certificate EXPIRED (-3 days to expiry) | days=-3;30:;0:
1490
1518
  ```
1491
1519
 
1520
+ The perfdata thresholds use the `N:` range form, "alert below N": `30:` is the
1521
+ `--days` warning, `0:` the critical one (expired), or `--critical-days` when set
1522
+ (`days=12;30:;7:`), so graphers colour each series exactly as the plugin rates
1523
+ it.
1524
+
1492
1525
  `prometheus` emits textfile-collector metrics (`certinspect_up`,
1493
1526
  `certinspect_cert_expiry_days`, `certinspect_cert_valid`), keeping the normal
1494
1527
  worst-status exit code:
@@ -1508,7 +1541,7 @@ certinspect_cert_valid{target="example.com"} 1
1508
1541
 
1509
1542
  Three further gauges appear only for the targets whose check actually ran, so a
1510
1543
  scrape never carries a misleading `0` for a check that was not requested:
1511
- `certinspect_hostname_match` (host targets), and — with `--verify` —
1544
+ `certinspect_hostname_match` (host targets), and — unless `--no-verify` —
1512
1545
  `certinspect_chain_trusted` and `certinspect_cert_revoked` (the latter only when
1513
1546
  OCSP/CRL returns a definitive answer). This lets you alert directly on chain,
1514
1547
  hostname and revocation problems without parsing text:
@@ -1553,18 +1586,22 @@ severe first:
1553
1586
  hostname mismatch → `1` runtime error (e.g. unreachable host) → `8` SAN
1554
1587
  missing → `9` policy → `3` expiring → `0` valid.
1555
1588
 
1556
- | Code | Meaning |
1557
- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1558
- | 0 | Valid certificate |
1559
- | 1 | Runtime error (network, file, parse) |
1560
- | 2 | Command-line usage error |
1561
- | 3 | Expiring within the `--days` threshold |
1562
- | 4 | Expired, not yet valid, or with invalid dates |
1563
- | 5 | Hostname does not match the certificate |
1564
- | 6 | Chain not trusted or revoked (`--verify`) |
1565
- | 7 | Fingerprint does not match `--pin` |
1566
- | 8 | Expected SAN missing (`--expect-san`) |
1567
- | 9 | Policy violation (`--not-after-max`/`--cab-forum`, `--min-key-size`, `--fail-weak`, `--require-sct`, `--require-must-staple`, `--require-revocation-check`, `--min-tls-version`) |
1589
+ Two options replace these codes: `--exporter nagios` exits with the plugin
1590
+ convention (`0` OK, `1` WARNING, `2` CRITICAL) and `--exit-zero` always exits
1591
+ `0`.
1592
+
1593
+ | Code | Meaning |
1594
+ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1595
+ | 0 | Valid certificate |
1596
+ | 1 | Runtime error (network, file, parse) |
1597
+ | 2 | Command-line usage error |
1598
+ | 3 | Expiring within the `--days` threshold |
1599
+ | 4 | Expired, not yet valid, with invalid dates, or expiring within `--critical-days` |
1600
+ | 5 | Hostname does not match the certificate |
1601
+ | 6 | Chain not trusted or certificate revoked (verification is on by default; `--no-verify` skips it) |
1602
+ | 7 | Fingerprint does not match `--pin` |
1603
+ | 8 | Expected SAN missing (`--expect-san`) |
1604
+ | 9 | Policy violation (`--profile`, `--not-after-max`/`--cab-forum`, `--min-key-size`, `--fail-weak`, `--require-sct`, `--require-must-staple`, `--require-revocation-check`, `--min-tls-version`), or an unexpected issuer with `--discover-only --expect-issuer` |
1568
1605
 
1569
1606
  Example in a script:
1570
1607
 
@@ -462,11 +462,11 @@ certinspect internal.example.lan --verify --cafile ./internal-ca.pem
462
462
 
463
463
  ### Catch a revoked certificate
464
464
 
465
- `--verify` queries OCSP and falls back to the CRL; a revoked leaf fails with
466
- exit `6`:
465
+ Verification is on by default: it queries OCSP and falls back to the CRL, and a
466
+ revoked leaf fails with exit `6`:
467
467
 
468
468
  ```bash
469
- certinspect revoked.example.com --verify
469
+ certinspect revoked.example.com
470
470
  ```
471
471
 
472
472
  ### Spot an expired intermediate before it breaks the chain
@@ -633,7 +633,7 @@ certinspect example.com --export ./example.com.pem
633
633
  | `--summary` | Print a one-line tally (valid/expiring/expired/errors) to stderr; counts every target before filtering. |
634
634
  | `--field NAME` | Print only the given field(s), one tab-separated line per target (repeatable; `target` for the host). For scripting without a JSON tool. |
635
635
  | `--exit-zero` | Always exit 0, even on problems or fetch errors. Report-only mode for dashboards/CI that read the output, not the exit code. |
636
- | `--export PATH` | Save the inspected certificate as a PEM file at PATH. |
636
+ | `--export PATH` | Save the inspected certificate as a PEM file at PATH. Single target only. |
637
637
  | `--starttls {smtp,imap,pop3,ftp}` | Upgrade a plaintext connection to TLS before inspecting (standard port unless `--port` is given). |
638
638
  | `--exporter {nagios,prometheus}` | Emit machine-readable monitoring output (ignores `--quiet`). |
639
639
  | `--concurrency N` | Inspect up to N hosts in parallel in batch mode (default: 1; order is preserved). Also governs `--discover`'s per-domain concurrency. |
@@ -681,6 +681,10 @@ SAN:
681
681
  ```
682
682
 
683
683
  Passing several hosts prints one `=== host ===` block per target (batch mode).
684
+ A target on a non-default port is labelled `host:port` (e.g.
685
+ `=== example.com:8443 ===`) there and in every other output, the
686
+ `--state-file` and the Prometheus `target` label, so several services on the
687
+ same host stay apart.
684
688
 
685
689
  ### `--file PATH` — inspect a local certificate
686
690
 
@@ -790,6 +794,10 @@ The `status` field mirrors the human report's `Status` line (`VALID`,
790
794
  honors `--days` / `--critical-days`, so a JSON consumer gets the verdict
791
795
  without re-deriving it from the dates.
792
796
 
797
+ `key.type` is the key family (`RSA`, `EC`, `DSA`, `Ed25519` or `Ed448`).
798
+ EdDSA keys have a fixed size, so for them `key.size` is `null` (`n/a` in the
799
+ text report).
800
+
793
801
  Need the pre-2.0 flat array (no envelope, dates via `str()`, integer serial)?
794
802
  Pass `--schema 1`:
795
803
 
@@ -866,6 +874,19 @@ $ certinspect --file ./bundle.pem --verify
866
874
  Chain trusted: True
867
875
  ```
868
876
 
877
+ For a host, revocation is checked over OCSP first, falling back to the CRL. An
878
+ answer only counts when it is authentic: the OCSP response must be about this
879
+ certificate and signed by its issuer (or by a responder the issuer delegated
880
+ with the OCSP Signing EKU); the CRL must be signed by the issuer, name it and
881
+ cover this kind of certificate. The issuer itself, taken from the verified
882
+ chain or downloaded from the certificate's AIA URL, must have signed the leaf.
883
+ Anything else is reported as `UNAVAILABLE` — a browser-like soft-fail that
884
+ leaves the exit code alone; add
885
+ [`--require-revocation-check`](#--require-revocation-check) to make it fail.
886
+ The OCSP, CRL and issuer URLs come from the certificate, so certinspect
887
+ refuses to fetch loopback, link-local (cloud metadata) or other internal
888
+ addresses — also after an HTTP redirect — and caps each response at 16 MB.
889
+
869
890
  ### `--chain`
870
891
 
871
892
  ```console
@@ -1146,13 +1167,13 @@ you had passed the flags yourself.
1146
1167
 
1147
1168
  Each stricter tier is a superset of the one below it:
1148
1169
 
1149
- | Check (flag) | `lenient` | `standard` | `strict` |
1150
- | --------------------------------------------- | :-------: | :--------: | :---------: |
1151
- | Minimum TLS version (`--min-tls-version`) | TLSv1.2 | TLSv1.2 | **TLSv1.3** |
1152
- | Fail on weak crypto (`--fail-weak`) | yes | yes | yes |
1153
- | Minimum key size (`--min-key-size`) | — | 2048 bit | 2048 bit |
1154
- | Require CT SCTs (`--require-sct`) | — | — | yes |
1155
- | CA/Browser Forum validity cap (`--cab-forum`) | — | — | yes |
1170
+ | Check (flag) | `lenient` | `standard` | `strict` |
1171
+ | --------------------------------------------- | :-------: | :----------------: | :----------------: |
1172
+ | Minimum TLS version (`--min-tls-version`) | TLSv1.2 | TLSv1.2 | **TLSv1.3** |
1173
+ | Fail on weak crypto (`--fail-weak`) | yes | yes | yes |
1174
+ | Minimum key size (`--min-key-size`) | — | 2048 bit (RSA/DSA) | 2048 bit (RSA/DSA) |
1175
+ | Require CT SCTs (`--require-sct`) | — | — | yes |
1176
+ | CA/Browser Forum validity cap (`--cab-forum`) | — | — | yes |
1156
1177
 
1157
1178
  Precedence and edge cases a sysadmin should know:
1158
1179
 
@@ -1261,7 +1282,9 @@ summary: 1 valid · 0 expiring · 0 expired · 1 error (2 targets)
1261
1282
  Print only the fields you ask for, one tab-separated line per target, so you
1262
1283
  can pull values straight into a script without a JSON tool. Repeat `--field`
1263
1284
  for several columns; the pseudo-field `target` is the inspected host and list
1264
- fields (like `san`) are comma-joined.
1285
+ fields (like `san`) are comma-joined. Any key of the `--json --schema 1`
1286
+ output is a valid name (e.g. `issuer`, `key_type`, `key_size`,
1287
+ `revocation_status`).
1265
1288
 
1266
1289
  ```console
1267
1290
  $ certinspect example.com github.com --field target --field days_to_expire --field status
@@ -1290,7 +1313,9 @@ $ echo $?
1290
1313
 
1291
1314
  ### `--export PATH`
1292
1315
 
1293
- Save the fetched certificate as PEM and still print the report.
1316
+ Save the fetched certificate as PEM and still print the report. It takes a
1317
+ single target; with several (hosts, `--file`s or a `--discover` result) the
1318
+ command stops with a usage error rather than overwriting the same file.
1294
1319
 
1295
1320
  ```console
1296
1321
  $ certinspect example.com --export ./fetched.pem
@@ -1367,7 +1392,7 @@ Machine-readable monitoring output (full examples in
1367
1392
 
1368
1393
  ```console
1369
1394
  $ certinspect example.com --exporter nagios
1370
- OK: example.com certificate VALID (64 days to expiry) | days=64;30;0
1395
+ OK: example.com certificate VALID (64 days to expiry) | days=64;30:;0:
1371
1396
  ```
1372
1397
 
1373
1398
  ### `--version`
@@ -1424,7 +1449,10 @@ Status: EXPIRING
1424
1449
  ```
1425
1450
 
1426
1451
  The state file is always brought up to date, whether or not `--only-changed`
1427
- is given, so the next run has a fresh baseline to compare against.
1452
+ is given, so the next run has a fresh baseline to compare against. A target
1453
+ that cannot be reached keeps its last known status, so a transient outage is
1454
+ reported as an error on that run (exit code 1) but not as a change once the
1455
+ host is back; a target removed from the list is dropped from the file.
1428
1456
 
1429
1457
  ### `--print-completion {bash,zsh}`
1430
1458
 
@@ -1459,10 +1487,15 @@ host is CRITICAL:
1459
1487
 
1460
1488
  ```console
1461
1489
  $ certinspect example.com expired.example.com --exporter nagios
1462
- OK: example.com certificate VALID (217 days to expiry) | days=217;30;0
1463
- CRITICAL: expired.example.com certificate EXPIRED (-3 days to expiry) | days=-3;30;0
1490
+ OK: example.com certificate VALID (217 days to expiry) | days=217;30:;0:
1491
+ CRITICAL: expired.example.com certificate EXPIRED (-3 days to expiry) | days=-3;30:;0:
1464
1492
  ```
1465
1493
 
1494
+ The perfdata thresholds use the `N:` range form, "alert below N": `30:` is the
1495
+ `--days` warning, `0:` the critical one (expired), or `--critical-days` when set
1496
+ (`days=12;30:;7:`), so graphers colour each series exactly as the plugin rates
1497
+ it.
1498
+
1466
1499
  `prometheus` emits textfile-collector metrics (`certinspect_up`,
1467
1500
  `certinspect_cert_expiry_days`, `certinspect_cert_valid`), keeping the normal
1468
1501
  worst-status exit code:
@@ -1482,7 +1515,7 @@ certinspect_cert_valid{target="example.com"} 1
1482
1515
 
1483
1516
  Three further gauges appear only for the targets whose check actually ran, so a
1484
1517
  scrape never carries a misleading `0` for a check that was not requested:
1485
- `certinspect_hostname_match` (host targets), and — with `--verify` —
1518
+ `certinspect_hostname_match` (host targets), and — unless `--no-verify` —
1486
1519
  `certinspect_chain_trusted` and `certinspect_cert_revoked` (the latter only when
1487
1520
  OCSP/CRL returns a definitive answer). This lets you alert directly on chain,
1488
1521
  hostname and revocation problems without parsing text:
@@ -1527,18 +1560,22 @@ severe first:
1527
1560
  hostname mismatch → `1` runtime error (e.g. unreachable host) → `8` SAN
1528
1561
  missing → `9` policy → `3` expiring → `0` valid.
1529
1562
 
1530
- | Code | Meaning |
1531
- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1532
- | 0 | Valid certificate |
1533
- | 1 | Runtime error (network, file, parse) |
1534
- | 2 | Command-line usage error |
1535
- | 3 | Expiring within the `--days` threshold |
1536
- | 4 | Expired, not yet valid, or with invalid dates |
1537
- | 5 | Hostname does not match the certificate |
1538
- | 6 | Chain not trusted or revoked (`--verify`) |
1539
- | 7 | Fingerprint does not match `--pin` |
1540
- | 8 | Expected SAN missing (`--expect-san`) |
1541
- | 9 | Policy violation (`--not-after-max`/`--cab-forum`, `--min-key-size`, `--fail-weak`, `--require-sct`, `--require-must-staple`, `--require-revocation-check`, `--min-tls-version`) |
1563
+ Two options replace these codes: `--exporter nagios` exits with the plugin
1564
+ convention (`0` OK, `1` WARNING, `2` CRITICAL) and `--exit-zero` always exits
1565
+ `0`.
1566
+
1567
+ | Code | Meaning |
1568
+ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1569
+ | 0 | Valid certificate |
1570
+ | 1 | Runtime error (network, file, parse) |
1571
+ | 2 | Command-line usage error |
1572
+ | 3 | Expiring within the `--days` threshold |
1573
+ | 4 | Expired, not yet valid, with invalid dates, or expiring within `--critical-days` |
1574
+ | 5 | Hostname does not match the certificate |
1575
+ | 6 | Chain not trusted or certificate revoked (verification is on by default; `--no-verify` skips it) |
1576
+ | 7 | Fingerprint does not match `--pin` |
1577
+ | 8 | Expected SAN missing (`--expect-san`) |
1578
+ | 9 | Policy violation (`--profile`, `--not-after-max`/`--cab-forum`, `--min-key-size`, `--fail-weak`, `--require-sct`, `--require-must-staple`, `--require-revocation-check`, `--min-tls-version`), or an unexpected issuer with `--discover-only --expect-issuer` |
1542
1579
 
1543
1580
  Example in a script:
1544
1581
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "certinspect"
3
- version = "2.4.0"
3
+ version = "2.4.1"
4
4
  description = "Command-line TLS certificate inspector"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -1,3 +1,3 @@
1
1
  """certinspect — command-line TLS certificate inspector."""
2
2
 
3
- __version__ = "2.4.0"
3
+ __version__ = "2.4.1"
@@ -346,7 +346,8 @@ def build_parser() -> argparse.ArgumentParser:
346
346
  "Apply a named bundle of the opt-in policy checks (exit code 9) in "
347
347
  "one go. Intensity ladder, not an official standard: 'lenient' = "
348
348
  "TLS >= 1.2 and fail on weak crypto; 'standard' adds a 2048-bit "
349
- "minimum key; 'strict' = TLS >= 1.3, 2048-bit key, weak-crypto "
349
+ "minimum RSA/DSA key; 'strict' = TLS >= 1.3, 2048-bit RSA/DSA key, "
350
+ "weak-crypto "
350
351
  "failure, required Certificate Transparency SCTs and the CA/Browser "
351
352
  "Forum validity cap. Any explicit flag overrides the profile; the "
352
353
  "TLS-version part applies to host targets only. Passing a profile "
@@ -444,7 +445,10 @@ def build_parser() -> argparse.ArgumentParser:
444
445
  parser.add_argument(
445
446
  "--export",
446
447
  metavar="PATH",
447
- help="Save the inspected certificate as a PEM file at PATH.",
448
+ help=(
449
+ "Save the inspected certificate as a PEM file at PATH. Needs a "
450
+ "single target (host or --file)."
451
+ ),
448
452
  )
449
453
  parser.add_argument(
450
454
  "--starttls",
@@ -524,7 +528,8 @@ def build_parser() -> argparse.ArgumentParser:
524
528
  "compare against the previous run. Combine with --only-changed to "
525
529
  "show only the targets whose status changed; without it, the file "
526
530
  "is simply kept up to date for the next run. Host targets only; a "
527
- "target seen for the first time counts as changed."
531
+ "target seen for the first time counts as changed, and one that "
532
+ "cannot be reached keeps its last known status."
528
533
  ),
529
534
  )
530
535
  parser.add_argument(
@@ -656,6 +656,8 @@ def main() -> None:
656
656
  parser.error("There is no target or no file to inspect.")
657
657
  if file_targets.count("-") > 1:
658
658
  parser.error("--file '-' (standard input) may be given at most once.")
659
+ if args.export and len(host_targets) + len(file_targets) > 1:
660
+ parser.error("--export saves a single certificate; give one target.")
659
661
 
660
662
  # With STARTTLS, fall back to the protocol's standard port unless the user
661
663
  # passed --port explicitly (i.e. it differs from the 443 default).
@@ -723,7 +725,11 @@ def main() -> None:
723
725
  changed_targets = {
724
726
  t for t, status in current_state.items() if previous_state.get(t) != status
725
727
  }
726
- save_state(args.state_file, current_state)
728
+ # A target that failed this run keeps its last known status, so a
729
+ # transient outage is not reported as a change once it recovers.
730
+ failed = {name for name, _ in errors}
731
+ kept = {t: s for t, s in previous_state.items() if t in failed}
732
+ save_state(args.state_file, {**kept, **current_state})
727
733
 
728
734
  override = render(
729
735
  results,
@@ -9,9 +9,11 @@ import csv
9
9
  import io
10
10
  import json
11
11
 
12
+ from cryptography import x509
13
+
12
14
  from certinspect.exit_codes import ExitCode, Status
13
15
  from certinspect.models import CertificateInfo
14
- from certinspect.parser import certificate_status
16
+ from certinspect.parser import certificate_status, common_name
15
17
 
16
18
  LABEL_WIDTH = 16
17
19
 
@@ -282,9 +284,9 @@ def format_fields(
282
284
 
283
285
  # Columns emitted by format_csv, in order. The first element is the header
284
286
  # label; the second pulls the value out of a (target, info) pair. The columns
285
- # are deliberately lean and free of embedded commas (CN only, no full DN,
286
- # serial or fingerprint) so the file opens cleanly in a spreadsheet; the
287
- # dropped fields remain available via --json.
287
+ # are deliberately lean (CN only, no full DN, serial or fingerprint) so the
288
+ # file opens cleanly in a spreadsheet; a name that itself contains a comma is
289
+ # quoted by the csv writer. The dropped fields remain available via --json.
288
290
  _CSV_COLUMNS = (
289
291
  ("target", lambda target, info: target or ""),
290
292
  ("common_name", lambda target, info: _common_name(info["subject"])),
@@ -298,12 +300,15 @@ _CSV_COLUMNS = (
298
300
 
299
301
 
300
302
  def _common_name(dn: str) -> str:
301
- """Return the CN from an RFC 4514 distinguished name, or the whole DN."""
302
- for field in dn.split(","):
303
- field = field.strip()
304
- if field.startswith("CN="):
305
- return field[3:]
306
- return dn
303
+ """Return the CN from an RFC 4514 distinguished name, or the whole DN.
304
+
305
+ The DN is parsed rather than split on commas: a value may contain an
306
+ escaped comma, and even a fake ``CN=`` smuggled into another attribute.
307
+ """
308
+ try:
309
+ return common_name(x509.Name.from_rfc4514_string(dn))
310
+ except ValueError:
311
+ return dn
307
312
 
308
313
 
309
314
  def format_csv(
@@ -453,7 +458,9 @@ def format_nagios(
453
458
  info, warn_days, critical_days
454
459
  )
455
460
  days = info["days_to_expire"]
456
- perfdata = f"days={days};{warn_days};{critical_days or 0}"
461
+ # "N:" alerts below N; a bare "N" would alert above it (plugin range rules).
462
+ critical = critical_days if critical_days is not None else 0
463
+ perfdata = f"days={days};{warn_days}:;{critical}:"
457
464
  lines.append(
458
465
  f"{_NAGIOS_LABELS[severity]}: {name} certificate {status} "
459
466
  f"({days} days to expiry) | {perfdata}"
@@ -116,10 +116,10 @@ def chain_summary(cert: x509.Certificate) -> dict:
116
116
 
117
117
  def _short_name(cert: x509.Certificate) -> str:
118
118
  """Return the certificate's Common Name, or its full subject DN."""
119
- return _name_cn(cert.subject)
119
+ return common_name(cert.subject)
120
120
 
121
121
 
122
- def _name_cn(name: x509.Name) -> str:
122
+ def common_name(name: x509.Name) -> str:
123
123
  """Return the Common Name of an X.509 name, or its full RFC 4514 DN."""
124
124
  attrs = name.get_attributes_for_oid(NameOID.COMMON_NAME)
125
125
  return attrs[0].value if attrs else name.rfc4514_string()
@@ -193,9 +193,9 @@ def diagnose_chain(presented: list[x509.Certificate]) -> dict | None:
193
193
  ),
194
194
  }
195
195
 
196
- issuer_cn = _name_cn(leaf.issuer)
196
+ issuer_cn = common_name(leaf.issuer)
197
197
  if any(leaf.issuer == cert.subject for cert in intermediates):
198
- anchor = _name_cn(presented[-1].issuer)
198
+ anchor = common_name(presented[-1].issuer)
199
199
  return {
200
200
  "code": "UNTRUSTED_ROOT",
201
201
  "detail": (
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: certinspect
3
- Version: 2.4.0
3
+ Version: 2.4.1
4
4
  Summary: Command-line TLS certificate inspector
5
5
  Author-email: Michele Angrisano <michele.angrisano@gmail.com>
6
6
  License-Expression: MIT
@@ -488,11 +488,11 @@ certinspect internal.example.lan --verify --cafile ./internal-ca.pem
488
488
 
489
489
  ### Catch a revoked certificate
490
490
 
491
- `--verify` queries OCSP and falls back to the CRL; a revoked leaf fails with
492
- exit `6`:
491
+ Verification is on by default: it queries OCSP and falls back to the CRL, and a
492
+ revoked leaf fails with exit `6`:
493
493
 
494
494
  ```bash
495
- certinspect revoked.example.com --verify
495
+ certinspect revoked.example.com
496
496
  ```
497
497
 
498
498
  ### Spot an expired intermediate before it breaks the chain
@@ -659,7 +659,7 @@ certinspect example.com --export ./example.com.pem
659
659
  | `--summary` | Print a one-line tally (valid/expiring/expired/errors) to stderr; counts every target before filtering. |
660
660
  | `--field NAME` | Print only the given field(s), one tab-separated line per target (repeatable; `target` for the host). For scripting without a JSON tool. |
661
661
  | `--exit-zero` | Always exit 0, even on problems or fetch errors. Report-only mode for dashboards/CI that read the output, not the exit code. |
662
- | `--export PATH` | Save the inspected certificate as a PEM file at PATH. |
662
+ | `--export PATH` | Save the inspected certificate as a PEM file at PATH. Single target only. |
663
663
  | `--starttls {smtp,imap,pop3,ftp}` | Upgrade a plaintext connection to TLS before inspecting (standard port unless `--port` is given). |
664
664
  | `--exporter {nagios,prometheus}` | Emit machine-readable monitoring output (ignores `--quiet`). |
665
665
  | `--concurrency N` | Inspect up to N hosts in parallel in batch mode (default: 1; order is preserved). Also governs `--discover`'s per-domain concurrency. |
@@ -707,6 +707,10 @@ SAN:
707
707
  ```
708
708
 
709
709
  Passing several hosts prints one `=== host ===` block per target (batch mode).
710
+ A target on a non-default port is labelled `host:port` (e.g.
711
+ `=== example.com:8443 ===`) there and in every other output, the
712
+ `--state-file` and the Prometheus `target` label, so several services on the
713
+ same host stay apart.
710
714
 
711
715
  ### `--file PATH` — inspect a local certificate
712
716
 
@@ -816,6 +820,10 @@ The `status` field mirrors the human report's `Status` line (`VALID`,
816
820
  honors `--days` / `--critical-days`, so a JSON consumer gets the verdict
817
821
  without re-deriving it from the dates.
818
822
 
823
+ `key.type` is the key family (`RSA`, `EC`, `DSA`, `Ed25519` or `Ed448`).
824
+ EdDSA keys have a fixed size, so for them `key.size` is `null` (`n/a` in the
825
+ text report).
826
+
819
827
  Need the pre-2.0 flat array (no envelope, dates via `str()`, integer serial)?
820
828
  Pass `--schema 1`:
821
829
 
@@ -892,6 +900,19 @@ $ certinspect --file ./bundle.pem --verify
892
900
  Chain trusted: True
893
901
  ```
894
902
 
903
+ For a host, revocation is checked over OCSP first, falling back to the CRL. An
904
+ answer only counts when it is authentic: the OCSP response must be about this
905
+ certificate and signed by its issuer (or by a responder the issuer delegated
906
+ with the OCSP Signing EKU); the CRL must be signed by the issuer, name it and
907
+ cover this kind of certificate. The issuer itself, taken from the verified
908
+ chain or downloaded from the certificate's AIA URL, must have signed the leaf.
909
+ Anything else is reported as `UNAVAILABLE` — a browser-like soft-fail that
910
+ leaves the exit code alone; add
911
+ [`--require-revocation-check`](#--require-revocation-check) to make it fail.
912
+ The OCSP, CRL and issuer URLs come from the certificate, so certinspect
913
+ refuses to fetch loopback, link-local (cloud metadata) or other internal
914
+ addresses — also after an HTTP redirect — and caps each response at 16 MB.
915
+
895
916
  ### `--chain`
896
917
 
897
918
  ```console
@@ -1172,13 +1193,13 @@ you had passed the flags yourself.
1172
1193
 
1173
1194
  Each stricter tier is a superset of the one below it:
1174
1195
 
1175
- | Check (flag) | `lenient` | `standard` | `strict` |
1176
- | --------------------------------------------- | :-------: | :--------: | :---------: |
1177
- | Minimum TLS version (`--min-tls-version`) | TLSv1.2 | TLSv1.2 | **TLSv1.3** |
1178
- | Fail on weak crypto (`--fail-weak`) | yes | yes | yes |
1179
- | Minimum key size (`--min-key-size`) | — | 2048 bit | 2048 bit |
1180
- | Require CT SCTs (`--require-sct`) | — | — | yes |
1181
- | CA/Browser Forum validity cap (`--cab-forum`) | — | — | yes |
1196
+ | Check (flag) | `lenient` | `standard` | `strict` |
1197
+ | --------------------------------------------- | :-------: | :----------------: | :----------------: |
1198
+ | Minimum TLS version (`--min-tls-version`) | TLSv1.2 | TLSv1.2 | **TLSv1.3** |
1199
+ | Fail on weak crypto (`--fail-weak`) | yes | yes | yes |
1200
+ | Minimum key size (`--min-key-size`) | — | 2048 bit (RSA/DSA) | 2048 bit (RSA/DSA) |
1201
+ | Require CT SCTs (`--require-sct`) | — | — | yes |
1202
+ | CA/Browser Forum validity cap (`--cab-forum`) | — | — | yes |
1182
1203
 
1183
1204
  Precedence and edge cases a sysadmin should know:
1184
1205
 
@@ -1287,7 +1308,9 @@ summary: 1 valid · 0 expiring · 0 expired · 1 error (2 targets)
1287
1308
  Print only the fields you ask for, one tab-separated line per target, so you
1288
1309
  can pull values straight into a script without a JSON tool. Repeat `--field`
1289
1310
  for several columns; the pseudo-field `target` is the inspected host and list
1290
- fields (like `san`) are comma-joined.
1311
+ fields (like `san`) are comma-joined. Any key of the `--json --schema 1`
1312
+ output is a valid name (e.g. `issuer`, `key_type`, `key_size`,
1313
+ `revocation_status`).
1291
1314
 
1292
1315
  ```console
1293
1316
  $ certinspect example.com github.com --field target --field days_to_expire --field status
@@ -1316,7 +1339,9 @@ $ echo $?
1316
1339
 
1317
1340
  ### `--export PATH`
1318
1341
 
1319
- Save the fetched certificate as PEM and still print the report.
1342
+ Save the fetched certificate as PEM and still print the report. It takes a
1343
+ single target; with several (hosts, `--file`s or a `--discover` result) the
1344
+ command stops with a usage error rather than overwriting the same file.
1320
1345
 
1321
1346
  ```console
1322
1347
  $ certinspect example.com --export ./fetched.pem
@@ -1393,7 +1418,7 @@ Machine-readable monitoring output (full examples in
1393
1418
 
1394
1419
  ```console
1395
1420
  $ certinspect example.com --exporter nagios
1396
- OK: example.com certificate VALID (64 days to expiry) | days=64;30;0
1421
+ OK: example.com certificate VALID (64 days to expiry) | days=64;30:;0:
1397
1422
  ```
1398
1423
 
1399
1424
  ### `--version`
@@ -1450,7 +1475,10 @@ Status: EXPIRING
1450
1475
  ```
1451
1476
 
1452
1477
  The state file is always brought up to date, whether or not `--only-changed`
1453
- is given, so the next run has a fresh baseline to compare against.
1478
+ is given, so the next run has a fresh baseline to compare against. A target
1479
+ that cannot be reached keeps its last known status, so a transient outage is
1480
+ reported as an error on that run (exit code 1) but not as a change once the
1481
+ host is back; a target removed from the list is dropped from the file.
1454
1482
 
1455
1483
  ### `--print-completion {bash,zsh}`
1456
1484
 
@@ -1485,10 +1513,15 @@ host is CRITICAL:
1485
1513
 
1486
1514
  ```console
1487
1515
  $ certinspect example.com expired.example.com --exporter nagios
1488
- OK: example.com certificate VALID (217 days to expiry) | days=217;30;0
1489
- CRITICAL: expired.example.com certificate EXPIRED (-3 days to expiry) | days=-3;30;0
1516
+ OK: example.com certificate VALID (217 days to expiry) | days=217;30:;0:
1517
+ CRITICAL: expired.example.com certificate EXPIRED (-3 days to expiry) | days=-3;30:;0:
1490
1518
  ```
1491
1519
 
1520
+ The perfdata thresholds use the `N:` range form, "alert below N": `30:` is the
1521
+ `--days` warning, `0:` the critical one (expired), or `--critical-days` when set
1522
+ (`days=12;30:;7:`), so graphers colour each series exactly as the plugin rates
1523
+ it.
1524
+
1492
1525
  `prometheus` emits textfile-collector metrics (`certinspect_up`,
1493
1526
  `certinspect_cert_expiry_days`, `certinspect_cert_valid`), keeping the normal
1494
1527
  worst-status exit code:
@@ -1508,7 +1541,7 @@ certinspect_cert_valid{target="example.com"} 1
1508
1541
 
1509
1542
  Three further gauges appear only for the targets whose check actually ran, so a
1510
1543
  scrape never carries a misleading `0` for a check that was not requested:
1511
- `certinspect_hostname_match` (host targets), and — with `--verify` —
1544
+ `certinspect_hostname_match` (host targets), and — unless `--no-verify` —
1512
1545
  `certinspect_chain_trusted` and `certinspect_cert_revoked` (the latter only when
1513
1546
  OCSP/CRL returns a definitive answer). This lets you alert directly on chain,
1514
1547
  hostname and revocation problems without parsing text:
@@ -1553,18 +1586,22 @@ severe first:
1553
1586
  hostname mismatch → `1` runtime error (e.g. unreachable host) → `8` SAN
1554
1587
  missing → `9` policy → `3` expiring → `0` valid.
1555
1588
 
1556
- | Code | Meaning |
1557
- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1558
- | 0 | Valid certificate |
1559
- | 1 | Runtime error (network, file, parse) |
1560
- | 2 | Command-line usage error |
1561
- | 3 | Expiring within the `--days` threshold |
1562
- | 4 | Expired, not yet valid, or with invalid dates |
1563
- | 5 | Hostname does not match the certificate |
1564
- | 6 | Chain not trusted or revoked (`--verify`) |
1565
- | 7 | Fingerprint does not match `--pin` |
1566
- | 8 | Expected SAN missing (`--expect-san`) |
1567
- | 9 | Policy violation (`--not-after-max`/`--cab-forum`, `--min-key-size`, `--fail-weak`, `--require-sct`, `--require-must-staple`, `--require-revocation-check`, `--min-tls-version`) |
1589
+ Two options replace these codes: `--exporter nagios` exits with the plugin
1590
+ convention (`0` OK, `1` WARNING, `2` CRITICAL) and `--exit-zero` always exits
1591
+ `0`.
1592
+
1593
+ | Code | Meaning |
1594
+ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1595
+ | 0 | Valid certificate |
1596
+ | 1 | Runtime error (network, file, parse) |
1597
+ | 2 | Command-line usage error |
1598
+ | 3 | Expiring within the `--days` threshold |
1599
+ | 4 | Expired, not yet valid, with invalid dates, or expiring within `--critical-days` |
1600
+ | 5 | Hostname does not match the certificate |
1601
+ | 6 | Chain not trusted or certificate revoked (verification is on by default; `--no-verify` skips it) |
1602
+ | 7 | Fingerprint does not match `--pin` |
1603
+ | 8 | Expected SAN missing (`--expect-san`) |
1604
+ | 9 | Policy violation (`--profile`, `--not-after-max`/`--cab-forum`, `--min-key-size`, `--fail-weak`, `--require-sct`, `--require-must-staple`, `--require-revocation-check`, `--min-tls-version`), or an unexpected issuer with `--discover-only --expect-issuer` |
1568
1605
 
1569
1606
  Example in a script:
1570
1607
 
@@ -1272,6 +1272,47 @@ def test_main_export_writes_pem(monkeypatch, capsys, tmp_path, make_cert):
1272
1272
  assert content.startswith(b"-----BEGIN CERTIFICATE-----")
1273
1273
 
1274
1274
 
1275
+ def test_main_export_rejects_several_hosts(monkeypatch, capsys, tmp_path, make_cert):
1276
+ certs = {"a.com": make_cert(san=["a.com"]), "b.com": make_cert(san=["b.com"])}
1277
+ monkeypatch.setattr("certinspect.cli.get_server_cert", _fake_fetch(certs))
1278
+ out_path = tmp_path / "exported.pem"
1279
+
1280
+ code = _run_main(monkeypatch, ["a.com", "b.com", "--export", str(out_path)])
1281
+
1282
+ assert code == 2
1283
+ assert "--export" in capsys.readouterr().err
1284
+ assert not out_path.exists()
1285
+
1286
+
1287
+ def test_main_export_rejects_several_files(monkeypatch, capsys, tmp_path, make_cert):
1288
+ first, second = tmp_path / "a.der", tmp_path / "b.der"
1289
+ first.write_bytes(make_cert())
1290
+ second.write_bytes(make_cert())
1291
+ out_path = tmp_path / "exported.pem"
1292
+ argv = ["--file", str(first), "--file", str(second), "--export", str(out_path)]
1293
+
1294
+ assert _run_main(monkeypatch, argv) == 2
1295
+ assert not out_path.exists()
1296
+
1297
+
1298
+ def test_main_export_rejects_a_discovery_that_finds_several_hosts(
1299
+ monkeypatch, capsys, tmp_path, make_cert
1300
+ ):
1301
+ monkeypatch.setattr(
1302
+ "certinspect.cli.discover_hostnames",
1303
+ lambda domain, timeout: ["a.example.com", "b.example.com"],
1304
+ )
1305
+ monkeypatch.setattr(
1306
+ "certinspect.cli.get_server_cert",
1307
+ lambda host, port, timeout, **kwargs: (make_cert(san=[host]), CONN),
1308
+ )
1309
+ out_path = tmp_path / "exported.pem"
1310
+ argv = ["--discover", "example.com", "--export", str(out_path)]
1311
+
1312
+ assert _run_main(monkeypatch, argv) == 2
1313
+ assert not out_path.exists()
1314
+
1315
+
1275
1316
  def _fake_fetch(mapping):
1276
1317
  """Return a get_server_cert replacement backed by host->bytes mapping."""
1277
1318
 
@@ -2259,6 +2300,80 @@ def test_main_state_file_malformed_is_treated_as_empty(
2259
2300
  assert "=== a.com ===" in out
2260
2301
 
2261
2302
 
2303
+ def _fetch_with_outage(certs, down):
2304
+ """A get_server_cert replacement whose hosts in ``down`` are unreachable."""
2305
+
2306
+ def _fetch(host, port, timeout, starttls=None, servername=None):
2307
+ if host in down:
2308
+ raise OSError("connection refused")
2309
+ return certs[host], CONN
2310
+
2311
+ return _fetch
2312
+
2313
+
2314
+ def _state_run(monkeypatch, capsys, state_path, targets, certs, down=()):
2315
+ monkeypatch.setattr(
2316
+ "certinspect.cli.get_server_cert", _fetch_with_outage(certs, set(down))
2317
+ )
2318
+ argv = [*targets, "--state-file", str(state_path), "--only-changed"]
2319
+ _run_main(monkeypatch, argv)
2320
+ return capsys.readouterr().out
2321
+
2322
+
2323
+ def test_main_state_file_keeps_the_last_status_of_an_unreachable_target(
2324
+ monkeypatch, capsys, tmp_path, make_cert
2325
+ ):
2326
+ state_path = tmp_path / "state.json"
2327
+ state_path.write_text(json.dumps({"a.com": "VALID", "b.com": "VALID"}))
2328
+ certs = {"b.com": make_cert(san=["b.com"], days_valid=10)}
2329
+
2330
+ _state_run(monkeypatch, capsys, state_path, ["a.com", "b.com"], certs, ["a.com"])
2331
+
2332
+ assert json.loads(state_path.read_text()) == {
2333
+ "a.com": "VALID",
2334
+ "b.com": "EXPIRING",
2335
+ }
2336
+
2337
+
2338
+ def test_main_state_file_ignores_an_outage_on_recovery(
2339
+ monkeypatch, capsys, tmp_path, make_cert
2340
+ ):
2341
+ state_path = tmp_path / "state.json"
2342
+ certs = {"a.com": make_cert(san=["a.com"], days_valid=200)}
2343
+
2344
+ _state_run(monkeypatch, capsys, state_path, ["a.com"], certs)
2345
+ _state_run(monkeypatch, capsys, state_path, ["a.com"], certs, ["a.com"])
2346
+ out = _state_run(monkeypatch, capsys, state_path, ["a.com"], certs)
2347
+
2348
+ assert "=== a.com ===" not in out
2349
+
2350
+
2351
+ def test_main_state_file_reports_a_change_made_during_an_outage(
2352
+ monkeypatch, capsys, tmp_path, make_cert
2353
+ ):
2354
+ state_path = tmp_path / "state.json"
2355
+ valid = {"a.com": make_cert(san=["a.com"], days_valid=200)}
2356
+ expiring = {"a.com": make_cert(san=["a.com"], days_valid=10)}
2357
+
2358
+ _state_run(monkeypatch, capsys, state_path, ["a.com"], valid)
2359
+ _state_run(monkeypatch, capsys, state_path, ["a.com"], valid, ["a.com"])
2360
+ out = _state_run(monkeypatch, capsys, state_path, ["a.com"], expiring)
2361
+
2362
+ assert "=== a.com ===" in out
2363
+
2364
+
2365
+ def test_main_state_file_forgets_a_target_removed_from_the_list(
2366
+ monkeypatch, capsys, tmp_path, make_cert
2367
+ ):
2368
+ state_path = tmp_path / "state.json"
2369
+ state_path.write_text(json.dumps({"a.com": "VALID", "gone.com": "VALID"}))
2370
+ certs = {"a.com": make_cert(san=["a.com"], days_valid=200)}
2371
+
2372
+ _state_run(monkeypatch, capsys, state_path, ["a.com"], certs)
2373
+
2374
+ assert json.loads(state_path.read_text()) == {"a.com": "VALID"}
2375
+
2376
+
2262
2377
  def test_main_only_changed_requires_state_file(monkeypatch, capsys):
2263
2378
  code = _run_main(monkeypatch, ["a.com", "--only-changed"])
2264
2379
  assert code == 2
@@ -268,6 +268,54 @@ def test_format_nagios_overall_is_worst_severity(make_cert):
268
268
  assert code == NAGIOS_WARNING
269
269
 
270
270
 
271
+ @pytest.mark.parametrize(
272
+ "critical_days, thresholds", [(7, ";30:;7:"), (None, ";30:;0:")]
273
+ )
274
+ def test_format_nagios_perfdata_alerts_below_the_thresholds(
275
+ make_cert, critical_days, thresholds
276
+ ):
277
+ info = _info(make_cert(days_valid=200))
278
+ text, _ = format_nagios(
279
+ [("example.com", info, 0)], warn_days=30, critical_days=critical_days
280
+ )
281
+ assert text.endswith(f"| days={info['days_to_expire']}{thresholds}")
282
+
283
+
284
+ def _breaches(value: float, threshold: str) -> bool:
285
+ """Monitoring Plugins range rule: "N" is 0..N, "N:" is N..inf; alert outside."""
286
+ low, sep, high = threshold.partition(":")
287
+ if not sep:
288
+ low, high = "0", low
289
+ return not (float(low or 0) <= value <= float(high or "inf"))
290
+
291
+
292
+ @pytest.mark.parametrize(
293
+ "days_valid, critical_days",
294
+ [(45, 7), (20, 7), (3, 7), (45, None), (-2, None)],
295
+ )
296
+ def test_format_nagios_perfdata_agrees_with_the_plugin_state(
297
+ make_cert, days_valid, critical_days
298
+ ):
299
+ from certinspect.exit_codes import EXIT_BY_STATUS
300
+ from certinspect.parser import certificate_status
301
+
302
+ info = _info(make_cert(days_valid=days_valid, days_ago_start=30))
303
+ info["status"] = certificate_status(info, 30, critical_days)
304
+ code = EXIT_BY_STATUS[info["status"]]
305
+ text, _ = format_nagios(
306
+ [("example.com", info, code)], warn_days=30, critical_days=critical_days
307
+ )
308
+ label, perfdata = text.split(" | ")
309
+ value, warn, crit = perfdata.removeprefix("days=").split(";")
310
+ if _breaches(float(value), crit):
311
+ graphed = "CRITICAL"
312
+ elif _breaches(float(value), warn):
313
+ graphed = "WARNING"
314
+ else:
315
+ graphed = "OK"
316
+ assert label.startswith(f"{graphed}:")
317
+
318
+
271
319
  def test_format_prometheus_exposes_metrics(make_cert):
272
320
  info = _info(make_cert(days_valid=42))
273
321
  results = [("example.com", info, 0)]
@@ -419,6 +467,35 @@ def test_format_csv_issuer_is_common_name_only(make_cert):
419
467
  assert rows[0]["issuer"] == "Example Root CA"
420
468
 
421
469
 
470
+ def test_format_csv_keeps_a_comma_inside_the_common_name(make_cert):
471
+ info = _info(make_cert(common_name="ACME, Inc", san=["example.com"]))
472
+ rows = _parse_csv(format_csv([("example.com", info, 0)]))
473
+ assert rows[0]["common_name"] == "ACME, Inc"
474
+
475
+
476
+ def test_format_csv_issuer_cannot_be_spoofed_by_an_escaped_cn(make_cert):
477
+ info = _info(make_cert(san=["example.com"]))
478
+ # An Organization value that smuggles a fake "CN=" after an escaped comma.
479
+ info["issuer"] = "O=x\\,CN=DigiCert Global G2,CN=Mallory Self-Signed"
480
+ rows = _parse_csv(format_csv([("example.com", info, 0)]))
481
+ assert rows[0]["issuer"] == "Mallory Self-Signed"
482
+
483
+
484
+ def test_format_csv_issuer_without_common_name_keeps_the_dn(make_cert):
485
+ from cryptography import x509
486
+ from cryptography.x509.oid import NameOID
487
+
488
+ info = _info(make_cert(san=["example.com"]))
489
+ info["issuer"] = x509.Name(
490
+ [
491
+ x509.NameAttribute(NameOID.EMAIL_ADDRESS, "pki@example.com"),
492
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "No CN Here"),
493
+ ]
494
+ ).rfc4514_string()
495
+ rows = _parse_csv(format_csv([("example.com", info, 0)]))
496
+ assert rows[0]["issuer"] == info["issuer"]
497
+
498
+
422
499
  def test_format_csv_custom_delimiter(make_cert):
423
500
  info = _info(make_cert(san=["example.com"], days_valid=200))
424
501
  text = format_csv([("example.com", info, 0)], delimiter=";")
File without changes
File without changes