/
cert.py
1729 lines (1498 loc) · 61.4 KB
/
cert.py
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Authors:
# Andrew Wnuk <awnuk@redhat.com>
# Jason Gerard DeRose <jderose@redhat.com>
# John Dennis <jdennis@redhat.com>
#
# Copyright (C) 2009 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base64
import collections
import datetime
import logging
from operator import attrgetter
import cryptography.x509
from cryptography.hazmat.primitives import hashes, serialization
import six
from ipalib import Command, Str, Int, Flag
from ipalib import api
from ipalib import errors, messages
from ipalib import x509
from ipalib import ngettext
from ipalib.constants import IPA_CA_CN
from ipalib.crud import Create, PKQuery, Retrieve, Search
from ipalib.frontend import Method, Object
from ipalib.parameters import (
Bytes, Certificate, CertificateSigningRequest, DateTime, DNParam,
DNSNameParam, Principal
)
from ipalib.plugable import Registry
from .virtual import VirtualCommand
from .baseldap import pkey_to_value
from .certprofile import validate_profile_id
from ipalib.text import _
from ipalib.request import context
from ipalib import output
from ipapython import kerberos
from ipapython.dn import DN
from ipaserver.plugins.service import normalize_principal, validate_realm
from ipaserver.masters import ENABLED_SERVICE, CONFIGURED_SERVICE
try:
import pyhbac
except ImportError:
raise errors.SkipPluginModule(reason=_('pyhbac is not installed.'))
if six.PY3:
unicode = str
__doc__ = _("""
IPA certificate operations
""") + _("""
Implements a set of commands for managing server SSL certificates.
""") + _("""
Certificate requests exist in the form of a Certificate Signing Request (CSR)
in PEM format.
""") + _("""
The dogtag CA uses just the CN value of the CSR and forces the rest of the
subject to values configured in the server.
""") + _("""
A certificate is stored with a service principal and a service principal
needs a host.
""") + _("""
In order to request a certificate:
""") + _("""
* The host must exist
* The service must exist (or you use the --add option to automatically add it)
""") + _("""
SEARCHING:
""") + _("""
Certificates may be searched on by certificate subject, serial number,
revocation reason, validity dates and the issued date.
""") + _("""
When searching on dates the _from date does a >= search and the _to date
does a <= search. When combined these are done as an AND.
""") + _("""
Dates are treated as GMT to match the dates in the certificates.
""") + _("""
The date format is YYYY-mm-dd.
""") + _("""
EXAMPLES:
""") + _("""
Request a new certificate and add the principal:
ipa cert-request --add --principal=HTTP/lion.example.com example.csr
""") + _("""
Retrieve an existing certificate:
ipa cert-show 1032
""") + _("""
Revoke a certificate (see RFC 5280 for reason details):
ipa cert-revoke --revocation-reason=6 1032
""") + _("""
Remove a certificate from revocation hold status:
ipa cert-remove-hold 1032
""") + _("""
Check the status of a signing request:
ipa cert-status 10
""") + _("""
Search for certificates by hostname:
ipa cert-find --subject=ipaserver.example.com
""") + _("""
Search for revoked certificates by reason:
ipa cert-find --revocation-reason=5
""") + _("""
Search for certificates based on issuance date
ipa cert-find --issuedon-from=2013-02-01 --issuedon-to=2013-02-07
""") + _("""
Search for certificates owned by a specific user:
ipa cert-find --user=user
""") + _("""
Examine a certificate:
ipa cert-find --file=cert.pem --all
""") + _("""
Verify that a certificate is owned by a specific user:
ipa cert-find --file=cert.pem --user=user
""") + _("""
IPA currently immediately issues (or declines) all certificate requests so
the status of a request is not normally useful. This is for future use
or the case where a CA does not immediately issue a certificate.
""") + _("""
The following revocation reasons are supported:
""") + _(""" * 0 - unspecified
""") + _(""" * 1 - keyCompromise
""") + _(""" * 2 - cACompromise
""") + _(""" * 3 - affiliationChanged
""") + _(""" * 4 - superseded
""") + _(""" * 5 - cessationOfOperation
""") + _(""" * 6 - certificateHold
""") + _(""" * 8 - removeFromCRL
""") + _(""" * 9 - privilegeWithdrawn
""") + _(""" * 10 - aACompromise
""") + _("""
Note that reason code 7 is not used. See RFC 5280 for more details:
""") + _("""
http://www.ietf.org/rfc/rfc5280.txt
""")
logger = logging.getLogger(__name__)
USER, HOST, KRBTGT, SERVICE = range(4)
register = Registry()
PKIDATE_FORMAT = '%Y-%m-%d'
def _acl_make_request(principal_type, principal, ca_id, profile_id):
"""Construct HBAC request for the given principal, CA and profile"""
req = pyhbac.HbacRequest()
req.targethost.name = ca_id
req.service.name = profile_id
if principal_type == 'user':
req.user.name = principal.username
elif principal_type == 'host':
req.user.name = principal.hostname
elif principal_type == 'service':
req.user.name = unicode(principal)
groups = []
if principal_type == 'user':
user_obj = api.Command.user_show(
str(principal.username))['result']
groups = user_obj.get('memberof_group', [])
groups += user_obj.get('memberofindirect_group', [])
elif principal_type == 'host':
host_obj = api.Command.host_show(
str(principal.hostname))['result']
groups = host_obj.get('memberof_hostgroup', [])
groups += host_obj.get('memberofindirect_hostgroup', [])
req.user.groups = sorted(set(groups))
return req
def _acl_make_rule(principal_type, obj):
"""Turn CA ACL object into HBAC rule.
``principal_type``
String in {'user', 'host', 'service'}
"""
rule = pyhbac.HbacRule(obj['cn'][0])
rule.enabled = obj['ipaenabledflag'][0]
rule.srchosts.category = {pyhbac.HBAC_CATEGORY_ALL}
# add CA(s)
if 'ipacacategory' in obj and obj['ipacacategory'][0].lower() == 'all':
rule.targethosts.category = {pyhbac.HBAC_CATEGORY_ALL}
else:
# For compatibility with pre-lightweight-CAs CA ACLs,
# no CA members implies the host authority (only)
rule.targethosts.names = obj.get('ipamemberca_ca', [IPA_CA_CN])
# add profiles
if ('ipacertprofilecategory' in obj
and obj['ipacertprofilecategory'][0].lower() == 'all'):
rule.services.category = {pyhbac.HBAC_CATEGORY_ALL}
else:
attr = 'ipamembercertprofile_certprofile'
rule.services.names = obj.get(attr, [])
# add principals and principal's groups
category_attr = '{}category'.format(principal_type)
if category_attr in obj and obj[category_attr][0].lower() == 'all':
rule.users.category = {pyhbac.HBAC_CATEGORY_ALL}
else:
if principal_type == 'user':
rule.users.names = obj.get('memberuser_user', [])
rule.users.groups = obj.get('memberuser_group', [])
elif principal_type == 'host':
rule.users.names = obj.get('memberhost_host', [])
rule.users.groups = obj.get('memberhost_hostgroup', [])
elif principal_type == 'service':
rule.users.names = [
unicode(principal)
for principal in obj.get('memberservice_service', [])
]
return rule
def acl_evaluate(principal, ca_id, profile_id):
if principal.is_user:
principal_type = 'user'
elif principal.is_host:
principal_type = 'host'
else:
principal_type = 'service'
req = _acl_make_request(principal_type, principal, ca_id, profile_id)
acls = api.Command.caacl_find(no_members=False)['result']
rules = [_acl_make_rule(principal_type, obj) for obj in acls]
return req.evaluate(rules) == pyhbac.HBAC_EVAL_ALLOW
def normalize_pkidate(value):
return datetime.datetime.strptime(value, PKIDATE_FORMAT)
def convert_pkidatetime(value):
value = datetime.datetime.fromtimestamp(int(value) // 1000)
return x509.format_datetime(value)
def normalize_serial_number(num):
"""
Convert a SN given in decimal or hexadecimal.
Returns the number or None if conversion fails.
"""
# plain decimal or hexa with radix prefix
try:
num = int(num, 0)
except ValueError:
try:
# hexa without prefix
num = int(num, 16)
except ValueError:
pass
return unicode(num)
def ca_enabled_check(_api):
if not _api.Command.ca_is_enabled()['result']:
raise errors.NotFound(reason=_('CA is not configured'))
def caacl_check(principal, ca, profile_id):
if not acl_evaluate(principal, ca, profile_id):
raise errors.ACIError(info=_(
"Principal '%(principal)s' "
"is not permitted to use CA '%(ca)s' "
"with profile '%(profile_id)s' for certificate issuance."
) % dict(
principal=unicode(principal),
ca=ca,
profile_id=profile_id
)
)
def ca_kdc_check(api_instance, hostname):
master_dn = api_instance.Object.server.get_dn(unicode(hostname))
kdc_dn = DN(('cn', 'KDC'), master_dn)
try:
kdc_entry = api_instance.Backend.ldap2.get_entry(
kdc_dn, ['ipaConfigString'])
wanted = {ENABLED_SERVICE, CONFIGURED_SERVICE}
if wanted.intersection(kdc_entry['ipaConfigString']):
raise errors.NotFound(
reason=_("enabledService/configuredService not in "
"ipaConfigString kdc entry"))
except errors.NotFound:
raise errors.ACIError(
info=_("Host '%(hostname)s' is not an active KDC")
% dict(hostname=hostname))
def bind_principal_can_manage_cert(cert):
"""Check that the bind principal can manage the given cert.
``cert``
A python-cryptography ``Certificate`` object.
"""
bind_principal = kerberos.Principal(getattr(context, 'principal'))
if not bind_principal.is_host:
return False
hostname = bind_principal.hostname
# Verify that hostname matches subject of cert.
# We check the "most-specific" CN value.
cns = cert.subject.get_attributes_for_oid(
cryptography.x509.oid.NameOID.COMMON_NAME)
if len(cns) == 0:
return False # no CN in subject
else:
return hostname == cns[-1].value
class BaseCertObject(Object):
takes_params = (
Str(
'cacn?',
cli_name='ca',
default=IPA_CA_CN,
autofill=True,
label=_('Issuing CA'),
doc=_('Name of issuing CA'),
flags={'no_create', 'no_update', 'no_search'},
),
Certificate(
'certificate',
label=_("Certificate"),
doc=_("Base-64 encoded certificate."),
flags={'no_create', 'no_update', 'no_search'},
),
Bytes(
'certificate_chain*',
label=_("Certificate chain"),
doc=_("X.509 certificate chain"),
flags={'no_create', 'no_update', 'no_search'},
),
DNParam(
'subject',
label=_('Subject'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_rfc822name*',
label=_('Subject email address'),
flags={'no_create', 'no_update', 'no_search'},
),
DNSNameParam(
'san_dnsname*',
label=_('Subject DNS name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_x400address*',
label=_('Subject X.400 address'),
flags={'no_create', 'no_update', 'no_search'},
),
DNParam(
'san_directoryname*',
label=_('Subject directory name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_edipartyname*',
label=_('Subject EDI Party name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_uri*',
label=_('Subject URI'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_ipaddress*',
label=_('Subject IP Address'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_oid*',
label=_('Subject OID'),
flags={'no_create', 'no_update', 'no_search'},
),
Principal(
'san_other_upn*',
label=_('Subject UPN'),
flags={'no_create', 'no_update', 'no_search'},
),
Principal(
'san_other_kpn*',
label=_('Subject Kerberos principal name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_other*',
label=_('Subject Other Name'),
flags={'no_create', 'no_update', 'no_search'},
),
DNParam(
'issuer',
label=_('Issuer'),
doc=_('Issuer DN'),
flags={'no_create', 'no_update', 'no_search'},
),
DateTime(
'valid_not_before',
label=_('Not Before'),
flags={'no_create', 'no_update', 'no_search'},
),
DateTime(
'valid_not_after',
label=_('Not After'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'sha1_fingerprint',
label=_('Fingerprint (SHA1)'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'sha256_fingerprint',
label=_('Fingerprint (SHA256)'),
flags={'no_create', 'no_update', 'no_search'},
),
Int(
'serial_number',
label=_('Serial number'),
doc=_('Serial number in decimal or if prefixed with 0x in hexadecimal'),
normalizer=normalize_serial_number,
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'serial_number_hex',
label=_('Serial number (hex)'),
flags={'no_create', 'no_update', 'no_search'},
),
)
def _parse(self, obj, full=True):
"""Extract certificate-specific data into a result object.
``obj``
Result object containing certificate, into which extracted
data will be inserted.
``full``
Whether to include all fields, or only the ones we guess
people want to see most of the time. Also add
recognised otherNames to the generic ``san_other``
attribute when ``True`` in addition to the specialised
attribute.
Raise ``ValueError`` if the certificate is malformed.
(Note: only the main certificate structure and Subject Alt
Name extension are examined.)
"""
if 'certificate' in obj:
cert = x509.load_der_x509_certificate(
base64.b64decode(obj['certificate']))
obj['subject'] = DN(cert.subject)
obj['issuer'] = DN(cert.issuer)
obj['serial_number'] = cert.serial_number
obj['valid_not_before'] = x509.format_datetime(
cert.not_valid_before)
obj['valid_not_after'] = x509.format_datetime(
cert.not_valid_after)
if full:
obj['sha1_fingerprint'] = x509.to_hex_with_colons(
cert.fingerprint(hashes.SHA1()))
obj['sha256_fingerprint'] = x509.to_hex_with_colons(
cert.fingerprint(hashes.SHA256()))
general_names = x509.process_othernames(
cert.san_general_names)
for gn in general_names:
try:
self._add_san_attribute(obj, full, gn)
except Exception:
# Invalid GeneralName (i.e. not a valid X.509 cert);
# don't fail but log something about it
logger.warning(
"Encountered bad GeneralName; skipping", exc_info=True)
serial_number = obj.get('serial_number')
if serial_number is not None:
obj['serial_number_hex'] = u'0x%X' % serial_number
def _add_san_attribute(self, obj, full, gn):
name_type_map = {
cryptography.x509.RFC822Name:
('san_rfc822name', attrgetter('value')),
cryptography.x509.DNSName: ('san_dnsname', attrgetter('value')),
# cryptography.x509.???: 'san_x400address',
cryptography.x509.DirectoryName:
('san_directoryname', lambda x: DN(x.value)),
# cryptography.x509.???: 'san_edipartyname',
cryptography.x509.UniformResourceIdentifier:
('san_uri', attrgetter('value')),
cryptography.x509.IPAddress:
('san_ipaddress', attrgetter('value')),
cryptography.x509.RegisteredID:
('san_oid', attrgetter('value.dotted_string')),
cryptography.x509.OtherName: ('san_other', _format_othername),
x509.UPN: ('san_other_upn', attrgetter('name')),
x509.KRB5PrincipalName: ('san_other_kpn', attrgetter('name')),
}
default_attrs = {
'san_rfc822name', 'san_dnsname', 'san_other_upn', 'san_other_kpn',
}
if type(gn) not in name_type_map:
return
attr_name, format_name = name_type_map[type(gn)]
if full or attr_name in default_attrs:
attr_value = self.params[attr_name].type(format_name(gn))
obj.setdefault(attr_name, []).append(attr_value)
if full and attr_name.startswith('san_other_'):
# also include known otherName in generic otherName attribute
attr_value = self.params['san_other'].type(_format_othername(gn))
obj.setdefault('san_other', []).append(attr_value)
def _format_othername(on):
"""Format a python-cryptography OtherName for display."""
return u'{}:{}'.format(
on.type_id.dotted_string,
base64.b64encode(on.value).decode('ascii')
)
class BaseCertMethod(Method):
def get_options(self):
yield self.obj.params['cacn'].clone(query=True)
for option in super(BaseCertMethod, self).get_options():
yield option
@register()
class certreq(BaseCertObject):
takes_params = BaseCertObject.takes_params + (
Str(
'request_type',
default=u'pkcs10',
autofill=True,
flags={'no_option', 'no_update', 'no_update', 'no_search'},
),
Str(
'profile_id?', validate_profile_id,
label=_("Profile ID"),
doc=_("Certificate Profile to use"),
flags={'no_update', 'no_update', 'no_search'},
),
Str(
'cert_request_status',
label=_('Request status'),
flags={'no_create', 'no_update', 'no_search'},
),
Int(
'request_id',
label=_('Request id'),
primary_key=True,
flags={'no_create', 'no_update', 'no_search', 'no_output'},
),
)
_chain_flag = Flag(
'chain',
default=False,
doc=_('Include certificate chain in output'),
)
@register()
class cert_request(Create, BaseCertMethod, VirtualCommand):
__doc__ = _('Submit a certificate signing request.')
obj_name = 'certreq'
attr_name = 'request'
takes_args = (
CertificateSigningRequest(
'csr',
label=_('CSR'),
cli_name='csr_file',
),
)
operation="request certificate"
takes_options = (
Principal(
'principal',
validate_realm,
label=_('Principal'),
doc=_('Principal for this certificate (e.g. HTTP/test.example.com)'),
normalizer=normalize_principal
),
Flag(
'add',
doc=_(
"automatically add the principal if it doesn't exist "
"(service principals only)"),
),
_chain_flag,
)
def get_args(self):
# FIXME: the 'no_create' flag is ignored for positional arguments
for arg in super(cert_request, self).get_args():
if arg.name == 'request_id':
continue
yield arg
def execute(self, csr, all=False, raw=False, chain=False, **kw):
ca_enabled_check(self.api)
ldap = self.api.Backend.ldap2
realm = unicode(self.api.env.realm)
add = kw.get('add')
request_type = kw.get('request_type')
profile_id = kw.get('profile_id', self.Backend.ra.DEFAULT_PROFILE)
# Check that requested authority exists (done before CA ACL
# enforcement so that user gets better error message if
# referencing nonexistant CA) and look up authority ID.
#
ca = kw['cacn']
ca_obj = api.Command.ca_show(ca, all=all, chain=chain)['result']
ca_id = ca_obj['ipacaid'][0]
"""
Access control is partially handled by the ACI titled
'Hosts can modify service userCertificate'. This is for the case
where a machine binds using a host/ prinicpal. It can only do the
request if the target hostname is in the managedBy attribute which
is managed using the add/del member commands.
Binding with a user principal one needs to be in the request_certs
taskgroup (directly or indirectly via role membership).
"""
principal_arg = kw.get('principal')
if principal_to_principal_type(principal_arg) == KRBTGT:
principal_obj = None
principal = principal_arg
# Allow krbtgt to use only the KDC certprofile
if profile_id != self.Backend.ra.KDC_PROFILE:
raise errors.ACIError(
info=_("krbtgt certs can use only the %s profile") % (
self.Backend.ra.KDC_PROFILE))
# Allow only our own realm krbtgt for now; no trusted realms.
if principal != kerberos.Principal((u'krbtgt', realm),
realm=realm):
raise errors.NotFound("Not our realm's krbtgt")
else:
principal_obj = self.lookup_or_add_principal(principal_arg, add)
if 'krbcanonicalname' in principal_obj:
principal = principal_obj['krbcanonicalname'][0]
else:
principal = principal_obj['krbprincipalname'][0]
principal_string = unicode(principal)
principal_type = principal_to_principal_type(principal)
bind_principal = kerberos.Principal(getattr(context, 'principal'))
bind_principal_string = unicode(bind_principal)
bind_principal_type = principal_to_principal_type(bind_principal)
if (bind_principal_string != principal_string and
bind_principal_type != HOST):
# Can the bound principal request certs for another principal?
self.check_access()
try:
self.check_access("request certificate ignore caacl")
bypass_caacl = True
except errors.ACIError:
bypass_caacl = False
if not bypass_caacl:
if principal_type == KRBTGT:
ca_kdc_check(self.api, bind_principal.hostname)
else:
caacl_check(principal, ca, profile_id)
try:
ext_san = csr.extensions.get_extension_for_oid(
cryptography.x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
except cryptography.x509.extensions.ExtensionNotFound:
ext_san = None
# Ensure that the DN in the CSR matches the principal
#
# We only look at the "most specific" CN value
cns = csr.subject.get_attributes_for_oid(
cryptography.x509.oid.NameOID.COMMON_NAME)
if len(cns) == 0:
raise errors.ValidationError(name='csr',
error=_("No Common Name was found in subject of request."))
cn = cns[-1].value # "most specific" is end of list
if principal_type in (SERVICE, HOST):
if not _dns_name_matches_principal(cn, principal, principal_obj):
raise errors.ValidationError(
name='csr',
error=_(
"hostname in subject of request '%(cn)s' does not "
"match name or aliases of principal '%(principal)s'"
) % dict(cn=cn, principal=principal))
elif principal_type == KRBTGT and not bypass_caacl:
if cn.lower() != bind_principal.hostname.lower():
raise errors.ACIError(
info=_("hostname in subject of request '%(cn)s' "
"does not match principal hostname "
"'%(hostname)s'") % dict(
cn=cn, hostname=bind_principal.hostname))
elif principal_type == USER:
# check user name
if cn != principal.username:
raise errors.ValidationError(
name='csr',
error=_("DN commonName does not match user's login")
)
# check email address
#
# fail if any email addr from DN does not appear in ldap entry
email_addrs = csr.subject.get_attributes_for_oid(
cryptography.x509.oid.NameOID.EMAIL_ADDRESS)
csr_emails = [attr.value for attr in email_addrs]
if not _emails_are_valid(csr_emails,
principal_obj.get('mail', [])):
raise errors.ValidationError(
name='csr',
error=_(
"DN emailAddress does not match "
"any of user's email addresses")
)
if principal_type != KRBTGT:
# We got this far so the principal entry exists, can we write it?
dn = principal_obj.dn
if not ldap.can_write(dn, "usercertificate"):
raise errors.ACIError(
info=_("Insufficient 'write' privilege to the "
"'userCertificate' attribute of entry '%s'.") % dn)
# Validate the subject alt name, if any
generalnames = []
if ext_san is not None:
generalnames = x509.process_othernames(ext_san.value)
for gn in generalnames:
if isinstance(gn, cryptography.x509.general_name.DNSName):
if principal.is_user:
raise errors.ValidationError(
name='csr',
error=_(
"subject alt name type %s is forbidden "
"for user principals") % "DNSName"
)
name = gn.value
if _dns_name_matches_principal(name, principal, principal_obj):
continue # nothing more to check for this alt name
# no match yet; check for an alternative principal with
# same realm and service type as subject principal.
components = list(principal.components)
components[-1] = name
alt_principal = kerberos.Principal(components, principal.realm)
alt_principal_obj = None
try:
if principal_type == HOST:
alt_principal_obj = api.Command['host_show'](
name, all=True)
elif principal_type == KRBTGT:
alt_principal = kerberos.Principal(
(u'host', name), principal.realm)
elif principal_type == SERVICE:
alt_principal_obj = api.Command['service_show'](
alt_principal, all=True)
except errors.NotFound:
# We don't want to issue any certificates referencing
# machines we don't know about. Nothing is stored in this
# host record related to this certificate.
raise errors.NotFound(reason=_('The service principal for '
'subject alt name %s in certificate request does not '
'exist') % name)
if alt_principal_obj is not None:
# we found an alternative principal;
# now check write access and caacl
altdn = alt_principal_obj['result']['dn']
if not ldap.can_write(altdn, "usercertificate"):
raise errors.ACIError(info=_(
"Insufficient privilege to create a certificate "
"with subject alt name '%s'.") % name)
if not bypass_caacl:
if principal_type == KRBTGT:
ca_kdc_check(ldap, alt_principal.hostname)
else:
caacl_check(alt_principal, ca, profile_id)
elif isinstance(gn, (x509.KRB5PrincipalName, x509.UPN)):
if principal_type == KRBTGT:
principal_obj = dict()
principal_obj['krbprincipalname'] = [
kerberos.Principal((u'krbtgt', realm), realm)]
if not _principal_name_matches_principal(
gn.name, principal_obj):
raise errors.ValidationError(
name='csr',
error=_(
"Principal '%s' in subject alt name does not "
"match requested principal") % gn.name)
elif isinstance(gn, cryptography.x509.general_name.RFC822Name):
if principal_type == USER:
if not _emails_are_valid([gn.value],
principal_obj.get('mail', [])):
raise errors.ValidationError(
name='csr',
error=_(
"RFC822Name does not match "
"any of user's email addresses")
)
else:
raise errors.ValidationError(
name='csr',
error=_(
"subject alt name type %s is forbidden "
"for non-user principals") % "RFC822Name"
)
else:
raise errors.ACIError(
info=_("Subject alt name type %s is forbidden")
% type(gn).__name__)
# Request the certificate
try:
# re-serialise to PEM, in case the user-supplied data has
# extraneous material that will cause Dogtag to freak out
# keep it as string not bytes, it is required later
csr_pem = csr.public_bytes(
serialization.Encoding.PEM).decode('utf-8')
result = self.Backend.ra.request_certificate(
csr_pem, profile_id, ca_id, request_type=request_type)
except errors.HTTPRequestError as e:
if e.status == 409: # pylint: disable=no-member
raise errors.CertificateOperationError(
error=_("CA '%s' is disabled") % ca)
else:
raise e
if not raw:
try:
self.obj._parse(result, all)
except ValueError as e:
self.add_message(
messages.CertificateInvalid(
subject=principal,
reason=e,
)
)
result['request_id'] = int(result['request_id'])
result['cacn'] = ca_obj['cn'][0]
# Success? Then add it to the principal's entry
# (unless the profile tells us not to)
profile = api.Command['certprofile_show'](profile_id)
store = profile['result']['ipacertprofilestoreissued'][0] == 'TRUE'
if store and 'certificate' in result:
cert = result.get('certificate')
kwargs = dict(addattr=u'usercertificate={}'.format(cert))
# note: we call different commands for the different
# principal types because handling of 'userCertificate'
# vs. 'userCertificate;binary' varies by plugin.
if principal_type == SERVICE:
api.Command['service_mod'](principal_string, **kwargs)
elif principal_type == HOST:
api.Command['host_mod'](principal.hostname, **kwargs)
elif principal_type == USER:
api.Command['user_mod'](principal.username, **kwargs)
elif principal_type == KRBTGT:
logger.error("Profiles used to store cert should't be "
"used for krbtgt certificates")
if 'certificate_chain' in ca_obj:
cert = x509.load_der_x509_certificate(
base64.b64decode(result['certificate']))
cert = cert.public_bytes(serialization.Encoding.DER)
result['certificate_chain'] = [cert] + ca_obj['certificate_chain']
return dict(
result=result,
value=pkey_to_value(int(result['request_id']), kw),
)
def lookup_principal(self, principal):
"""
Look up a principal's account. Only works for users, hosts, services.
"""
return self.api.Backend.ldap2.find_entry_by_attr(
'krbprincipalname', principal, 'krbprincipalaux',
base_dn=DN(self.api.env.container_accounts, self.api.env.basedn)
)
def lookup_or_add_principal(self, principal, add):
"""
Look up a principal or add it if it does not exist.
Only works for users, hosts, services. krbtgt must be
handled separately.
Only service principals get added, and only when ``add`` is
``True``. If ``add`` is requested for a nonexistant user or
host, raise ``OperationNotSupportedForPrincipalTypes``.
:param principal: ``kerberos.Principal`` to look up
:param add: whether to add the principal if not found; bool
:return: an ``LDAPEntry``
"""
try:
return self.lookup_principal(principal)
except errors.NotFound:
if add:
if principal.is_service and not principal.is_host:
self.api.Command.service_add(
str(principal), all=True, force=True)
return self.lookup_principal(principal) # we want an LDAPEntry
else:
if principal.is_user:
princtype_str = _('user')
else:
princtype_str = _('host')
raise errors.OperationNotSupportedForPrincipalType(
operation=_("'add' option"),
principal_type=princtype_str)
else:
raise errors.NotFound(
reason=_("The principal for this request doesn't exist."))
def _emails_are_valid(csr_emails, principal_emails):
"""
Checks if any email address from certificate request does not
appear in ldap entry, comparing the domain part case-insensitively.
"""
def lower_domain(email):
email_splitted = email.split('@', 1)
if len(email_splitted) > 1:
email_splitted[1] = email_splitted[1].lower()
return '@'.join(email_splitted)
principal_emails_lower = set(map(lower_domain, principal_emails))
csr_emails_lower = set(map(lower_domain, csr_emails))
return csr_emails_lower.issubset(principal_emails_lower)
def principal_to_principal_type(principal):
if principal.is_user:
return USER
elif principal.is_host:
return HOST
elif principal.service_name == 'krbtgt':
return KRBTGT
else: