summaryrefslogtreecommitdiffstats
path: root/base/common/python/pki/authority.py
blob: 8827db88aac879f450b47e88754972c242595b8e (plain)
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
# 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; version 2 of the License.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2014 Red Hat, Inc.
# All rights reserved.
#
# Author:
#     Ade Lee <alee@redhat.com>

from __future__ import absolute_import
from __future__ import print_function

import json
from six import iteritems
import uuid

import pki
import pki.client as client
import pki.encoder as encoder
import pki.cert as cert


class AuthorityData(object):
    """
    Class containing authority data to be sent to/from the server when
    getting or creating subordinate CAs
    """

    json_attribute_names = {
        'id': 'aid',
        'description': 'description',
        'dn': 'dn',
        'enabled': 'enabled',
        'isHostAuthority': 'is_host_authority',
        'link': 'link',
        'parentID': 'parent_aid'
    }

    def __init__(self, dn=None, aid=None, parent_aid=None,
                 description=None, enabled="False",
                 is_host_authority="False", link=None):
        self.dn = dn
        self.aid = aid
        self.parent_aid = parent_aid
        self.description = description
        self.enabled = (enabled.lower() == "true")
        self.is_host_authority = (is_host_authority.lower() == "true")
        self.link = link

    def __repr__(self):
        attributes = {
            "AuthorityData": {
                "aid": self.aid,
                "dn": self.dn,
                "description": self.description,
                "is_host_authority": self.is_host_authority,
                "parent_aid": self.parent_aid,
                "enabled": self.enabled
            }
        }
        return str(attributes)

    @classmethod
    def from_json(cls, attr_list):
        """ Return AuthorityData object from JSON dict """
        ca_data = cls()

        for k, v in iteritems(attr_list):
            if k not in ['link']:
                if k in AuthorityData.json_attribute_names:
                    setattr(ca_data, AuthorityData.json_attribute_names[k], v)
                else:
                    setattr(ca_data, k, v)

        if 'link' in attr_list:
            ca_data.link = pki.Link.from_json(attr_list['link'])

        return ca_data


class AuthorityDataCollection(object):
    """
    Class containing list of AuthorityData objects and their respective link
    objects.
    This data is returned when searching/listing authorities.
    """

    def __init__(self):
        """ Constructor """
        self.ca_list = []
        self.links = []

    def __iter__(self):
        return iter(self.ca_list)

    @classmethod
    def from_json(cls, json_value):
        """ Populate object from JSON input """
        ret = cls()
        cas = json_value
        if not isinstance(cas, list):
            ret.ca_list.append(AuthorityData.from_json(cas))
        else:
            for ca in cas:
                ret.ca_list.append(
                    AuthorityData.from_json(ca))

        return ret


class AuthorityClient(object):
    """
    Class encapsulating and mirroring the functionality in the
    AuthorityResource Java interface class defining the REST API for
    subordinate CA (authority) resources.
    """

    def __init__(self, connection):
        """ Constructor """
        self.connection = connection
        self.ca_url = '/rest/authorities'

    @pki.handle_exceptions()
    def get_ca(self, aid):
        """ Return a AuthorityData object for a subordinate CA. """
        if aid is None:
            raise ValueError("Subordinate aid must be specified")

        url = self.ca_url + '/' + str(aid)
        headers = {'Content-type': 'application/json',
                   'Accept': 'application/json'}
        r = self.connection.get(url, headers)
        return AuthorityData.from_json(r.json())

    @pki.handle_exceptions()
    def get_cert(self, aid, output_format="PEM"):
        """Return the signing certificate for the CA

        :param aid: ID for the CA
        :param output_format: either 'PEM' or 'DER'
        :return: CA certificate in relevant format
        """
        """ Return the signing certificate for the CA. """
        if aid is None:
            raise ValueError("CA ID must be specified")

        url = '{}/{}/cert'.format(self.ca_url, str(aid))

        headers = {'Content-type': 'application/json'}

        if output_format == "PEM":
            headers['Accept'] = "application/x-pem-file"
        elif output_format == "DER":
            headers['Accept'] = "application/pkix-cert"
        else:
            raise ValueError(
                "Invalid format passed in - PEM or DER expected.")

        r = self.connection.get(url, headers)
        return r.text

    @pki.handle_exceptions()
    def get_chain(self, aid, output_format="PKCS7"):
        """Returns the certificate chain for the CA.

        :param aid: ID for the CA
        :param output_format: either PEM or PKCS7
        :return: CA certificate chain in requested format
        """
        if aid is None:
            raise ValueError("CA ID must be specified")

        url = '{}/{}/chain'.format(self.ca_url, str(aid))

        headers = {'Content-type': 'application/json'}
        if output_format == "PEM":
            headers['Accept'] = "application/x-pem-file"
        elif output_format == "PKCS7":
            headers['Accept'] = "application/pkcs7-mime"

        r = self.connection.get(url, headers)
        return r.text

    @pki.handle_exceptions()
    def list_cas(self, max_results=None, max_time=None, start=None, size=None):
        """ Return a AuthorityDataCollection object of subordinate CAs

        Right now, this is going to list all the defined authorities.  We will
        add search criteria when this is defined on the Java interface.
        """
        query_params = {"maxResults": max_results, "maxTime": max_time,
                        "start": start, "size": size}
        headers = {'Content-type': 'application/json',
                   'Accept': 'application/json'}
        response = self.connection.get(
            path=self.ca_url,
            headers=headers,
            params=query_params)
        return AuthorityDataCollection.from_json(response.json())

    @pki.handle_exceptions()
    def create_ca(self, ca_data):
        """ Create authority (subCA)
        :param ca_data: AuthorityData object containing parameters that
            describe how a subordinate authority should be constructed.
        :return: AuthorityData object for the created subordinate CA
        """
        if ca_data is None:
            raise ValueError("ca_data must be defined")

        if ca_data.dn is None:
            raise ValueError("Subject DN must be defined in ca_data")

        if ca_data.description is None:
            raise ValueError('Description must be defined in ca_data')

        if ca_data.parent_aid is None:
            raise ValueError('parent_aid must be defined.  '
                             'Top level CAs are not yet supported')

        create_request = json.dumps(ca_data, cls=encoder.CustomTypeEncoder,
                                    sort_keys=True)

        headers = {'Content-type': 'application/json',
                   'Accept': 'application/json'}

        response = self.connection.post(
            self.ca_url,
            create_request,
            headers)

        new_ca = AuthorityData.from_json(response.json())
        return new_ca

    @pki.handle_exceptions()
    def enable_ca(self, aid):
        """Enable the specified CA
        :param aid: ID of the CA to be enabled
        :return: None
        """
        if aid is None:
            raise ValueError("CA ID must be specified")

        url = '{}/{}/enable'.format(self.ca_url, str(aid))

        headers = {'Content-type': 'application/json',
                   'Accept': 'application/json'}

        self.connection.post(url, headers)

    @pki.handle_exceptions()
    def disable_ca(self, aid):
        """Disable the specified CA
        :param aid: ID of the CA to be disabled
        :return: None
        """
        if aid is None:
            raise ValueError("CA ID must be specified")

        url = '{}/{}/disable'.format(self.ca_url, str(aid))
        headers = {'Content-type': 'application/json',
                   'Accept': 'application/json'}

        self.connection.post(url, headers)

    @pki.handle_exceptions()
    def delete_ca(self, aid):
        """Delete the specified CA
        :param aid: ID of the CA to be deleted
        :return: None
        """
        if aid is None:
            raise ValueError("CA ID must be specified")

        url = '{}/{}'.format(self.ca_url, str(aid))
        headers = {'Content-type': 'application/json',
                   'Accept': 'application/json'}

        self.connection.delete(url, headers)

encoder.NOTYPES['AuthorityData'] = AuthorityData


def issue_cert_using_authority(cert_client, authority_id):
    print("Issuing Cert using subordinate CA")
    print("---------------------------------")
    print("aid: " + authority_id)

    inputs = dict()
    inputs['cert_request_type'] = 'crmf'
    inputs['cert_request'] = "MIIBpDCCAaAwggEGAgUA5n9VYTCBx4ABAqUOMAwxCjAIBgN" \
                             "VBAMTAXimgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAK" \
                             "/SmUVoUjBtqHNw/e3OoCSXw42pdQSR53/eYJWpf7nyTbZ9U" \
                             "uIhGfXOtxy5vRetmDHE9u0AopmuJbr1rL17/tSnDakpkE9u" \
                             "mQ2lMOReLloSdX32w2xOeulUwh5BGbFpq10S0SvW1H93Vn0" \
                             "eCy2aa4UtILNEsp7JJ3FnYJibfuMPAgMBAAGpEDAOBgNVHQ" \
                             "8BAf8EBAMCBeAwMzAVBgkrBgEFBQcFAQEMCHJlZ1Rva2VuM" \
                             "BoGCSsGAQUFBwUBAgwNYXV0aGVudGljYXRvcqGBkzANBgkq" \
                             "hkiG9w0BAQUFAAOBgQCuywnrDk/wGwfbguw9oVs9gzFQwM4" \
                             "zeFbk+z82G5CWoG/4mVOT5LPL5Q8iF+KfnaU9Qcu6zZPxW6" \
                             "ZmDd8WpPJ+MTPyQl3Q5BfiKa4l5ra1NeqxMOlMiiupwINmm" \
                             "7jd1KaA2eIjuyC8/gTaO4b14R6aRaOj+Scp9cNYbthA7REh" \
                             "Jw=="
    inputs['sn_uid'] = 'test12345'
    inputs['sn_e'] = 'example@redhat.com'
    inputs['sn_cn'] = 'TestUser'

    enrollment_results = cert_client.enroll_cert(
        'caUserCert', inputs, authority_id)

    for enrollment_result in enrollment_results:
        request_data = enrollment_result.request
        cert_data = enrollment_result.cert
        print('Request ID: ' + request_data.request_id)
        print('Request Status:' + request_data.request_status)
        print('Serial Number: ' + cert_data.serial_number)
        print('Issuer: ' + cert_data.issuer_dn)
        print('Subject: ' + cert_data.subject_dn)
        print('Pretty Print:')
        print(cert_data.pretty_repr)

    print()


def main():
    # Create a PKIConnection object that stores the details of the CA.
    connection = client.PKIConnection('https', 'localhost', '8453', 'ca')

    # The pem file used for authentication. Created from a p12 file using the
    # command -
    # openssl pkcs12 -in <p12_file_path> -out /tmp/auth.pem -nodes
    connection.set_authentication_cert("/tmp/auth.pem")

    # Instantiate the CertClient
    ca_client = AuthorityClient(connection)

    # Create a top level authority
    print("Creating a new top level CA")
    print("-----------------------------")

    subca_subject = ('cn=subca ' + str(uuid.uuid4()) +
                     ' signing cert, o=example.com')

    sub_subca_subject = ('cn=subca2 ' + str(uuid.uuid4()) +
                         ' signing cert, o=example.com')
    authority_data = {
        'dn': subca_subject,
        'description': 'Test Top-level subordinate CA',
    }
    data = AuthorityData(**authority_data)
    try:
        subca = ca_client.create_ca(data)
    except ValueError as e:
        print(e.message)

    # Get the host CA
    print("Getting the host CA")
    print("----------------------")
    authorities = ca_client.list_cas()
    for ca in authorities.ca_list:
        if ca.is_host_authority:
            host_ca = ca

    print(str(host_ca))

    # Create a sub CA
    print("Creating a new subordinate CA")
    print("-----------------------------")

    authority_data = {
        'dn': subca_subject,
        'description': 'Test subordinate CA',
        'parent_aid': host_ca.aid
    }
    data = AuthorityData(**authority_data)
    subca = ca_client.create_ca(data)
    print(ca_client.get_ca(subca.aid))

    # Get the authority signing cert and pkcs7 chain
    pem_cert = ca_client.get_cert(subca.aid, "PEM")
    print("PEM CA Signing Cert:")
    print(pem_cert)

    pkcs7_chain = ca_client.get_chain(subca.aid, "PKCS7")
    print("PKCS7 Cert Chain:")
    print(pkcs7_chain)

    pem_chain = ca_client.get_chain(subca.aid, "PEM")
    print("PEM Cert Chain:")
    print(pem_chain)

    # List all authorities
    print("Listing all authorities")
    print("-----------------------")
    authorities = ca_client.list_cas()
    for ca in authorities.ca_list:
        print(str(ca))

    # Issue a cert using the sub-CA
    cert_client = cert.CertClient(connection)
    issue_cert_using_authority(cert_client, subca.aid)

    # Create a sub-sub CA
    print('Create a sub-sub CA')
    print('-------------------')
    sub_subca_data = {
        'dn': sub_subca_subject,
        'description': 'Test sub-sub CA',
        'parent_aid': subca.aid
    }

    data = AuthorityData(**sub_subca_data)
    sub_subca = ca_client.create_ca(data)
    print(ca_client.get_ca(sub_subca.aid))

    # Get the authority signing cert and PKCS7
    # Get the authority signing cert and pkcs7 chain
    pem_cert = ca_client.get_cert(sub_subca.aid, "PEM")
    print("PEM CA Signing Cert:")
    print(pem_cert)

    pkcs7_chain = ca_client.get_chain(sub_subca.aid, "PKCS7")
    print("PKCS7 Cert Chain:")
    print(pkcs7_chain)

    pem_chain = ca_client.get_chain(sub_subca.aid, "PEM")
    print("PEM Cert Chain:")
    print(pem_chain)

    # issue a cert using the sub-subca
    cert_client = cert.CertClient(connection)
    issue_cert_using_authority(cert_client, sub_subca.aid)

    # delete the sub-subca
    print("Delete sub CA")
    print("-------------")
    try:
        ca_client.delete_ca(sub_subca.aid)
    except pki.ConflictingOperationException as e:
        print(e)

    # disable the sub-subca
    print("Disable sub sub CA")
    print("------------------")
    ca_client.disable_ca(sub_subca.aid)

    # Get sub-subca
    sub_subca = ca_client.get_ca(sub_subca.aid)
    print(str(sub_subca))

    # issue a cert using sub-subca
    print("Issuing a cert using disabled subca")
    print("-----------------------------------")
    try:
        issue_cert_using_authority(cert_client, sub_subca.aid)
    except pki.ConflictingOperationException as e:
        print(e)

    # delete the sub-subca
    print("Delete sub CA")
    print("-------------")
    ca_client.delete_ca(sub_subca.aid)

    # get the sub-subca
    print("Get deleted subca")
    print("-----------------")
    try:
        ca_client.get_ca(sub_subca.aid)
    except pki.ResourceNotFoundException as e:
        print(e)

    # issue a cert using the sub-subca
    print("Issue a cert using deleted subca")
    print("--------------------------------")
    try:
        issue_cert_using_authority(cert_client, sub_subca.aid)
    except pki.ResourceNotFoundException as e:
        print(e)

    # create a new subca with same subjectdn
    print("Create a new sub-subca re-using subject dn")
    print("------------------------------------------")
    data = AuthorityData(**sub_subca_data)
    sub_subca = ca_client.create_ca(data)
    print(ca_client.get_ca(sub_subca.aid))

    print("Issuing a cert using sub-subca")
    print("-----------------------------------")
    issue_cert_using_authority(cert_client, sub_subca.aid)

if __name__ == "__main__":
    main()