File: test_external_ca.py

package info (click to toggle)
freeipa 4.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 367,240 kB
  • sloc: javascript: 562,763; python: 310,289; ansic: 49,809; sh: 7,176; makefile: 2,589; xml: 343; sed: 16
file content (1015 lines) | stat: -rw-r--r-- 38,785 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
#
# Copyright (C) 2017  FreeIPA Contributors see COPYING for license
#
#
# 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/>.

from __future__ import absolute_import

import os
import re
import time

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.x509.oid import ObjectIdentifier, NameOID
from cryptography.hazmat.primitives import hashes, serialization

from ipatests.pytest_ipa.integration import tasks
from ipatests.test_integration.base import IntegrationTest
from ipalib import x509 as ipa_x509
from ipaplatform.paths import paths
from ipapython.dn import DN

from itertools import chain, repeat
from ipatests.create_external_ca import ExternalCA, ISSUER_CN

IPA_CA = 'ipa_ca.crt'
ROOT_CA = 'root_ca.crt'

# string to identify PKI restart in the journal
PKI_START_STR = 'Started pki_tomcatd'


def check_CA_flag(host, nssdb=paths.PKI_TOMCAT_ALIAS_DIR,
                  cn=ISSUER_CN):
    """
    Check if external CA (by default 'example.test' in our test env) has
    CA flag in nssdb.
    """
    result = host.run_command(['certutil', '-L', '-d', nssdb])
    text = result.stdout_text

    # match CN in cert nickname and C flag in SSL section of NSS flags table
    match_CA_flag = re.compile(r'.*{}.*\s+C'.format(cn))
    match = re.search(match_CA_flag, text)

    return match


def match_in_journal(host, string, since='today', services=('certmonger',)):
    """
    Returns match object for the particular string.
    """
    # prepend '-u' before every service name
    service_args = list(chain.from_iterable(list(zip(repeat('-u'), services))))
    command_args = ['journalctl', '--since={}'.format(since)] + service_args
    result = host.run_command(command_args)

    output = result.stdout_text

    traceback = re.compile(string)
    match = re.search(traceback, output)

    return match


def install_server_external_ca_step1(host, extra_args=(), raiseonerr=True):
    """Step 1 to install the ipa server with external ca"""
    return tasks.install_master(
        host, external_ca=True, extra_args=extra_args, raiseonerr=raiseonerr,
    )


def install_server_external_ca_step2(host, ipa_ca_cert, root_ca_cert,
                                     extra_args=(),
                                     raiseonerr=True):
    """Step 2 to install the ipa server with external ca"""
    args = ['ipa-server-install', '-U', '-r', host.domain.realm,
            '-a', host.config.admin_password,
            '-p', host.config.dirman_password,
            '--external-cert-file', ipa_ca_cert,
            '--external-cert-file', root_ca_cert]
    args.extend(extra_args)
    cmd = host.run_command(args, raiseonerr=raiseonerr)
    return cmd


def check_ipaca_issuerDN(host, expected_dn):
    result = host.run_command(['ipa', 'ca-show', 'ipa'])
    assert "Issuer DN: {}".format(expected_dn) in result.stdout_text


def create_external_ca_with_subject(subject_attrs):
    """
    Create an external CA with custom subject attributes including non-standard
    OIDs.

    :param subject_attrs: List of x509.NameAttribute objects to include in
    subject
    :return: Tuple of (ExternalCA object, root CA certificate as PEM bytes)

    Example:
        subj_attrs = [
            x509.NameAttribute(NameOID.COMMON_NAME, 'My CA'),
            x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),
            x509.NameAttribute(ObjectIdentifier('2.5.4.97'), 'VATEU-123456789')
        ]
        external_ca, root_ca_pem = create_external_ca_with_subject(subj_attrs)
        signed_cert = external_ca.sign_csr(csr_data)
    """
    external_ca = ExternalCA()
    external_ca.create_ca_key()

    # Create the custom subject
    subject = x509.Name(subject_attrs)
    external_ca.issuer = subject

    # Build the root CA certificate
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(subject)
    builder = builder.issuer_name(subject)  # self-signed
    builder = builder.public_key(external_ca.ca_public_key)
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.not_valid_before(external_ca.now)
    builder = builder.not_valid_after(external_ca.now + external_ca.delta)

    # Add required extensions for a CA certificate
    builder = builder.add_extension(
        x509.KeyUsage(
            digital_signature=False,
            content_commitment=False,
            key_encipherment=False,
            data_encipherment=False,
            key_agreement=False,
            key_cert_sign=True,
            crl_sign=True,
            encipher_only=False,
            decipher_only=False,
        ),
        critical=True,
    )

    builder = builder.add_extension(
        x509.BasicConstraints(ca=True, path_length=None),
        critical=True,
    )

    builder = builder.add_extension(
        x509.SubjectKeyIdentifier.from_public_key(
            external_ca.ca_public_key
        ),
        critical=False,
    )

    builder = builder.add_extension(
        x509.AuthorityKeyIdentifier.from_issuer_public_key(
            external_ca.ca_public_key
        ),
        critical=False,
    )

    # Sign the certificate
    root_ca_cert = builder.sign(
        external_ca.ca_key, hashes.SHA256(), default_backend()
    )
    root_ca_pem = root_ca_cert.public_bytes(serialization.Encoding.PEM)

    return external_ca, root_ca_pem


def find_cert_in_chain(cert_chain, subject_attrs=None, issuer_attrs=None):
    """
    Retrieves a certificate from a provided chain that matches specified
    criteria. The search can be filtered using dictionaries of subject
    attributes, issuer attributes, or a combination of both.

    :param cert_chain: List of certificates to search through
    :param subject_attrs: Dict of OID -> expected value for subject attributes
    :param issuer_attrs: Dict of OID -> expected value for issuer attributes
    :return: The matching certificate or None if not found

    Example:
        from cryptography.x509.oid import NameOID, ObjectIdentifier
        org_id_oid = ObjectIdentifier("2.5.4.97")

        # Find IPA CA cert with specific subject and issuer
        cert = find_cert_in_chain(
            ca_chain,
            subject_attrs={
                NameOID.COMMON_NAME: "Certificate Authority",
                NameOID.ORGANIZATION_NAME: "EXAMPLE.TEST"
            },
            issuer_attrs={
                org_id_oid: "VATEU-123456789"
            }
        )
    """
    for cert in cert_chain:
        # Check subject attributes if provided
        if subject_attrs:
            subject_match = True
            for oid, expected_value in subject_attrs.items():
                attrs = [attr for attr in cert.subject if attr.oid == oid]
                if not any(attr.value == expected_value for attr in attrs):
                    # This cert doesn't match, move to next cert
                    subject_match = False
                    break
            if not subject_match:
                continue

        # Check issuer attributes if provided
        if issuer_attrs:
            issuer_match = True
            for oid, expected_value in issuer_attrs.items():
                attrs = [attr for attr in cert.issuer if attr.oid == oid]
                if not any(attr.value == expected_value for attr in attrs):
                    # This cert doesn't match, move to next cert
                    issuer_match = False
                    break
            if not issuer_match:
                continue

        # All specified attributes match, return this cert
        return cert

    return None


def check_mscs_extension(ipa_csr, template):
    csr = x509.load_pem_x509_csr(ipa_csr, default_backend())
    extensions = [
        ext for ext in csr.extensions
        if ext.oid.dotted_string == template.ext_oid
    ]
    assert extensions
    mscs_ext = extensions[0].value

    # Crypto 41.0.0 supports cryptography.x509.MSCertificateTemplate
    # The extension gets decoded into MSCertificateTemplate which
    # provides additional attributes (template_id, major_minor and
    # minor_version)
    # If the test is executed with an older python-cryptography version,
    # the extension is decoded as UnrecognizedExtension instead and
    # provides only the encoded payload
    if isinstance(mscs_ext, x509.UnrecognizedExtension):
        assert mscs_ext.value == template.get_ext_data()
    else:
        # Compare the decoded extension with the values specified in the
        # template with a format name_or_oid:major:minor
        parts = template.unparsed_input.split(':')
        assert mscs_ext.template_id.dotted_string == parts[0]

        if isinstance(template, ipa_x509.MSCSTemplateV2):
            # Also contains OID:major[:minor]
            major = int(parts[1])
            assert major == mscs_ext.major_version
            if len(parts) > 2:
                minor = int(parts[2])
                assert minor == mscs_ext.minor_version


class TestExternalCA(IntegrationTest):
    """
    Test of FreeIPA server installation with external CA
    """
    num_replicas = 1
    num_clients = 1

    def test_external_ca(self):
        # Step 1 of ipa-server-install.
        result = install_server_external_ca_step1(
            self.master, extra_args=['--external-ca-type=ms-cs']
        )
        assert result.returncode == 0

        # check CSR for extension
        ipa_csr = self.master.get_file_contents(paths.ROOT_IPA_CSR)
        check_mscs_extension(ipa_csr, ipa_x509.MSCSTemplateV1(u'SubCA'))

        # Sign CA, transport it to the host and get ipa a root ca paths.
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA)

        # Step 2 of ipa-server-install.
        result = install_server_external_ca_step2(
            self.master, ipa_ca_fname, root_ca_fname)
        assert result.returncode == 0

        # Make sure IPA server is working properly
        tasks.kinit_admin(self.master)
        result = self.master.run_command(['ipa', 'user-show', 'admin'])
        assert 'User login: admin' in result.stdout_text

        # check that we can also install replica
        tasks.install_replica(self.master, self.replicas[0])

        # check that nsds5ReplicaReleaseTimeout option was set
        result = tasks.ldapsearch_dm(
            self.master,
            'cn=mapping tree,cn=config',
            ['(cn=replica)'],
        )
        # case insensitive match
        text = result.stdout_text.lower()
        # see ipaserver.install.replication.REPLICA_FINAL_SETTINGS
        assert 'nsds5ReplicaReleaseTimeout: 60'.lower() in text
        assert 'nsDS5ReplicaBindDnGroupCheckInterval: 60'.lower() in text

    def test_client_installation_with_otp(self):
        # Test for issue 7526: client installation fails with one-time
        # password when the master is installed with an externally signed
        # CA because the whole cert chain is not published in
        # /usr/share/ipa/html/ca.crt

        # Create a random password for the client
        client = self.clients[0]
        client_pwd = 'Secret123'
        args = ['ipa',
                'host-add', client.hostname,
                '--ip-address', client.ip,
                '--no-reverse',
                '--password', client_pwd]
        self.master.run_command(args)

        # Enroll the client with the client_pwd
        client.run_command(
            ['ipa-client-install',
             '--domain', self.master.domain.name,
             '--server', self.master.hostname,
             '-w', client_pwd,
             '-U'])


class TestExternalCAConstraints(IntegrationTest):
    """Test of FreeIPA server installation with external CA and constraints
    """
    num_replicas = 0
    num_clients = 1

    def test_external_ca_constrained(self):
        install_server_external_ca_step1(self.master)

        # name constraints for IPA DNS domain (dot prefix)
        nameconstraint = x509.NameConstraints(
            permitted_subtrees=[
                x509.DNSName("." + self.master.domain.name),
            ],
            excluded_subtrees=None
        )

        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA,
            root_ca_extensions=[nameconstraint],
        )

        install_server_external_ca_step2(
            self.master, ipa_ca_fname, root_ca_fname
        )

        tasks.kinit_admin(self.master)
        self.master.run_command(['ipa', 'ping'])


class TestExternalCAInstallWithOrgId(IntegrationTest):
    """Test 2-step installation with external CA containing
    organizationIdentifier.

    This test verifies that FreeIPA can successfully install with a 2-step
    external CA process when the external CA certificate contains the
    organizationIdentifier attribute (OID 2.5.4.97) in its issuer DN.

    This tests the fix for DN parsing in ensure_ipa_authority_entry in
    cainstance.py where the issuer DN must be properly parsed against
    ATTR_NAME_BY_OID to recognize all OIDs including organizationIdentifier.
    """
    num_replicas = 0
    num_clients = 0

    def test_external_ca_install_with_organization_identifier(self):
        """Test 2-step installation with organizationIdentifier (OID 2.5.4.97)

        Verify that FreeIPA can successfully complete a 2-step installation
        with an external CA that contains organizationIdentifier (OID 2.5.4.97)
        in the issuer DN. The issuer DN should be properly parsed and stored
        in LDAP during the ensure_ipa_authority_entry process.
        """

        # Test parameters
        org_id_value = "VATEU-123456789"
        org_id_oid = ObjectIdentifier("2.5.4.97")  # organizationIdentifier OID
        external_ca_cn = "External CA with OrgID"

        # Step 1 of ipa-server-install
        result = install_server_external_ca_step1(self.master)
        assert result.returncode == 0

        # Get the CSR generated by step 1
        ipa_csr = self.master.get_file_contents(paths.ROOT_IPA_CSR)

        # Create an external CA with organizationIdentifier in the subject
        subject_attrs = [
            x509.NameAttribute(NameOID.COMMON_NAME, external_ca_cn),
            x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Test Organization'),
            x509.NameAttribute(org_id_oid, org_id_value),
        ]
        external_ca, root_ca = create_external_ca_with_subject(subject_attrs)

        # Sign the IPA CSR with the external CA that has organizationIdentifier
        ipa_ca = external_ca.sign_csr(ipa_csr)

        # Write certificates to files
        root_ca_fname = os.path.join(
            self.master.config.test_dir,
            'root_ca_with_orgid.crt'
        )
        ipa_ca_fname = os.path.join(
            self.master.config.test_dir,
            'ipa_ca_signed_with_orgid.crt'
        )

        # Transport certificates to master
        self.master.put_file_contents(root_ca_fname, root_ca)
        self.master.put_file_contents(ipa_ca_fname, ipa_ca)

        # Step 2 of ipa-server-install
        # This should succeed despite organizationIdentifier in issuer DN
        result = install_server_external_ca_step2(
            self.master, ipa_ca_fname, root_ca_fname
        )
        assert result.returncode == 0

        # Make sure IPA server is working properly
        tasks.kinit_admin(self.master)
        result = self.master.run_command(['ipa', 'user-show', 'admin'])
        assert 'User login: admin' in result.stdout_text

        # Verify IPA is functional
        result = self.master.run_command(['ipa', 'ping'])
        assert result.returncode == 0

        # Verify the certificate chain contains the expected certificates
        # Load all certificates from /etc/ipa/ca.crt (the CA chain)
        ca_chain_content = self.master.get_file_contents(paths.IPA_CA_CRT)
        ca_chain = ipa_x509.load_certificate_list(ca_chain_content)

        # 1. Find and verify the IPA CA certificate
        # It should have subject O=REALM, CN=Certificate Authority
        # and issuer with organizationIdentifier
        ipa_ca_cert = find_cert_in_chain(
            ca_chain,
            subject_attrs={
                NameOID.COMMON_NAME: "Certificate Authority",
                NameOID.ORGANIZATION_NAME: self.master.domain.realm
            },
            issuer_attrs={
                org_id_oid: org_id_value,
                NameOID.COMMON_NAME: external_ca_cn
            }
        )
        assert ipa_ca_cert is not None, \
            f"Did not find IPA CA certificate with subject " \
            f"O={self.master.domain.realm}, CN=Certificate Authority " \
            f"and issuer with organizationIdentifier={org_id_value}"

        # 2. Find and verify the external root CA certificate
        # It should be self-signed with organizationIdentifier in subject
        external_ca_cert = find_cert_in_chain(
            ca_chain,
            subject_attrs={
                NameOID.COMMON_NAME: external_ca_cn,
                org_id_oid: org_id_value
            },
            issuer_attrs={
                NameOID.COMMON_NAME: external_ca_cn,
                org_id_oid: org_id_value
            }
        )
        assert external_ca_cert is not None, \
            f"Did not find external root CA certificate (CN={external_ca_cn})" \
            f" with organizationIdentifier={org_id_value} in subject"

        # 3. Verify the issuer DN is correctly stored in LDAP
        # The issuer DN should contain organizationIdentifier
        # Note: The order in the DN string representation matters
        result = self.master.run_command(['ipa', 'ca-show', 'ipa'])
        assert f"organizationIdentifier={org_id_value}" in result.stdout_text, \
            "organizationIdentifier not found in IPA CA issuer DN"


def verify_caentry(host, cert):
    """
    Verify the content of cn=DOMAIN IPA CA,cn=certificates,cn=ipa,cn=etc,basedn
    and make sure that ipaConfigString contains the expected values.
    Verify the content of cn=cacert,cn=certificates,cn=ipa,cn=etc,basedn
    and make sure that it contains the expected certificate.
    """
    # Check the LDAP entry
    ldap = host.ldap_connect()
    # cn=DOMAIN IPA CA must contain ipaConfigString: ipaCa, compatCA
    ca_nick = '{} IPA CA'.format(host.domain.realm)
    entry = ldap.get_entry(DN(('cn', ca_nick), ('cn', 'certificates'),
                              ('cn', 'ipa'), ('cn', 'etc'),
                              host.domain.basedn))
    ipaconfigstring = [x.lower() for x in entry.get('ipaconfigstring')]
    expected = ['compatca', 'ipaca']
    assert expected == sorted(ipaconfigstring)

    # cn=cacert,cn=certificates,cn=etc,basedn must contain the latest
    # IPA CA
    entry2 = ldap.get_entry(DN(('cn', 'CACert'), ('cn', 'ipa'),
                               ('cn', 'etc'), host.domain.basedn))
    cert_from_ldap = entry2.single_value['cACertificate']
    assert cert == cert_from_ldap


class TestSelfExternalSelf(IntegrationTest):
    """
    Test self-signed > external CA > self-signed test case.
    """
    def test_install_master(self):
        result = tasks.install_master(self.master)
        assert result.returncode == 0

        # Check the content of the ldap entries for the CA
        remote_cacrt = self.master.get_file_contents(paths.IPA_CA_CRT)
        cacrt = ipa_x509.load_pem_x509_certificate(remote_cacrt)
        verify_caentry(self.master, cacrt)

    def test_switch_to_external_ca(self):

        result = self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew',
                                         '--external-ca'])
        assert result.returncode == 0

        # Sign CA, transport it to the host and get ipa a root ca paths.
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.IPA_CA_CSR, ROOT_CA, IPA_CA)

        # renew CA with externally signed one
        result = self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew',
                                          '--external-cert-file={}'.
                                          format(ipa_ca_fname),
                                          '--external-cert-file={}'.
                                          format(root_ca_fname)])
        assert result.returncode == 0

        # update IPA certificate databases
        result = self.master.run_command([paths.IPA_CERTUPDATE])
        assert result.returncode == 0

        # Check if external CA have "C" flag after the switch
        result = check_CA_flag(self.master)
        assert bool(result), ('External CA does not have "C" flag')

        # Check that ldap entries for the CA have been updated
        remote_cacrt = self.master.get_file_contents(ipa_ca_fname)
        cacrt = ipa_x509.load_pem_x509_certificate(remote_cacrt)
        verify_caentry(self.master, cacrt)

    def test_issuerDN_after_renew_to_external(self):
        """ Check if issuer DN is updated after self-signed > external-ca

        This test checks if issuer DN is updated properly after CA is
        renewed from self-signed to external-ca
        """
        check_ipaca_issuerDN(self.master, "CN={}".format(ISSUER_CN))

    def test_switch_back_to_self_signed(self):

        # for journalctl --since
        switch_time = time.strftime('%Y-%m-%d %H:%M:%S')
        # switch back to self-signed CA
        result = self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew',
                                          '--self-signed'])
        assert result.returncode == 0

        # Confirm there is no traceback in the journal
        result = match_in_journal(self.master, since=switch_time,
                                  string='Traceback')
        assert not bool(result), ('"Traceback" keyword found in the journal.'
                                  'Please check further')

        # Check if pki-tomcatd was started after switching back.
        result = match_in_journal(self.master, since=switch_time,
                                  string=PKI_START_STR)
        assert bool(result), ('pki_tomcatd not started after switching back to'
                              'self-signed CA')

        result = self.master.run_command([paths.IPA_CERTUPDATE])
        assert result.returncode == 0

    def test_issuerDN_after_renew_to_self_signed(self):
        """ Check if issuer DN is updated after external-ca > self-signed

        This test checks if issuer DN is updated properly after CA is
        renewed back from external-ca to self-signed
        """
        issuer_dn = 'CN=Certificate Authority,O={}'.format(
            self.master.domain.realm)
        check_ipaca_issuerDN(self.master, issuer_dn)


class TestExternalCAdirsrvStop(IntegrationTest):
    """When the dirsrv service, which gets started during the first
    ipa-server-install --external-ca phase, is not running when the
    second phase is run with --external-cert-file options, the
    ipa-server-install command fail.

    This test checks if second phase installs successfully when dirsrv
    is stoped.

    related ticket: https://pagure.io/freeipa/issue/6611"""
    def test_external_ca_dirsrv_stop(self):

        # Step 1 of ipa-server-install
        result = install_server_external_ca_step1(self.master)
        assert result.returncode == 0

        # stop dirsrv server.
        tasks.service_control_dirsrv(self.master, 'stop')

        # Sign CA, transport it to the host and get ipa and root ca paths.
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA)

        # Step 2 of ipa-server-install.
        result = install_server_external_ca_step2(
            self.master, ipa_ca_fname, root_ca_fname)
        assert result.returncode == 0

        # Make sure IPA server is working properly
        tasks.kinit_admin(self.master)
        result = self.master.run_command(['ipa', 'user-show', 'admin'])
        assert 'User login: admin' in result.stdout_text


class TestExternalCAInvalidCert(IntegrationTest):
    """Manual renew external CA cert with invalid file"""

    def test_external_ca(self):
        # Step 1 of ipa-server-install.
        install_server_external_ca_step1(self.master)

        # Sign CA, transport it to the host and get ipa a root ca paths.
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA)

        # Step 2 of ipa-server-install.
        install_server_external_ca_step2(self.master, ipa_ca_fname,
                                         root_ca_fname)

        self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew',
                                 '--external-ca'])
        result = self.master.run_command(['grep', '-v', 'CERTIFICATE',
                                          ipa_ca_fname])
        contents = result.stdout_text

        BAD_CERT = 'bad_ca.crt'
        invalid_cert = os.path.join(self.master.config.test_dir, BAD_CERT)
        self.master.put_file_contents(invalid_cert, contents)
        # Sign CA, transport it to the host and get ipa a root ca paths.
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.IPA_CA_CSR, ROOT_CA, IPA_CA)
        # renew CA with invalid cert
        cmd = [paths.IPA_CACERT_MANAGE, 'renew', '--external-cert-file',
               invalid_cert, '--external-cert-file', root_ca_fname]
        result = self.master.run_command(cmd, raiseonerr=False)
        assert result.returncode == 1

    def test_external_ca_with_too_small_key(self):
        # reuse the existing deployment and renewal CSR
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.IPA_CA_CSR, ROOT_CA, IPA_CA, key_size=1024)

        cmd = [
            paths.IPA_CACERT_MANAGE, 'renew',
            '--external-cert-file', ipa_ca_fname,
            '--external-cert-file', root_ca_fname,
        ]
        result = self.master.run_command(cmd, raiseonerr=False)
        assert result.returncode == 1


class TestExternalCAInvalidIntermediate(IntegrationTest):
    """Test case for https://pagure.io/freeipa/issue/7877"""

    def test_invalid_intermediate(self):
        install_server_external_ca_step1(self.master)
        root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport(
            self.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA,
            root_ca_path_length=0
        )
        result = install_server_external_ca_step2(
            self.master, ipa_ca_fname, root_ca_fname, raiseonerr=False
        )
        assert result.returncode > 0
        assert "basic contraint pathlen" in result.stderr_text


class TestExternalCAInstall(IntegrationTest):
    """install CA cert manually """

    def test_install_master(self):
        # step 1 install ipa-server

        tasks.install_master(self.master)

    def test_install_external_ca(self):
        # Create root CA
        external_ca = ExternalCA()
        # Create root CA
        root_ca = external_ca.create_ca()
        root_ca_fname = os.path.join(self.master.config.test_dir, ROOT_CA)

        # Transport certificates (string > file) to master
        self.master.put_file_contents(root_ca_fname, root_ca)

        # Install new cert
        self.master.run_command([paths.IPA_CACERT_MANAGE, 'install',
                                 root_ca_fname])

    def test_renew_external_ca_with_organization_identifier(self):
        """Test CA renewal with organizationIdentifier (OID 2.5.4.97)

        Verify that FreeIPA can successfully renew CA with an external CA
        that contains organizationIdentifier (OID 2.5.4.97) in the issuer DN.
        The IPA CA will be signed by this external CA, and the issuer DN
        will contain the organizationIdentifier attribute.
        """

        # Test parameters
        org_id_value = "VATEU-123456789"
        org_id_oid = ObjectIdentifier("2.5.4.97")  # organizationIdentifier OID
        external_ca_cn = "External CA with OrgID"

        # Initiate CA renewal with external CA
        result = self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew',
                                         '--external-ca'])
        assert result.returncode == 0

        # Get the CSR generated by the renewal process
        ipa_csr = self.master.get_file_contents(paths.IPA_CA_CSR)

        # Create an external CA with organizationIdentifier in the subject
        subject_attrs = [
            x509.NameAttribute(NameOID.COMMON_NAME, external_ca_cn),
            x509.NameAttribute(NameOID.COUNTRY_NAME, 'US'),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'Test Organization'),
            x509.NameAttribute(org_id_oid, org_id_value),
        ]
        external_ca, root_ca = create_external_ca_with_subject(subject_attrs)

        # Sign the IPA CSR with the external CA that has organizationIdentifier
        ipa_ca = external_ca.sign_csr(ipa_csr)

        # Write certificates to files
        root_ca_fname = os.path.join(
            self.master.config.test_dir,
            'root_ca_with_orgid.crt'
        )
        ipa_ca_fname = os.path.join(
            self.master.config.test_dir,
            'ipa_ca_signed_with_orgid.crt'
        )

        # Transport certificates to master
        self.master.put_file_contents(root_ca_fname, root_ca)
        self.master.put_file_contents(ipa_ca_fname, ipa_ca)

        # Complete the renewal with the signed certificates
        # This should succeed despite organizationIdentifier in issuer DN
        result = self.master.run_command([
            paths.IPA_CACERT_MANAGE, 'renew',
            '--external-cert-file', ipa_ca_fname,
            '--external-cert-file', root_ca_fname
        ])
        assert result.returncode == 0

        # Verify the CA was properly installed
        result = self.master.run_command([paths.IPA_CERTUPDATE])
        assert result.returncode == 0

        # Verify IPA is still functional
        tasks.kinit_admin(self.master)
        result = self.master.run_command(['ipa', 'ping'])
        assert result.returncode == 0

        # Verify the certificate chain contains the expected certificates
        # Load all certificates from /etc/ipa/ca.crt (the CA chain)
        ca_chain_content = self.master.get_file_contents(paths.IPA_CA_CRT)
        ca_chain = ipa_x509.load_certificate_list(ca_chain_content)

        # 1. Find and verify the IPA CA certificate
        # It should have subject O=REALM, CN=Certificate Authority
        # and issuer with organizationIdentifier
        ipa_ca_cert = find_cert_in_chain(
            ca_chain,
            subject_attrs={
                NameOID.COMMON_NAME: "Certificate Authority",
                NameOID.ORGANIZATION_NAME: self.master.domain.realm
            },
            issuer_attrs={
                org_id_oid: org_id_value,
                NameOID.COMMON_NAME: external_ca_cn
            }
        )
        assert ipa_ca_cert is not None, \
            f"Did not find IPA CA certificate with subject " \
            f"O={self.master.domain.realm}, CN=Certificate Authority " \
            f"and issuer with organizationIdentifier={org_id_value}"

        # 2. Find and verify the external root CA certificate
        # It should be self-signed with organizationIdentifier in subject
        external_ca_cert = find_cert_in_chain(
            ca_chain,
            subject_attrs={
                NameOID.COMMON_NAME: external_ca_cn,
                org_id_oid: org_id_value
            },
            issuer_attrs={
                NameOID.COMMON_NAME: external_ca_cn,
                org_id_oid: org_id_value
            }
        )
        assert external_ca_cert is not None, \
            f"Did not find external root CA certificate (CN={external_ca_cn})"\
            f" with organizationIdentifier={org_id_value} in subject"


class TestMultipleExternalCA(IntegrationTest):
    """Setup externally signed ca1

    install ipa-server with externally signed ca1
    Setup externally signed ca2 and renew ipa-server with
    externally signed ca2 and check the difference in certificate
    """

    def test_master_install_ca1(self):
        install_server_external_ca_step1(self.master)
        # Sign CA, transport it to the host and get ipa a root ca paths.
        root_ca_fname1 = tasks.create_temp_file(
            self.master, directory=paths.TMP, suffix="root_ca.crt"
        )
        ipa_ca_fname1 = tasks.create_temp_file(
            self.master, directory=paths.TMP, suffix="ipa_ca.crt"
        )

        ipa_csr = self.master.get_file_contents(paths.ROOT_IPA_CSR)

        external_ca = ExternalCA()
        root_ca = external_ca.create_ca(cn='RootCA1')
        ipa_ca = external_ca.sign_csr(ipa_csr)
        self.master.put_file_contents(root_ca_fname1, root_ca)
        self.master.put_file_contents(ipa_ca_fname1, ipa_ca)
        # Step 2 of ipa-server-install.
        install_server_external_ca_step2(self.master, ipa_ca_fname1,
                                         root_ca_fname1)

        cert_nick = "caSigningCert cert-pki-ca"
        result = self.master.run_command([
            'certutil', '-L', '-d', paths.PKI_TOMCAT_ALIAS_DIR,
            '-n', cert_nick])
        assert "CN=RootCA1" in result.stdout_text

    def test_master_install_ca2(self):
        root_ca_fname2 = tasks.create_temp_file(
            self.master, directory=paths.TMP, suffix="root_ca.crt"
        )
        ipa_ca_fname2 = tasks.create_temp_file(
            self.master, directory=paths.TMP, suffix="ipa_ca.crt"
        )

        self.master.run_command([
            paths.IPA_CACERT_MANAGE, 'renew', '--external-ca'])

        ipa_csr = self.master.get_file_contents(paths.IPA_CA_CSR)

        external_ca = ExternalCA()
        root_ca = external_ca.create_ca(cn='RootCA2')
        ipa_ca = external_ca.sign_csr(ipa_csr)
        self.master.put_file_contents(root_ca_fname2, root_ca)
        self.master.put_file_contents(ipa_ca_fname2, ipa_ca)
        # Step 2 of ipa-server-install.
        self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew',
                                 '--external-cert-file', ipa_ca_fname2,
                                 '--external-cert-file', root_ca_fname2])

        cert_nick = "caSigningCert cert-pki-ca"
        result = self.master.run_command([
            'certutil', '-L', '-d', paths.PKI_TOMCAT_ALIAS_DIR,
            '-n', cert_nick])
        assert "CN=RootCA2" in result.stdout_text


def _step1_profile(master, s):
    return install_server_external_ca_step1(
        master,
        extra_args=['--external-ca-type=ms-cs', f'--external-ca-profile={s}'],
        raiseonerr=False,
    )


def _test_invalid_profile(master, profile):
    result = _step1_profile(master, profile)
    assert result.returncode != 0
    assert '--external-ca-profile' in result.stderr_text


def _test_valid_profile(master, profile_cls, profile):
    result = _step1_profile(master, profile)
    assert result.returncode == 0
    ipa_csr = master.get_file_contents(paths.ROOT_IPA_CSR)
    check_mscs_extension(ipa_csr, profile_cls(profile))


class TestExternalCAProfileScenarios(IntegrationTest):
    """
    Test the various --external-ca-profile scenarios.
    This test is broken into sections, with each section first
    testing invalid arguments, then a valid argument, and finally
    uninstalling the half-installed IPA.

    """

    '''
    Tranche 1: version 1 templates.

    Test that --external-ca-profile=Foo gets propagated to the CSR.

    The default template extension when --external-ca-type=ms-cs,
    a V1 extension with value "SubCA", already gets tested by the
    ``TestExternalCA`` class.

    We only need to do Step 1 of installation, then check the CSR.

    '''
    def test_invalid_v1_template(self):
        _test_invalid_profile(self.master, 'NotAnOid:1')

    def test_valid_v1_template(self):
        _test_valid_profile(
            self.master, ipa_x509.MSCSTemplateV1, 'TemplateOfAwesome')

    def test_uninstall_1(self):
        tasks.uninstall_master(self.master)

    '''
    Tranche 2: V2 templates without minor version.

    Test that V2 template specifiers without minor version get
    propagated to CSR.  This class also tests all error modes in
    specifying a V2 template, those being:

    - no major version specified
    - too many parts specified (i.e. major, minor, and then some more)
    - major version is not an int
    - major version is negative
    - minor version is not an int
    - minor version is negative

    We only need to do Step 1 of installation, then check the CSR.

    '''
    def test_v2_template_too_few_parts(self):
        _test_invalid_profile(self.master, '1.2.3.4')

    def test_v2_template_too_many_parts(self):
        _test_invalid_profile(self.master, '1.2.3.4:100:200:300')

    def test_v2_template_major_version_not_int(self):
        _test_invalid_profile(self.master, '1.2.3.4:wat:200')

    def test_v2_template_major_version_negative(self):
        _test_invalid_profile(self.master, '1.2.3.4:-1:200')

    def test_v2_template_minor_version_not_int(self):
        _test_invalid_profile(self.master, '1.2.3.4:100:wat')

    def test_v2_template_minor_version_negative(self):
        _test_invalid_profile(self.master, '1.2.3.4:100:-2')

    def test_v2_template_valid_major_only(self):
        _test_valid_profile(
            self.master, ipa_x509.MSCSTemplateV2, '1.2.3.4:100')

    def test_uninstall_2(self):
        tasks.uninstall_master(self.master)

    '''
    Tranche 3: V2 templates with minor version.

    Test that V2 template specifiers _with_ minor version get
    propagated to CSR.  All error modes of V2 template specifiers
    were tested in ``TestExternalCAProfileV2Major``.

    We only need to do Step 1 of installation, then check the CSR.

    '''
    def test_v2_template_valid_major_minor(self):
        _test_valid_profile(
            self.master, ipa_x509.MSCSTemplateV2, '1.2.3.4:100:200')

    # this is the end; no need to uninstall.