-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrust.py
More file actions
478 lines (385 loc) · 16.1 KB
/
trust.py
File metadata and controls
478 lines (385 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2025 netcon-sync contributors
#
# This file is part of netcon-sync.
# netcon-sync is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
"""
Certificate handling for NSS database-backed HTTPS verification.
Pure library functions - no CLI code. The CLI tools (pfsense2unifi.py, etc.)
handle certificate trust operations via their own arguments.
"""
import subprocess
import tempfile
import sys
import re
from pathlib import Path
from urllib.parse import urlparse
from http_tls_nss import get_server_certificate
import nss.error
def ensure_nss_db(nss_db_dir):
"""
Ensure the NSS database directory and files exist.
Args:
nss_db_dir: Path to NSS database directory
"""
nss_db_dir = Path(nss_db_dir)
nss_db_dir.mkdir(parents=True, exist_ok=True)
# Initialize NSS db if it doesn't exist
if not (nss_db_dir / "cert9.db").exists():
# Create empty database using certutil
try:
subprocess.run(
["certutil", "-N", "-d", str(nss_db_dir), "-f", "/dev/null"],
check=True,
capture_output=True,
timeout=10
)
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Failed to initialize NSS database: {e}")
except FileNotFoundError:
raise RuntimeError("certutil not found. Install nss-tools package.")
def get_cert_fingerprints(hostname: str, port: int = 443) -> dict:
"""
Retrieve SHA-1 and SHA-256 fingerprints for a server's SSL certificate.
Uses NSS/NSPR socket layer for consistent TLS handling.
Args:
hostname (str): The hostname or IP address
port (int): The port number (default: 443)
Returns:
dict: Contains 'sha1' and 'sha256' fingerprint strings and 'der' certificate data
Raises:
Exception: If unable to retrieve the certificate
"""
return get_server_certificate(hostname, port)
def is_cert_trusted(nss_db_dir, hostname: str, port: int = 443) -> bool:
"""
Check if a server certificate is trusted in the NSS database (non-interactive).
Checks the trust attributes using certutil.
Args:
nss_db_dir: Path to NSS database directory
hostname (str): The hostname or IP address
port (int): The port number (default: 443)
Returns:
bool: True if the certificate is trusted, False otherwise
"""
ensure_nss_db(nss_db_dir)
nss_db_dir = Path(nss_db_dir)
try:
nickname = f"{hostname}:{port}"
# Use certutil to list all certificates and find ours
result = subprocess.run(
["certutil", "-L", "-d", str(nss_db_dir)],
capture_output=True,
timeout=10,
text=True
)
if result.returncode == 0:
# Look for the nickname in the output
# The trust attributes are shown with the nickname, like "P,,"
# Check if our nickname appears with trust bit 'P' (peer/server)
for line in result.stdout.split('\n'):
if nickname in line:
# Check if trust bits contain 'P' (trusted peer certificate for TLS server)
return 'P' in line or 'C' in line
return False
except Exception:
return False
def _cert_exists(nss_db_dir, nickname: str) -> bool:
"""
Check if a certificate with the given nickname exists in the NSS database.
Args:
nss_db_dir: Path to NSS database directory
nickname (str): Certificate nickname to check
Returns:
bool: True if certificate exists, False otherwise
"""
nss_db_dir = Path(nss_db_dir)
try:
result = subprocess.run(
["certutil", "-L", "-d", str(nss_db_dir)],
capture_output=True,
timeout=10,
text=True
)
if result.returncode == 0:
for line in result.stdout.split('\n'):
if nickname in line:
return True
return False
except Exception:
return False
def import_ca_cert(nss_db_dir, cert_path: str, nickname: str = None) -> tuple:
"""
Import a CA certificate (DER or PEM) into the NSS database.
Checks if a certificate with the same nickname already exists.
If it does, returns without importing (idempotent).
Args:
nss_db_dir: Path to NSS database directory
cert_path (str): Path to certificate file (DER or PEM)
nickname (str): Nickname for the certificate in NSS (optional)
Returns:
tuple: (nickname, was_newly_imported) where was_newly_imported is bool
Raises:
FileNotFoundError: If certificate file not found
RuntimeError: If import fails
"""
ensure_nss_db(nss_db_dir)
nss_db_dir = Path(nss_db_dir)
cert_file = Path(cert_path)
if not cert_file.exists():
raise FileNotFoundError(f"Certificate file not found: {cert_path}")
# Use provided nickname or derive from filename
if nickname is None:
nickname = cert_file.stem
# Check if certificate already exists
if _cert_exists(nss_db_dir, nickname):
return (nickname, False)
try:
subprocess.run(
[
"certutil",
"-A",
"-d", str(nss_db_dir),
"-n", nickname,
"-t", "CT,,", # CT = Trusted CA certificate
"-i", str(cert_file)
],
check=True,
capture_output=True,
timeout=10
)
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Failed to import certificate: {e.stderr.decode()}")
return (nickname, True)
def import_server_cert(nss_db_dir, hostname: str, port: int = 443, nickname: str = None) -> str:
"""
Fetch and import a server's certificate into the NSS database.
Args:
nss_db_dir: Path to NSS database directory
hostname (str): The hostname or IP address
port (int): The port number (default: 443)
nickname (str): Nickname for the certificate (optional)
Returns:
str: The nickname used in the database
Raises:
Exception: If certificate retrieval or import fails
"""
ensure_nss_db(nss_db_dir)
nss_db_dir = Path(nss_db_dir)
# Use provided nickname or derive from hostname:port
if nickname is None:
nickname = f"{hostname}:{port}"
try:
fingerprints = get_cert_fingerprints(hostname, port)
# Write DER data to temporary file (certutil needs file input)
with tempfile.NamedTemporaryFile(suffix='.der', delete=False) as tmp:
tmp.write(fingerprints["der"])
tmp_path = tmp.name
try:
# Import the certificate from the temporary file
subprocess.run(
[
"certutil",
"-A",
"-d", str(nss_db_dir),
"-n", nickname,
"-t", "P,,", # P = Trusted peer certificate
"-i", tmp_path
],
check=True,
capture_output=True,
timeout=10
)
finally:
# Clean up the temporary file
Path(tmp_path).unlink(missing_ok=True)
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Failed to import server certificate: {e.stderr.decode()}")
return nickname
def interactive_trust_server_cert(nss_db_dir, hostname: str, port: int = 443) -> bool:
"""
Interactively prompt user to trust a server certificate.
Checks if the certificate is already trusted. If yes, informs user and returns.
Otherwise, fetches the certificate, displays PKI details (SHA-1 and SHA-256 fingerprints),
asks for user confirmation, and imports if approved.
This function encapsulates all PKI display logic and user interaction.
Args:
nss_db_dir: Path to NSS database directory
hostname (str): The hostname or IP address
port (int): The port number (default: 443)
Returns:
bool: True if certificate is trusted (already or newly imported), False if rejected
Raises:
Exception: If certificate retrieval or import fails
"""
ensure_nss_db(nss_db_dir)
# Check if certificate is already trusted
if is_cert_trusted(nss_db_dir, hostname, port):
print(f"[OK] Certificate for {hostname}:{port} is already trusted.")
return True
try:
# Fetch fingerprints
fingerprints = get_cert_fingerprints(hostname, port)
def _print_cert_block(title: str, cert_info: dict, include_fingerprints: bool = False) -> None:
"""Render a certificate summary for interactive confirmation."""
print(title)
print(f" Subject: {cert_info.get('subject', 'unknown')}")
print(f" Issuer: {cert_info.get('issuer', 'unknown')}")
print(f" Serial: {cert_info.get('serial_number', 'unknown')}")
print(f" Not Before: {cert_info.get('not_before', 'unknown')}")
print(f" Not After: {cert_info.get('not_after', 'unknown')}")
alt_names = cert_info.get("subject_alt_names") or ()
if alt_names:
print(" Alt Names:")
for alt_name in alt_names:
print(f" - {alt_name}")
else:
print(" Alt Names: none")
if include_fingerprints:
print(f" SHA-1: {fingerprints['sha1']}")
print(f" SHA-256: {fingerprints['sha256']}")
# Display certificate details to user
print("\n" + "="*70)
print("CERTIFICATE DETAILS")
print("="*70)
print(f"Hostname: {hostname}")
print(f"Port: {port}")
print()
_print_cert_block("Leaf Certificate:", fingerprints, include_fingerprints=True)
chain = fingerprints.get("chain") or ()
if chain:
print()
print("Received Certificate Chain:")
for index, cert_info in enumerate(chain, start=1):
print(f" [{index}]")
_print_cert_block("", cert_info, include_fingerprints=False)
if index != len(chain):
print()
print("="*70)
# Ask for confirmation
print("\nPlease verify these certificate details match what you expect from the server.")
response = input("Do you trust this certificate? (type 'yes' or 'y' to accept): ").strip().lower()
if response not in ('yes', 'y'):
print("Certificate rejected.")
return False
# Import the certificate
nickname = import_server_cert(nss_db_dir, hostname, port)
print(f"\n[OK] Certificate imported as '{nickname}' and added to trusted store.")
return True
except Exception as e:
raise
# ==============================================================================
# ERROR FORMATTING - Certificate error messages
# ==============================================================================
def format_nss_error(server_name: str, server_url: str, error: Exception, prog_name: str) -> str:
"""
Format NSS certificate errors with helpful context and suggestions.
Args:
server_name (str): Human-readable name (e.g., "UniFi Controller", "pfSense")
server_url (str): Full server URL
error (Exception): The NSS error
prog_name (str): Program name (usually sys.argv[0])
Returns:
str: Formatted error message with suggestion
"""
if not isinstance(error, nss.error.NSPRError):
return str(error)
error_code = getattr(error, "error_code", getattr(error, "errno", None))
error_desc = getattr(error, "error_desc", "") or ""
error_name_match = re.match(r"^\(([^)]+)\)", error_desc)
error_name = error_name_match.group(1) if error_name_match else "UNKNOWN"
resolved_message = None
if error_code is not None:
resolved_message = nss.error.get_nspr_error_string(error_code)
raw_error = str(error)
header = "ERROR: NSPR/NSS FAILURE"
details = [
f"{header}: {server_name}",
"",
f"URL: {server_url}",
f"NSPR/NSS code: {error_name} ({error_code})" if error_code is not None else f"NSPR/NSS code: {error_name}",
]
if resolved_message:
details.append(f"Description: {resolved_message}")
if raw_error and raw_error != resolved_message:
details.append(f"Raw error: {raw_error}")
# PR_* connection failures are transport-level errors, not certificate errors.
# NSS' label is useful, but it can be overly specific from the user's point of view
# because it reflects the failing connect attempt NSS observed.
if error_name.startswith("PR_"):
details.extend([
"",
"This is a transport-level connection failure reported by NSS while connecting.",
"The specific PR_* label reflects NSS's view of the failed connect attempt and may",
"not uniquely identify the overall controller problem.",
])
# Trust commands are only relevant when NSS reports issuer/certificate trust problems.
if error_name in {"SEC_ERROR_UNTRUSTED_ISSUER", "SEC_ERROR_UNKNOWN_ISSUER", "SEC_ERROR_UNTRUSTED_CERT"}:
details.extend([
"",
f"This means the {server_name} certificate chain is not trusted by NSS.",
"",
"To fix this, you have two options:",
"",
"OPTION 1 (Preferred, if you have the issuing CA certificate file):",
f" {prog_name} trust --ca /path/to/[ca_cert.pem|ca_cert.der]",
"",
" This will trust all certificates signed by that CA.",
"",
"OPTION 2 (Trust the server certificate directly):",
f" {prog_name} trust --server {server_url}",
"",
" This will fetch the certificate, display its fingerprint for verification,",
" and add it to the trusted certificate store.",
])
return "\n".join(details).strip()
# ==============================================================================
# CLI HANDLERS - Used by pfsense2unifi.py and unifi_climgr.py
# ==============================================================================
def handle_trust_ca_cert(nss_db_dir, cert_path: str) -> None:
"""
CLI handler: Import a CA certificate from file into NSS database.
Prints status messages and exits with appropriate code.
Args:
nss_db_dir: Path to NSS database directory
cert_path (str): Path to certificate file (DER or PEM format)
This function exits with code 0 on success, 1 on failure.
"""
try:
nickname, was_newly_imported = import_ca_cert(nss_db_dir, cert_path)
if was_newly_imported:
print(f"[OK] CA certificate imported as '{nickname}'")
else:
print(f"[OK] CA certificate '{nickname}' is already imported.")
sys.exit(0)
except Exception as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
def handle_trust_server_url(nss_db_dir, server_url: str) -> None:
"""
CLI handler: Interactively trust a server certificate from URL.
Parses the URL, fetches the certificate, displays details, and imports if approved.
Args:
nss_db_dir: Path to NSS database directory
server_url (str): Server URL (e.g., https://example.com:8443)
This function exits with code 0 on success, 1 on failure.
"""
try:
parsed = urlparse(server_url)
hostname = parsed.hostname
port = parsed.port or 443
if not hostname:
print(f"ERROR: Invalid URL: {server_url}", file=sys.stderr)
sys.exit(1)
# Let trust module handle all PKI details and user interaction
if interactive_trust_server_cert(nss_db_dir, hostname, port):
sys.exit(0)
else:
sys.exit(1)
except Exception as e:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)