Debian Codegraph @

ipapython/certdb.py

raw
1 # Authors: Rob Crittenden <[email protected]>
2 #
3 # Copyright (C) 2009 Red Hat
4 # see file 'COPYING' for use and warranty information
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19 from __future__ import absolute_import
20
21 import collections
22 import datetime
23 import logging
24 import os
25 import io
26 import pwd
27 import grp
28 import re
29 import shutil
30 import stat
31 import tempfile
32 from ctypes.util import find_library
33 from tempfile import NamedTemporaryFile
34
35 import cryptography.x509
36
37 from ipaplatform.paths import paths
38 from ipaplatform.tasks import tasks
39 from ipapython.dn import DN
40 from ipapython.kerberos import Principal
41 from ipapython import ipautil
42 from ipalib import x509 # pylint: disable=ipa-forbidden-import
43
44
45 logger = logging.getLogger(__name__)
46
47 CA_NICKNAME_FMT = "%s IPA CA"
48
49 NSS_DBM_FILES = ("cert8.db", "key3.db", "secmod.db")
50 NSS_SQL_FILES = ("cert9.db", "key4.db", "pkcs11.txt")
51 NSS_FILES = NSS_DBM_FILES + NSS_SQL_FILES + ("pwdfile.txt",)
52
53 TrustFlags = collections.namedtuple('TrustFlags', 'has_key trusted ca usages')
54
55 EMPTY_TRUST_FLAGS = TrustFlags(False, None, None, None)
56
57 IPA_CA_TRUST_FLAGS = TrustFlags(
58 False, True, True, frozenset({
59 x509.EKU_SERVER_AUTH,
60 x509.EKU_CLIENT_AUTH,
61 x509.EKU_CODE_SIGNING,
62 x509.EKU_EMAIL_PROTECTION,
63 x509.EKU_PKINIT_CLIENT_AUTH,
64 x509.EKU_PKINIT_KDC,
65 }),
66 )
67
68 EXTERNAL_CA_TRUST_FLAGS = TrustFlags(
69 False, True, True, frozenset({x509.EKU_SERVER_AUTH}),
70 )
71
72 TRUSTED_PEER_TRUST_FLAGS = TrustFlags(
73 False, True, False, frozenset({x509.EKU_SERVER_AUTH}),
74 )
75
76
77 def nss_supports_dbm():
78 return bool(find_library("nssdbm3"))
79
80
81 def get_ca_nickname(realm, format=CA_NICKNAME_FMT):
82 return format % realm
83
84
85 def find_cert_from_txt(cert, start=0):
86 """
87 Given a cert blob (str) which may or may not contian leading and
88 trailing text, pull out just the certificate part. This will return
89 the FIRST cert in a stream of data.
90
91 :returns: a tuple (IPACertificate, last position in cert)
92 """
93 s = cert.find('-----BEGIN CERTIFICATE-----', start)
94 e = cert.find('-----END CERTIFICATE-----', s)
95 if e > 0:
96 e = e + 25
97
98 if s < 0 or e < 0:
99 raise RuntimeError("Unable to find certificate")
100
101 cert = x509.load_pem_x509_certificate(cert[s:e].encode('utf-8'))
102 return (cert, e)
103
104
105 def parse_trust_flags(trust_flags):
106 """
107 Convert certutil trust flags to TrustFlags object.
108 """
109 has_key = 'u' in trust_flags
110
111 if 'p' in trust_flags:
112 if 'C' in trust_flags or 'P' in trust_flags or 'T' in trust_flags:
113 raise ValueError("cannot be both trusted and not trusted")
114 return False, None, None
115 elif 'C' in trust_flags or 'T' in trust_flags:
116 if 'P' in trust_flags:
117 raise ValueError("cannot be both CA and not CA")
118 ca = True
119 elif 'P' in trust_flags:
120 ca = False
121 else:
122 return TrustFlags(has_key, None, None, frozenset())
123
124 trust_flags = trust_flags.split(',')
125 ext_key_usage = set()
126 for i, kp in enumerate((x509.EKU_SERVER_AUTH,
127 x509.EKU_EMAIL_PROTECTION,
128 x509.EKU_CODE_SIGNING)):
129 if 'C' in trust_flags[i] or 'P' in trust_flags[i]:
130 ext_key_usage.add(kp)
131 if 'T' in trust_flags[0]:
132 ext_key_usage.add(x509.EKU_CLIENT_AUTH)
133
134 return TrustFlags(has_key, True, ca, frozenset(ext_key_usage))
135
136
137 def unparse_trust_flags(trust_flags):
138 """
139 Convert TrustFlags object to certutil trust flags.
140 """
141 has_key, trusted, ca, ext_key_usage = trust_flags
142
143 if trusted is False:
144 if has_key:
145 return 'pu,pu,pu'
146 else:
147 return 'p,p,p'
148 elif trusted is None or ca is None:
149 if has_key:
150 return 'u,u,u'
151 else:
152 return ',,'
153 elif ext_key_usage is None:
154 if ca:
155 if has_key:
156 return 'CTu,Cu,Cu'
157 else:
158 return 'CT,C,C'
159 else:
160 if has_key:
161 return 'Pu,Pu,Pu'
162 else:
163 return 'P,P,P'
164
165 trust_flags = ['', '', '']
166 for i, kp in enumerate((x509.EKU_SERVER_AUTH,
167 x509.EKU_EMAIL_PROTECTION,
168 x509.EKU_CODE_SIGNING)):
169 if kp in ext_key_usage:
170 trust_flags[i] += ('C' if ca else 'P')
171 if ca and x509.EKU_CLIENT_AUTH in ext_key_usage:
172 trust_flags[0] += 'T'
173 if has_key:
174 for i in range(3):
175 trust_flags[i] += 'u'
176
177 trust_flags = ','.join(trust_flags)
178 return trust_flags
179
180
181 def verify_kdc_cert_validity(kdc_cert, ca_certs, realm):
182 """
183 Verifies the validity of a kdc_cert, ensuring it is trusted by
184 the ca_certs chain, has a PKINIT_KDC extended key usage support,
185 and verify it applies to the given realm.
186 """
187 with NamedTemporaryFile() as kdc_file, NamedTemporaryFile() as ca_file:
188 kdc_file.write(kdc_cert.public_bytes(x509.Encoding.PEM))
189 kdc_file.flush()
190 x509.write_certificate_list(ca_certs, ca_file.name)
191 ca_file.flush()
192
193 try:
194 ipautil.run(
195 [paths.OPENSSL, 'verify', '-CAfile', ca_file.name,
196 kdc_file.name],
197 capture_output=True)
198 except ipautil.CalledProcessError as e:
199 raise ValueError(e.output)
200
201 try:
202 eku = kdc_cert.extensions.get_extension_for_class(
203 cryptography.x509.ExtendedKeyUsage)
204 list(eku.value).index(
205 cryptography.x509.ObjectIdentifier(x509.EKU_PKINIT_KDC))
206 except (cryptography.x509.ExtensionNotFound,
207 ValueError):
208 raise ValueError("invalid for a KDC")
209
210 principal = str(Principal(['krbtgt', realm], realm))
211 gns = x509.process_othernames(kdc_cert.san_general_names)
212 for gn in gns:
213 if isinstance(gn, x509.KRB5PrincipalName) and gn.name == principal:
214 break
215 else:
216 raise ValueError("invalid for realm %s" % realm)
217
218
219 CERT_RE = re.compile(
220 r'^(?P<nick>.+?)\s+(?P<flags>\w*,\w*,\w*)\s*$'
221 )
222 KEY_RE = re.compile(
223 r'^<\s*(?P<slot>\d+)>'
224 r'\s+(?P<algo>\w+)'
225 r'\s+(?P<keyid>[0-9a-z]+)'
226 r'\s+(?P<nick>.*?)\s*$'
227 )
228
229
230 class Pkcs12ImportIncorrectPasswordError(RuntimeError):
231 """ Raised when import_pkcs12 fails because of a wrong password.
232 """
233
234
235 class Pkcs12ImportOpenError(RuntimeError):
236 """ Raised when import_pkcs12 fails trying to open the file.
237 """
238
239
240 class Pkcs12ImportUnknownError(RuntimeError):
241 """ Raised when import_pkcs12 fails because of an unknown error.
242 """
243
244
245 class NSSDatabase:
246 """A general-purpose wrapper around a NSS cert database
247
248 For permanent NSS databases, pass the cert DB directory to __init__
249
250 For temporary databases, do not pass nssdir, and call close() when done
251 to remove the DB. Alternatively, a NSSDatabase can be used as a
252 context manager that calls close() automatically.
253 """
254 # Traditionally, we used CertDB for our NSS DB operations, but that class
255 # got too tied to IPA server details, killing reusability.
256 # BaseCertDB is a class that knows nothing about IPA.
257 # Generic NSS DB code should be moved here.
258
259 def __init__(self, nssdir=None, dbtype='auto', token=None, pwd_file=None):
260 if nssdir is not None:
261 self.secdir = nssdir
262 self._is_temporary = False
263 if dbtype == "auto":
264 dbtype = self._detect_dbtype()
265
266 if dbtype == "dbm" and not nss_supports_dbm():
267 raise ValueError(
268 f"NSS is built without support of the legacy database(DBM) "
269 f"directory '{nssdir}'",
270 )
271
272 if nssdir is None:
273 self.secdir = tempfile.mkdtemp()
274 self._is_temporary = True
275
276 if pwd_file is None:
277 self.pwd_file = os.path.join(self.secdir, 'pwdfile.txt')
278 else:
279 self.pwd_file = pwd_file
280 self.dbtype = None
281 self.certdb = self.keydb = self.secmod = None
282 self.token = token
283 # files in actual db
284 self.filenames = ()
285 # all files that are handled by create_db(backup=True)
286 self.backup_filenames = ()
287 self._set_filenames(dbtype)
288
289 def _detect_dbtype(self):
290 if os.path.isfile(os.path.join(self.secdir, "cert9.db")):
291 return 'sql'
292 elif os.path.isfile(os.path.join(self.secdir, "cert8.db")):
293 return 'dbm'
294 else:
295 return 'auto'
296
297 def _set_filenames(self, dbtype):
298 self.dbtype = dbtype
299 dbmfiles = (
300 os.path.join(self.secdir, "cert8.db"),
301 os.path.join(self.secdir, "key3.db"),
302 os.path.join(self.secdir, "secmod.db")
303 )
304 sqlfiles = (
305 os.path.join(self.secdir, "cert9.db"),
306 os.path.join(self.secdir, "key4.db"),
307 os.path.join(self.secdir, "pkcs11.txt")
308 )
309 if dbtype == 'dbm':
310 self.certdb, self.keydb, self.secmod = dbmfiles
311 self.filenames = dbmfiles + (self.pwd_file,)
312 elif dbtype == 'sql':
313 self.certdb, self.keydb, self.secmod = sqlfiles
314 self.filenames = sqlfiles + (self.pwd_file,)
315 elif dbtype == 'auto':
316 self.certdb = self.keydb = self.secmod = None
317 self.filenames = None
318 else:
319 raise ValueError(dbtype)
320 self.backup_filenames = (
321 self.pwd_file,
322 ) + sqlfiles + dbmfiles
323
324 def close(self):
325 if self._is_temporary:
326 shutil.rmtree(self.secdir)
327
328 def __enter__(self):
329 return self
330
331 def __exit__(self, type, value, tb):
332 self.close()
333
334 def _check_db(self):
335 if self.filenames is None:
336 raise RuntimeError(
337 "NSSDB '{}' not initialized.".format(self.secdir)
338 )
339
340 def run_certutil(self, args, stdin=None, **kwargs):
341 self._check_db()
342 new_args = [
343 paths.CERTUTIL,
344 "-d", '{}:{}'.format(self.dbtype, self.secdir)
345 ]
346 new_args.extend(args)
347 if self.token:
348 new_args.extend(["-h", self.token])
349 new_args.extend(['-f', self.pwd_file])
350 # When certutil makes a request it creates a file in the cwd, make
351 # sure we are in a unique place when this happens.
352 return ipautil.run(new_args, stdin, cwd=self.secdir, **kwargs)
353
354 def run_pk12util(self, args, stdin=None, **kwargs):
355 self._check_db()
356 new_args = [
357 paths.PK12UTIL,
358 "-d", '{}:{}'.format(self.dbtype, self.secdir)
359 ]
360 new_args.extend(args)
361 return ipautil.run(new_args, stdin, **kwargs)
362
363 def exists(self):
364 """Check DB exists (all files are present)
365 """
366 if self.filenames is None:
367 return False
368 return all(os.path.isfile(filename) for filename in self.filenames)
369
370 def create_db(self, user=None, group=None, mode=None, backup=False):
371 """Create cert DB
372
373 :param user: User owner the secdir
374 :param group: Group owner of the secdir
375 :param mode: Mode of the secdir
376 :param backup: Backup the sedir files
377 """
378 if mode is not None:
379 dirmode = mode
380 filemode = mode & 0o666
381 pwdfilemode = mode & 0o660
382 else:
383 dirmode = 0o750
384 filemode = 0o640
385 pwdfilemode = 0o640
386
387 uid = -1
388 gid = -1
389 if user is not None:
390 uid = pwd.getpwnam(user).pw_uid
391 if group is not None:
392 gid = grp.getgrnam(group).gr_gid
393
394 if backup:
395 for filename in self.backup_filenames:
396 ipautil.backup_file(filename)
397
398 if not os.path.exists(self.secdir):
399 os.makedirs(self.secdir, dirmode)
400
401 if not os.path.exists(self.pwd_file):
402 # Create the password file for this db
403 with io.open(os.open(self.pwd_file,
404 os.O_CREAT | os.O_WRONLY,
405 pwdfilemode), 'w', closefd=True) as f:
406 f.write(ipautil.ipa_generate_password())
407 # flush and sync tempfile inode
408 f.flush()
409 os.fsync(f.fileno())
410
411 # In case dbtype is auto, let certutil decide which type of DB
412 # to create.
413 if self.dbtype == 'auto':
414 dbdir = self.secdir
415 else:
416 dbdir = '{}:{}'.format(self.dbtype, self.secdir)
417 args = [
418 paths.CERTUTIL,
419 '-d', dbdir,
420 '-N',
421 '-f', self.pwd_file,
422 # -@ in case it's an old db and it must be migrated
423 '-@', self.pwd_file,
424 ]
425 ipautil.run(args, stdin=None, cwd=self.secdir)
426 self._set_filenames(self._detect_dbtype())
427 if self.filenames is None:
428 # something went wrong...
429 raise ValueError(
430 "Failed to create NSSDB at '{}'".format(self.secdir)
431 )
432
433 # Finally fix up perms
434 os.chown(self.secdir, uid, gid)
435 os.chmod(self.secdir, dirmode)
436 tasks.restore_context(self.secdir, force=True)
437 for filename in self.filenames:
438 if os.path.exists(filename):
439 os.chown(filename, uid, gid)
440 if filename == self.pwd_file:
441 new_mode = pwdfilemode
442 else:
443 new_mode = filemode
444 os.chmod(filename, new_mode)
445 tasks.restore_context(filename, force=True)
446
447 def convert_db(self, rename_old=True):
448 """Convert DBM database format to SQL database format
449
450 **WARNING** **WARNING** **WARNING** **WARNING** **WARNING**
451
452 The caller must ensure that no other process or service is
453 accessing the NSSDB during migration. The DBM format does not support
454 multiple processes. If more than one process opens a DBM NSSDB for
455 writing, the database will become **irreparably corrupted**.
456
457 **WARNING** **WARNING** **WARNING** **WARNING** **WARNING**
458 """
459 if (self.dbtype == 'sql' or
460 os.path.isfile(os.path.join(self.secdir, "cert9.db"))):
461 raise ValueError(
462 'NSS DB {} has been migrated already.'.format(self.secdir)
463 )
464
465 # use certutil to migrate db to new format
466 # see https://bugzilla.mozilla.org/show_bug.cgi?id=1415912
467 # https://fedoraproject.org/wiki/Changes/NSSDefaultFileFormatSql
468 args = [
469 paths.CERTUTIL,
470 '-d', 'sql:{}'.format(self.secdir), '-N',
471 '-f', self.pwd_file, '-@', self.pwd_file
472 ]
473 ipautil.run(args, stdin=None, cwd=self.secdir)
474
475 # retain file ownership and permission, backup old files
476 migration = (
477 ('cert8.db', 'cert9.db'),
478 ('key3.db', 'key4.db'),
479 ('secmod.db', 'pkcs11.txt'),
480 )
481 for oldname, newname in migration:
482 oldname = os.path.join(self.secdir, oldname)
483 newname = os.path.join(self.secdir, newname)
484 oldstat = os.stat(oldname)
485 os.chmod(newname, stat.S_IMODE(oldstat.st_mode))
486 os.chown(newname, oldstat.st_uid, oldstat.st_gid)
487 tasks.restore_context(newname, force=True)
488
489 self._set_filenames('sql')
490 self.list_certs() # self-test
491
492 if rename_old:
493 for oldname, _ in migration: # pylint: disable=unused-variable
494 oldname = os.path.join(self.secdir, oldname)
495 os.rename(oldname, oldname + '.migrated')
496
497 def restore(self):
498 for filename in self.backup_filenames:
499 backup_path = filename + '.orig'
500 save_path = filename + '.ipasave'
501 try:
502 if os.path.exists(filename):
503 os.rename(filename, save_path)
504 if os.path.exists(backup_path):
505 os.rename(backup_path, filename)
506 except OSError as e:
507 logger.debug('%s', e)
508
509 def list_certs(self):
510 """Return nicknames and cert flags for all certs in the database
511
512 :return: List of (name, trust_flags) tuples
513 """
514 args = ["-L"]
515 result = self.run_certutil(args, capture_output=True)
516 certs = result.output.splitlines()
517
518 # FIXME, this relies on NSS never changing the formatting of certutil
519 certlist = []
520 for cert in certs:
521 match = CERT_RE.match(cert)
522 if match:
523 nickname = match.group('nick')
524 trust_flags = parse_trust_flags(match.group('flags'))
525 certlist.append((nickname, trust_flags))
526
527 return tuple(certlist)
528
529 def list_keys(self):
530 result = self.run_certutil(
531 ["-K"], raiseonerr=False, capture_output=True
532 )
533 if result.returncode == 255:
534 return ()
535 keylist = []
536 for line in result.output.splitlines():
537 mo = KEY_RE.match(line)
538 if mo is not None:
539 keylist.append((
540 int(mo.group('slot')),
541 mo.group('algo'),
542 mo.group('keyid'),
543 mo.group('nick'),
544 ))
545 return tuple(keylist)
546
547 def find_server_certs(self):
548 """Return nicknames and cert flags for server certs in the database
549
550 Server certs have an "u" character in the trust flags.
551
552 :return: List of (name, trust_flags) tuples
553 """
554 server_certs = []
555 for name, flags in self.list_certs():
556 if flags.has_key:
557 server_certs.append((name, flags))
558
559 return server_certs
560
561 def get_trust_chain(self, nickname):
562 """Return names of certs in a given cert's trust chain
563
564 The list starts with root ca, then first intermediate CA, second
565 intermediate, and so on.
566
567 :param nickname: Name of the cert
568 :return: List of certificate names
569 """
570 root_nicknames = []
571 result = self.run_certutil(
572 ["-O", "--simple-self-signed", "-n", nickname],
573 capture_output=True)
574 chain = result.output.splitlines()
575
576 for c in chain:
577 m = re.match(r'\s*"(.*)" \[.*', c)
578 if m:
579 root_nicknames.append(m.groups()[0])
580
581 return root_nicknames
582
583 def export_pkcs12(self, nickname, pkcs12_filename, pkcs12_passwd=None):
584 args = [
585 "-o", pkcs12_filename,
586 "-n", nickname,
587 "-k", self.pwd_file
588 ]
589 pkcs12_password_file = None
590 if pkcs12_passwd is not None:
591 pkcs12_password_file = ipautil.write_tmp_file(pkcs12_passwd + '\n')
592 args.extend(["-w", pkcs12_password_file.name])
593 try:
594 self.run_pk12util(args)
595 except ipautil.CalledProcessError as e:
596 if e.returncode == 17:
597 raise RuntimeError("incorrect password for pkcs#12 file %s" %
598 pkcs12_filename)
599 elif e.returncode == 10:
600 raise RuntimeError("Failed to open %s" % pkcs12_filename)
601 else:
602 raise RuntimeError("unknown error exporting pkcs#12 file %s" %
603 pkcs12_filename)
604 finally:
605 if pkcs12_password_file is not None:
606 pkcs12_password_file.close()
607
608 def import_pkcs12(self, pkcs12_filename, pkcs12_passwd=None):
609 args = [
610 "-i", pkcs12_filename,
611 "-k", self.pwd_file,
612 "-v"
613 ]
614 pkcs12_password_file = None
615 if pkcs12_passwd is not None:
616 pkcs12_password_file = ipautil.write_tmp_file(pkcs12_passwd + '\n')
617 args.extend(["-w", pkcs12_password_file.name])
618 try:
619 self.run_pk12util(args)
620 except ipautil.CalledProcessError as e:
621 if e.returncode in (17, 18):
622 raise Pkcs12ImportIncorrectPasswordError(
623 "incorrect password for pkcs#12 file %s" % pkcs12_filename)
624 elif e.returncode == 10:
625 raise Pkcs12ImportOpenError(
626 "Failed to open %s" % pkcs12_filename)
627 else:
628 raise Pkcs12ImportUnknownError(
629 "unknown error import pkcs#12 file %s" %
630 pkcs12_filename)
631 finally:
632 if pkcs12_password_file is not None:
633 pkcs12_password_file.close()
634
635 def import_files(self, files, import_keys=False, key_password=None,
636 key_nickname=None, trust_flags=EMPTY_TRUST_FLAGS):
637 """
638 Import certificates and a single private key from multiple files
639
640 The files may be in PEM and DER certificate, PKCS#7 certificate chain,
641 PKCS#8 and raw private key and PKCS#12 formats.
642
643 :param files: Names of files to import
644 :param import_keys: Whether to import private keys
645 :param key_password: Password to decrypt private keys
646 :param key_nickname: Nickname of the private key to import from PKCS#12
647 files
648 """
649 key_file = None
650 extracted_key = None
651 extracted_certs = []
652
653 for filename in files:
654 try:
655 with open(filename, 'rb') as f:
656 data = f.read()
657 except IOError as e:
658 raise RuntimeError(
659 "Failed to open %s: %s" % (filename, e.strerror))
660
661 # Try to parse the file as PEM file
662 matches = list(
663 re.finditer(
664 br'-----BEGIN (.+?)-----(.*?)-----END \1-----',
665 data, re.DOTALL
666 )
667 )
668 if matches:
669 loaded = False
670 for match in matches:
671 body = match.group()
672 label = match.group(1)
673 line = len(data[:match.start() + 1].splitlines())
674
675 if label in (b'CERTIFICATE', b'X509 CERTIFICATE',
676 b'X.509 CERTIFICATE'):
677 try:
678 cert = x509.load_pem_x509_certificate(body)
679 except ValueError as e:
680 if label != b'CERTIFICATE':
681 logger.warning(
682 "Skipping certificate in %s at line %s: "
683 "%s",
684 filename, line, e)
685 continue
686 logger.error('Failed to load certificate in %s '
687 'at line %s: %s',
688 filename, line, e)
689 else:
690 extracted_certs.append(cert)
691 loaded = True
692 continue
693
694 if label in (b'PKCS7', b'PKCS #7 SIGNED DATA',
695 b'CERTIFICATE'):
696 try:
697 certs = x509.pkcs7_to_certs(body)
698 except ipautil.CalledProcessError as e:
699 if label == b'CERTIFICATE':
700 logger.warning(
701 "Skipping certificate in %s at line %s: "
702 "%s",
703 filename, line, e)
704 else:
705 logger.warning(
706 "Skipping PKCS#7 in %s at line %s: %s",
707 filename, line, e)
708 continue
709 else:
710 extracted_certs.extend(certs)
711 loaded = True
712 continue
713
714 if label in (b'PRIVATE KEY', b'ENCRYPTED PRIVATE KEY',
715 b'RSA PRIVATE KEY', b'DSA PRIVATE KEY',
716 b'EC PRIVATE KEY'):
717 if not import_keys:
718 continue
719
720 if key_file:
721 raise RuntimeError(
722 "Can't load private key from both %s and %s" %
723 (key_file, filename))
724
725 # the args -v2 aes256 -v2prf hmacWithSHA256 are needed
726 # on OpenSSL 1.0.2 (fips mode). As soon as FreeIPA
727 # requires OpenSSL 1.1.0 we'll be able to drop them
728 args = [
729 paths.OPENSSL, 'pkcs8',
730 '-topk8',
731 '-v2', 'aes256', '-v2prf', 'hmacWithSHA256',
732 '-passout', 'file:' + self.pwd_file,
733 ]
734 if ((label != b'PRIVATE KEY' and key_password) or
735 label == b'ENCRYPTED PRIVATE KEY'):
736 key_pwdfile = ipautil.write_tmp_file(key_password)
737 args += [
738 '-passin', 'file:' + key_pwdfile.name,
739 ]
740 try:
741 result = ipautil.run(
742 args, stdin=body, capture_output=True)
743 except ipautil.CalledProcessError as e:
744 logger.warning(
745 "Skipping private key in %s at line %s: %s",
746 filename, line, e)
747 continue
748 else:
749 extracted_key = result.raw_output
750 key_file = filename
751 loaded = True
752 continue
753 if loaded:
754 continue
755 raise RuntimeError("Failed to load %s" % filename)
756
757 # Try to load the file as DER certificate
758 try:
759 cert = x509.load_der_x509_certificate(data)
760 except ValueError:
761 pass
762 else:
763 extracted_certs.append(cert)
764 continue
765
766 # Try to import the file as PKCS#12 file
767 if import_keys:
768 try:
769 self.import_pkcs12(filename, key_password)
770 except Pkcs12ImportUnknownError:
771 # the file may not be a PKCS#12 file,
772 # go to the generic error about unrecognized format
773 pass
774 except RuntimeError as e:
775 raise RuntimeError("Failed to load %s: %s" %
776 (filename, str(e)))
777 else:
778 if key_file:
779 raise RuntimeError(
780 "Can't load private key from both %s and %s" %
781 (key_file, filename))
782 key_file = filename
783
784 server_certs = self.find_server_certs()
785 if key_nickname:
786 for nickname, _trust_flags in server_certs:
787 if nickname == key_nickname:
788 break
789 else:
790 raise RuntimeError(
791 "Server certificate \"%s\" not found in %s" %
792 (key_nickname, filename))
793 else:
794 if len(server_certs) > 1:
795 raise RuntimeError(
796 "%s server certificates found in %s, "
797 "expecting only one" %
798 (len(server_certs), filename))
799
800 continue
801
802 # Supported formats were tried but none succeeded
803 raise RuntimeError("Failed to load %s: unrecognized format" %
804 filename)
805
806 if import_keys and not key_file:
807 raise RuntimeError(
808 "No server certificates found in %s" % (', '.join(files)))
809
810 for cert in extracted_certs:
811 nickname = str(DN(cert.subject))
812 self.add_cert(cert, nickname, trust_flags)
813
814 if extracted_key:
815 with tempfile.NamedTemporaryFile() as in_file, \
816 tempfile.NamedTemporaryFile() as out_file:
817 for cert in extracted_certs:
818 in_file.write(cert.public_bytes(x509.Encoding.PEM))
819 in_file.write(extracted_key)
820 in_file.flush()
821 out_password = ipautil.ipa_generate_password()
822 out_pwdfile = ipautil.write_tmp_file(out_password)
823 args = [
824 paths.OPENSSL, 'pkcs12',
825 '-export',
826 '-in', in_file.name,
827 '-out', out_file.name,
828 '-passin', 'file:' + self.pwd_file,
829 '-passout', 'file:' + out_pwdfile.name,
830 '-certpbe', 'aes-128-cbc',
831 '-keypbe', 'aes-128-cbc',
832 ]
833 try:
834 ipautil.run(args)
835 except ipautil.CalledProcessError as e:
836 raise RuntimeError(
837 "No matching certificate found for private key from "
838 "%s" % key_file)
839
840 self.import_pkcs12(out_file.name, out_password)
841
842 def trust_root_cert(self, root_nickname, trust_flags):
843 if root_nickname[:7] == "Builtin":
844 logger.debug(
845 "No need to add trust for built-in root CAs, skipping %s",
846 root_nickname)
847 else:
848 trust_flags = unparse_trust_flags(trust_flags)
849 try:
850 self.run_certutil(["-M", "-n", root_nickname,
851 "-t", trust_flags])
852 except ipautil.CalledProcessError:
853 raise RuntimeError(
854 "Setting trust on %s failed" % root_nickname)
855
856 def get_cert(self, nickname):
857 """
858 :param nickname: nickname of the certificate in the NSS database
859 :returns: string in Python2
860 bytes in Python3
861 """
862 args = ['-L', '-n', nickname, '-a']
863 try:
864 result = self.run_certutil(args, capture_output=True)
865 except ipautil.CalledProcessError:
866 raise RuntimeError("Failed to get %s" % nickname)
867 cert, _start = find_cert_from_txt(result.output, start=0)
868 return cert
869
870 def get_all_certs(self, nickname):
871 """
872 :param nickname: nickname of the certificate in the NSS database
873 :returns: list of bytes of all certificates for the nickname
874 """
875 args = ['-L', '-n', nickname, '-a']
876 try:
877 result = self.run_certutil(args, capture_output=True)
878 except ipautil.CalledProcessError:
879 raise RuntimeError("Failed to get %s" % nickname)
880 certs = []
881
882 st = 0
883 while True:
884 try:
885 cert, st = find_cert_from_txt(result.output, start=st)
886 except RuntimeError:
887 break
888 certs.append(cert)
889 return certs
890
891 def has_nickname(self, nickname):
892 try:
893 self.get_cert(nickname)
894 except RuntimeError:
895 # This might be error other than "nickname not found". Beware.
896 return False
897 else:
898 return True
899
900 def export_pem_cert(self, nickname, location):
901 """Export the given cert to PEM file in the given location"""
902 cert = self.get_cert(nickname)
903 with open(location, "wb") as fd:
904 fd.write(cert.public_bytes(x509.Encoding.PEM))
905 os.chmod(location, 0o444)
906
907 def import_pem_cert(self, nickname, flags, location):
908 """Import a cert form the given PEM file.
909
910 The file must contain exactly one certificate.
911 """
912 try:
913 with open(location) as fd:
914 certs = fd.read()
915 except IOError as e:
916 raise RuntimeError(
917 "Failed to open %s: %s" % (location, e.strerror)
918 )
919
920 cert, st = find_cert_from_txt(certs)
921 self.add_cert(cert, nickname, flags)
922
923 try:
924 find_cert_from_txt(certs, st)
925 except RuntimeError:
926 pass
927 else:
928 raise ValueError('%s contains more than one certificate' %
929 location)
930
931 def add_cert(self, cert, nick, flags):
932 flags = unparse_trust_flags(flags)
933 args = ["-A", "-n", nick, "-t", flags, '-a']
934 self.run_certutil(args, stdin=cert.public_bytes(x509.Encoding.PEM))
935
936 def delete_cert(self, nick):
937 self.run_certutil(["-D", "-n", nick])
938
939 def delete_key_only(self, nick):
940 """Delete the key with provided nick
941
942 This commands removes the key but leaves the cert in the DB.
943 """
944 keys = self.list_keys()
945 # keys is a list of tuple(slot, algo, keyid, nickname)
946 for (_slot, _algo, keyid, nickname) in keys:
947 if nickname == nick:
948 # Key is present in the DB, delete the key
949 self.run_certutil(["-F", "-k", keyid])
950 break
951
952 def delete_key_and_cert(self, nick):
953 """Delete a cert and its key from the DB"""
954 try:
955 self.run_certutil(["-F", "-n", nick])
956 except ipautil.CalledProcessError:
957 # Using -F -k instead of -F -n because the latter fails if
958 # the DB contains only the key
959 self.delete_key_only(nick)
960 # Check that cert was deleted
961 for (certname, _flags) in self.list_certs():
962 if certname == nick:
963 self.delete_cert(nick)
964
965 def _verify_cert_validity(self, cert):
966 """Common checks for cert validity
967 """
968 utcnow = datetime.datetime.now(tz=datetime.timezone.utc)
969 if cert.not_valid_before_utc > utcnow:
970 raise ValueError(
971 f"not valid before {cert.not_valid_before_utc} UTC is in "
972 "the future."
973 )
974 if cert.not_valid_after_utc < utcnow:
975 raise ValueError(
976 f"has expired {cert.not_valid_after_utc} UTC"
977 )
978 # make sure the cert does not expire during installation
979 if cert.not_valid_after_utc + datetime.timedelta(hours=1) < utcnow:
980 raise ValueError(
981 f"expires in less than one hour ({cert.not_valid_after_utc} "
982 "UTC)"
983 )
984
985 def verify_server_cert_validity(self, nickname, hostname):
986 """Verify a certificate is valid for a SSL server with given hostname
987
988 Raises a ValueError if the certificate is invalid.
989 """
990 cert = self.get_cert(nickname)
991 self._verify_cert_validity(cert)
992
993 try:
994 self.run_certutil(
995 [
996 '-V', # check validity of cert and attrs
997 '-n', nickname,
998 '-u', 'V', # usage; 'V' means "SSL server"
999 '-e', # check signature(s); this checks
1000 # key sizes, sig algorithm, etc.
1001 ],
1002 capture_output=True)
1003 except ipautil.CalledProcessError as e:
1004 # certutil output in case of error is
1005 # 'certutil: certificate is invalid: <ERROR_STRING>\n'
1006 raise ValueError(e.output)
1007
1008 try:
1009 cert.match_hostname(hostname)
1010 except ValueError:
1011 raise ValueError('invalid for server %s' % hostname)
1012
1013 def verify_ca_cert_validity(self, nickname, minpathlen=None):
1014 def verify_ca_cert(cert, nickname, minpathlen):
1015 self._verify_cert_validity(cert)
1016
1017 if not cert.subject:
1018 raise ValueError("has empty subject")
1019
1020 try:
1021 bc = cert.extensions.get_extension_for_class(
1022 cryptography.x509.BasicConstraints)
1023 except cryptography.x509.ExtensionNotFound:
1024 raise ValueError("missing basic constraints")
1025
1026 if not bc.value.ca:
1027 raise ValueError("not a CA certificate")
1028 if minpathlen is not None:
1029 # path_length is None means no limitation
1030 pl = bc.value.path_length
1031 if pl is not None and pl < minpathlen:
1032 raise ValueError(
1033 "basic contraint pathlen {}, "
1034 "must be at least {}".format(
1035 pl, minpathlen
1036 )
1037 )
1038
1039 try:
1040 ski = cert.extensions.get_extension_for_class(
1041 cryptography.x509.SubjectKeyIdentifier)
1042 except cryptography.x509.ExtensionNotFound:
1043 raise ValueError("missing subject key identifier extension")
1044 else:
1045 if len(ski.value.digest) == 0:
1046 raise ValueError("subject key identifier must not be empty")
1047
1048 try:
1049 self.run_certutil(
1050 [
1051 '-V', # check validity of cert and attrs
1052 '-n', nickname,
1053 '-u', 'L', # usage; 'L' means "SSL CA"
1054 '-e', # check signature(s); this checks
1055 # key sizes, sig algorithm, etc.
1056 ],
1057 capture_output=True)
1058 except ipautil.CalledProcessError as e:
1059 # certutil output in case of error is
1060 # 'certutil: certificate is invalid: <ERROR_STRING>\n'
1061 raise ValueError(e.output)
1062
1063 certlist = self.get_all_certs(nickname)
1064 for cert in certlist:
1065 verify_ca_cert(cert, nickname, minpathlen)
1066
1067 def verify_kdc_cert_validity(self, nickname, realm):
1068 nicknames = self.get_trust_chain(nickname)
1069 certs = [self.get_cert(nickname) for nickname in nicknames]
1070
1071 verify_kdc_cert_validity(certs[-1], certs[:-1], realm)