blob: fcce6640b102d98fcc714a4feea3096918b6a92f [file] [log] [blame]
Jean-Paul Calderone8671c852011-03-02 19:26:20 -05001# Copyright (c) Jean-Paul Calderone
2# See LICENSE file for details.
Jean-Paul Calderone8b63d452008-03-21 18:31:12 -04003
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -05004"""
Jonathan Ballet648875f2011-07-16 14:14:58 +09005Unit tests for :py:mod:`OpenSSL.crypto`.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -05006"""
7
Alex Chanb00ede22017-01-30 07:24:40 +00008from warnings import simplefilter
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04009
Alex Gaynor4b9c96a2014-08-14 09:51:48 -070010import base64
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -040011from subprocess import PIPE, Popen
Rick Dean47262da2009-07-08 16:17:17 -050012from datetime import datetime, timedelta
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -050013
Alex Gaynor791212d2015-09-05 15:46:08 -040014import pytest
15
Alex Gaynore7f51982016-09-11 11:48:14 -040016from six import binary_type
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050017
Alex Gaynor9939ba12017-06-25 16:28:24 -040018from cryptography import x509
Paul Kehrer72d968b2016-07-29 15:31:04 +080019from cryptography.hazmat.backends.openssl.backend import backend
20from cryptography.hazmat.primitives import serialization
21from cryptography.hazmat.primitives.asymmetric import rsa
22
Alex Gaynore466bc92017-07-06 23:43:47 -040023import flaky
24
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -050025from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
Jean-Paul Calderone78381d22008-03-06 23:35:22 -050026from OpenSSL.crypto import X509, X509Type, X509Name, X509NameType
Alex Gaynor31287502015-09-05 16:11:27 -040027from OpenSSL.crypto import (
Dan Sully44e767a2016-06-04 18:05:27 -070028 X509Store,
29 X509StoreFlags,
30 X509StoreType,
31 X509StoreContext,
32 X509StoreContextError
Alex Gaynor31287502015-09-05 16:11:27 -040033)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070034from OpenSSL.crypto import X509Req, X509ReqType
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -050035from OpenSSL.crypto import X509Extension, X509ExtensionType
Rick Dean5b7b6372009-04-01 11:34:06 -050036from OpenSSL.crypto import load_certificate, load_privatekey
Cory Benfield6492f7c2015-10-27 16:57:58 +090037from OpenSSL.crypto import load_publickey, dump_publickey
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -040038from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
Jean-Paul Calderone71919862009-04-01 13:01:19 -040039from OpenSSL.crypto import dump_certificate, load_certificate_request
40from OpenSSL.crypto import dump_certificate_request, dump_privatekey
Alex Chanb00ede22017-01-30 07:24:40 +000041from OpenSSL.crypto import PKCS7, PKCS7Type, load_pkcs7_data
Jean-Paul Calderone9178ee62010-01-25 17:55:30 -050042from OpenSSL.crypto import PKCS12, PKCS12Type, load_pkcs12
Dominic Chenf05b2122015-10-13 16:32:35 +000043from OpenSSL.crypto import CRL, Revoked, dump_crl, load_crl
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -040044from OpenSSL.crypto import NetscapeSPKI, NetscapeSPKIType
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040045from OpenSSL.crypto import (
46 sign, verify, get_elliptic_curve, get_elliptic_curves)
Hynek Schlawackf0e66852015-10-16 20:18:38 +020047
Alex Chanb00ede22017-01-30 07:24:40 +000048from .util import EqualityTestsMixin, is_consistent_type, WARNING_TYPE_EXPECTED
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040049
Alex Gaynoraceb3e22015-09-05 12:00:22 -040050
Jean-Paul Calderone9da338d2011-05-04 11:40:54 -040051def normalize_privatekey_pem(pem):
52 return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
53
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040054
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050055GOOD_CIPHER = "blowfish"
56BAD_CIPHER = "zippers"
57
Anthony Alba2ce737f2015-12-04 11:04:56 +080058GOOD_DIGEST = "SHA1"
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050059BAD_DIGEST = "monkeys"
60
Paul Kehrera40898b2017-06-11 16:30:58 -100061old_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
Rick Dean94e46fd2009-07-18 14:51:24 -050062MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
63BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
64ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
65NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
66MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
67ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
68urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
692xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
701dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
71FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
72VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
73BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
74b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
75AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
76hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
77w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
78-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -040079"""
Rick Dean94e46fd2009-07-18 14:51:24 -050080
Paul Kehrera40898b2017-06-11 16:30:58 -100081root_cert_pem = b"""-----BEGIN CERTIFICATE-----
82MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
83BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
84ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
85WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
86BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
87bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
88bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
89LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
90onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
91LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
92yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
93aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
94Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
95R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
96gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
97lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
98-----END CERTIFICATE-----
99"""
100
Alex Gaynore7f51982016-09-11 11:48:14 -0400101root_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500102MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
103jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
1043claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
105AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
106yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
1076JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
108BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
109u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
110PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
111I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
112ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
1136AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
114cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
115-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400116"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500117
Alex Gaynore7f51982016-09-11 11:48:14 -0400118intermediate_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700119MIICVzCCAcCgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQENBQAw
120WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
121DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTQw
122ODI4MDIwNDA4WhcNMjQwODI1MDIwNDA4WjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
123dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
124MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIGfMA0GCSqGSIb3DQEB
125AQUAA4GNADCBiQKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmK
126FGIbljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT
12721H2qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwID
128AQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDQUAA4GBAPIWSkLX
129QRMApOjjyC+tMxumT5e2pMqChHmxobQK4NMdrf2VCx+cRT6EmY8sK3/Xl/X8UBQ+
1309n5zXb1ZwhW/sTWgUvmOceJ4/XVs9FkdWOOn1J0XBch9ZIiFe/s5ASIgG7fUdcUF
1319mAWS6FK2ca3xIh5kIupCXOFa0dPvlw/YUFT
132-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400133"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700134
Alex Gaynore7f51982016-09-11 11:48:14 -0400135intermediate_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700136MIICWwIBAAKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmKFGIb
137ljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT21H2
138qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwIDAQAB
139AoGAfSZVV80pSeOKHTYfbGdNY/jHdU9eFUa/33YWriXU+77EhpIItJjkRRgivIfo
140rhFJpBSGmDLblaqepm8emsXMeH4+2QzOYIf0QGGP6E6scjTt1PLqdqKfVJ1a2REN
141147cujNcmFJb/5VQHHMpaPTgttEjlzuww4+BCDPsVRABWrkCQQD3loH36nLoQTtf
142+kQq0T6Bs9/UWkTAGo0ND81ALj0F8Ie1oeZg6RNT96RxZ3aVuFTESTv6/TbjWywO
143wdzlmV1vAkEA38rTJ6PTwaJlw5OttdDzAXGPB9tDmzh9oSi7cHwQQXizYd8MBYx4
144sjHUKD3dCQnb1dxJFhd3BT5HsnkRMbVZXQJAbXduH17ZTzcIOXc9jHDXYiFVZV5D
14552vV0WCbLzVCZc3jMrtSUKa8lPN5EWrdU3UchWybyG0MR5mX8S5lrF4SoQJAIyUD
146DBKaSqpqONCUUx1BTFS9FYrFjzbL4+c1qHCTTPTblt8kUCrDOZjBrKAqeiTmNSum
147/qUot9YUBF8m6BuGsQJATHHmdFy/fG1VLkyBp49CAa8tN3Z5r/CgTznI4DfMTf4C
148NbRHn2UmYlwQBa+L5lg9phewNe8aEwpPyPLoV85U8Q==
149-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400150"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700151
Alex Gaynore7f51982016-09-11 11:48:14 -0400152server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000153MIICJDCCAY2gAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
154BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
155VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMTA1
156N1oXDTM3MDYwNzAwMTA1N1owGDEWMBQGA1UEAwwNbG92ZWx5IHNlcnZlcjCBnzAN
157BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvqb4brndXS2kEL84qXbZXE6LYK+UrhNi
15870sdIM/24NVN7tXkPlOXqrMWhFHHml+aeSpPkH5b1vKnY1TcULmEubnNICtvjmZ5
159SGMQn+J+RmBs1SMd0EgY/0wBBQdlrlYp2QYgm8YC+zxTNSqWvhMFZAgHbj6Un5SS
160T8JGBqytjB0CAwEAAaM2MDQwHQYDVR0OBBYEFINVdy1eIfFJDAkk51QJEo3IfgSu
161MBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4GBAGki1K6WgHHJ
162qC6aY2EowjaWOXLO6jUZIhGk7BA7vMRfNug429AOZ4m5F6OQhzmJmlw67Jyu2FeI
163h0VtBuQoHPtjqZXF59oX6hMMmGLMs9pV0UA3fJs5MYA4/V5ZcQy0Ie0QoJNejLzE
1646V1Qz1rRTYLUyEcpI7ZCmBg2KQQI8YZI
Rick Dean94e46fd2009-07-18 14:51:24 -0500165-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400166"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500167
Alex Gaynore7f51982016-09-11 11:48:14 -0400168server_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500169MIICWwIBAAKBgQC+pvhuud1dLaQQvzipdtlcTotgr5SuE2LvSx0gz/bg1U3u1eQ+
170U5eqsxaEUceaX5p5Kk+QflvW8qdjVNxQuYS5uc0gK2+OZnlIYxCf4n5GYGzVIx3Q
171SBj/TAEFB2WuVinZBiCbxgL7PFM1Kpa+EwVkCAduPpSflJJPwkYGrK2MHQIDAQAB
172AoGAbwuZ0AR6JveahBaczjfnSpiFHf+mve2UxoQdpyr6ROJ4zg/PLW5K/KXrC48G
173j6f3tXMrfKHcpEoZrQWUfYBRCUsGD5DCazEhD8zlxEHahIsqpwA0WWssJA2VOLEN
174j6DuV2pCFbw67rfTBkTSo32ahfXxEKev5KswZk0JIzH3ooECQQDgzS9AI89h0gs8
175Dt+1m11Rzqo3vZML7ZIyGApUzVan+a7hbc33nbGRkAXjHaUBJO31it/H6dTO+uwX
176msWwNG5ZAkEA2RyFKs5xR5USTFaKLWCgpH/ydV96KPOpBND7TKQx62snDenFNNbn
177FwwOhpahld+vqhYk+pfuWWUpQciE+Bu7ZQJASjfT4sQv4qbbKK/scePicnDdx9th
1784e1EeB9xwb+tXXXUo/6Bor/AcUNwfiQ6Zt9PZOK9sR3lMZSsP7rMi7kzuQJABie6
1791sXXjFH7nNJvRG4S39cIxq8YRYTy68II/dlB2QzGpKxV/POCxbJ/zu0CU79tuYK7
180NaeNCFfH3aeTrX0LyQJAMBWjWmeKM2G2sCExheeQK0ROnaBC8itCECD4Jsve4nqf
181r50+LF74iLXFwqysVCebPKMOpDWp/qQ1BbJQIPs7/A==
182-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400183""")
Rick Dean94e46fd2009-07-18 14:51:24 -0500184
Alex Gaynore7f51982016-09-11 11:48:14 -0400185intermediate_server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700186MIICWDCCAcGgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQENBQAw
187ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
188CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
189biBEaWVnbzAeFw0xNDA4MjgwMjEwNDhaFw0yNDA4MjUwMjEwNDhaMG4xHTAbBgNV
190BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
191CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
192biBEaWVnbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqpJZygd+w1faLOr1
193iOAmbBhx5SZWcTCZ/ZjHQTJM7GuPT624QkqsixFghRKdDROwpwnAP7gMRukLqiy4
194+kRuGT5OfyGggL95i2xqA+zehjj08lSTlvGHpePJgCyTavIy5+Ljsj4DKnKyuhxm
195biXTRrH83NDgixVkObTEmh/OVK0CAwEAATANBgkqhkiG9w0BAQ0FAAOBgQBa0Npw
196UkzjaYEo1OUE1sTI6Mm4riTIHMak4/nswKh9hYup//WVOlr/RBSBtZ7Q/BwbjobN
1973bfAtV7eSAqBsfxYXyof7G1ALANQERkq3+oyLP1iVt08W1WOUlIMPhdCF/QuCwy6
198x9MJLhUCGLJPM+O2rAPWVD9wCmvq10ALsiH3yA==
199-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400200"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700201
Alex Gaynore7f51982016-09-11 11:48:14 -0400202intermediate_server_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700203MIICXAIBAAKBgQCqklnKB37DV9os6vWI4CZsGHHlJlZxMJn9mMdBMkzsa49PrbhC
204SqyLEWCFEp0NE7CnCcA/uAxG6QuqLLj6RG4ZPk5/IaCAv3mLbGoD7N6GOPTyVJOW
2058Yel48mALJNq8jLn4uOyPgMqcrK6HGZuJdNGsfzc0OCLFWQ5tMSaH85UrQIDAQAB
206AoGAIQ594j5zna3/9WaPsTgnmhlesVctt4AAx/n827DA4ayyuHFlXUuVhtoWR5Pk
2075ezj9mtYW8DyeCegABnsu2vZni/CdvU6uiS1Hv6qM1GyYDm9KWgovIP9rQCDSGaz
208d57IWVGxx7ODFkm3gN5nxnSBOFVHytuW1J7FBRnEsehRroECQQDXHFOv82JuXDcz
209z3+4c74IEURdOHcbycxlppmK9kFqm5lsUdydnnGW+mvwDk0APOB7Wg7vyFyr393e
210dpmBDCzNAkEAyv6tVbTKUYhSjW+QhabJo896/EqQEYUmtMXxk4cQnKeR/Ao84Rkf
211EqD5IykMUfUI0jJU4DGX+gWZ10a7kNbHYQJAVFCuHNFxS4Cpwo0aqtnzKoZaHY/8
212X9ABZfafSHCtw3Op92M+7ikkrOELXdS9KdKyyqbKJAKNEHF3LbOfB44WIQJAA2N4
2139UNNVUsXRbElEnYUS529CdUczo4QdVgQjkvk5RiPAUwSdBd9Q0xYnFOlFwEmIowg
214ipWJWe0aAlP18ZcEQQJBAL+5lekZ/GUdQoZ4HAsN5a9syrzavJ9VvU1KOOPorPZK
215nMRZbbQgP+aSB7yl6K0gaLaZ8XaK0pjxNBh6ASqg9f4=
216-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400217"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700218
Alex Gaynore7f51982016-09-11 11:48:14 -0400219client_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000220MIICIjCCAYugAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
221BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
222VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMDQx
223M1oXDTM3MDYwNzAwMDQxM1owFjEUMBIGA1UEAwwLdWdseSBjbGllbnQwgZ8wDQYJ
224KoZIhvcNAQEBBQADgY0AMIGJAoGBAMBmH9JG02bme0xPipvpjMSlOugyWrauf4at
225EdGJn7GQLD8IY2Fu0+Kvv9DFpSPboFKZCsfDVsYoRs+xaJbtt1dJ6ymX7EqKS7gb
2268q+eeZZ14keqyJd5Rm2q6swQtw9ADD3E8cS6GqpQm+8SgxOycISoYz7sO1ugJFqN
227jId+W4BFAgMBAAGjNjA0MB0GA1UdDgQWBBSDVXctXiHxSQwJJOdUCRKNyH4ErjAT
228BgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQAMqcHyweaCOZNN
229dWQQOsBKQlL5wqVVZwucHPWqobjxpULKy9gS2ha2zbgkXcB/BnBOSwe0Fm+MJV0T
230NbnTghcGJNpEH7VKn4xSLvIGZmnZZWgxeIB16z4GhpkK2fShBJ+6GKZjsgjT0lSH
231JRgjHbWutZfZvbSHXr9n7PIphG1Ojg==
Rick Dean94e46fd2009-07-18 14:51:24 -0500232-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400233"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500234
Alex Gaynore7f51982016-09-11 11:48:14 -0400235client_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500236MIICXgIBAAKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2rn+GrRHRiZ+xkCw/CGNh
237btPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xKiku4G/KvnnmWdeJHqsiX
238eUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7DtboCRajYyHfluARQIDAQAB
239AoGATkZ+NceY5Glqyl4mD06SdcKfV65814vg2EL7V9t8+/mi9rYL8KztSXGlQWPX
240zuHgtRoMl78yQ4ZJYOBVo+nsx8KZNRCEBlE19bamSbQLCeQMenWnpeYyQUZ908gF
241h6L9qsFVJepgA9RDgAjyDoS5CaWCdCCPCH2lDkdcqC54SVUCQQDseuduc4wi8h4t
242V8AahUn9fn9gYfhoNuM0gdguTA0nPLVWz4hy1yJiWYQe0H7NLNNTmCKiLQaJpAbb
243TC6vE8C7AkEA0Ee8CMJUc20BnGEmxwgWcVuqFWaKCo8jTH1X38FlATUsyR3krjW2
244dL3yDD9NwHxsYP7nTKp/U8MV7U9IBn4y/wJBAJl7H0/BcLeRmuJk7IqJ7b635iYB
245D/9beFUw3MUXmQXZUfyYz39xf6CDZsu1GEdEC5haykeln3Of4M9d/4Kj+FcCQQCY
246si6xwT7GzMDkk/ko684AV3KPc/h6G0yGtFIrMg7J3uExpR/VdH2KgwMkZXisSMvw
247JJEQjOMCVsEJlRk54WWjAkEAzoZNH6UhDdBK5F38rVt/y4SEHgbSfJHIAmPS32Kq
248f6GGcfNpip0Uk7q7udTKuX7Q/buZi/C4YW7u3VKAquv9NA==
249-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400250""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400251
Alex Gaynore7f51982016-09-11 11:48:14 -0400252cleartextCertificatePEM = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000253MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400254BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
Paul Kehrera40898b2017-06-11 16:30:58 -1000255ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
256WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
257BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
258bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
259bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
260LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
261onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
262LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
263yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
264aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
265Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
266R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
267gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
268lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400269-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400270"""
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400271
Alex Gaynore7f51982016-09-11 11:48:14 -0400272cleartextPrivateKeyPEM = normalize_privatekey_pem(b"""\
Jean-Paul Calderoned50d2042011-05-04 17:00:49 -0400273-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400274MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
275jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
2763claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
277AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
278yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
2796JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
280BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
281u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
282PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
283I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
284ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
2856AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
286cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
287-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400288""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400289
Alex Gaynore7f51982016-09-11 11:48:14 -0400290cleartextCertificateRequestPEM = b"""-----BEGIN CERTIFICATE REQUEST-----
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -0400291MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
292EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
293ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
294BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
295E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
296xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
297gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
298Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
299oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
300-----END CERTIFICATE REQUEST-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400301"""
Rick Dean5b7b6372009-04-01 11:34:06 -0500302
Alex Gaynore7f51982016-09-11 11:48:14 -0400303encryptedPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400304Proc-Type: 4,ENCRYPTED
305DEK-Info: DES-EDE3-CBC,9573604A18579E9E
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400306
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400307SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
308a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
3098+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
310mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
311+00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
312fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
313tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
314rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
315gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
316o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
3177SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
318MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
31911n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
320-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400321"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400322
Alex Gaynore7f51982016-09-11 11:48:14 -0400323encryptedPrivateKeyPEMPassphrase = b"foobar"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400324
Cory Benfield6492f7c2015-10-27 16:57:58 +0900325
Alex Gaynore7f51982016-09-11 11:48:14 -0400326cleartextPublicKeyPEM = b"""-----BEGIN PUBLIC KEY-----
Cory Benfield6492f7c2015-10-27 16:57:58 +0900327MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxszlc+b71LvlLS0ypt/l
328gT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZOtPclNY823Q4pErMTSWC
32990qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLjBuUIkQzEKEFV+8taiRV+
330ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPrUQqYQUEiTmVhh4FBUKZ5
331XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV215k4TeHMFYE5RG0KYAS
3328Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6HXRpQCyASzEG7bgtROLhL
333ywIDAQAB
334-----END PUBLIC KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400335"""
Cory Benfield6492f7c2015-10-27 16:57:58 +0900336
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400337# Some PKCS#7 stuff. Generated with the openssl command line:
338#
339# openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
340#
341# with a certificate and key (but the key should be irrelevant) in s.pem
Alex Gaynore7f51982016-09-11 11:48:14 -0400342pkcs7Data = b"""\
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400343-----BEGIN PKCS7-----
344MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
345BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
346A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
347MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
348cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
349A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
350HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
351SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
352zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
353LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
354A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
35565w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
356Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
357Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
358bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
359VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
360/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
361Ho4EzbYCOaEAMQA=
362-----END PKCS7-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400363"""
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400364
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700365pkcs7DataASN1 = base64.b64decode(b"""
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700366MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
367BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
368A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
369MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
370cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
371A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
372HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
373SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
374zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
375LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
376A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
37765w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
378Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
379Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
380bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
381VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
382/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
383Ho4EzbYCOaEAMQA=
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700384""")
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700385
Alex Gaynore7f51982016-09-11 11:48:14 -0400386crlData = b"""\
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -0500387-----BEGIN X509 CRL-----
388MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
389SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
390D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
391MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
392MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
3934dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
3940yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
395vrzEeLDRiiPl92dyyWmu
396-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400397"""
Jean-Paul Calderonee890db32010-08-22 16:55:15 -0400398
Alex Gaynore7f51982016-09-11 11:48:14 -0400399crlDataUnsupportedExtension = b"""\
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400400-----BEGIN X509 CRL-----
401MIIGRzCCBS8CAQIwDQYJKoZIhvcNAQELBQAwJzELMAkGA1UEBhMCVVMxGDAWBgNV
402BAMMD2NyeXB0b2dyYXBoeS5pbxgPMjAxNTAxMDEwMDAwMDBaGA8yMDE2MDEwMTAw
403MDAwMFowggTOMBQCAQAYDzIwMTUwMTAxMDAwMDAwWjByAgEBGA8yMDE1MDEwMTAw
404MDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAn
405MQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQD
406CgEAMHICAQIYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAw
407MDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlw
408dG9ncmFwaHkuaW8wCgYDVR0VBAMKAQEwcgIBAxgPMjAxNTAxMDEwMDAwMDBaMFww
409GAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTArpCkwJzELMAkGA1UE
410BhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNVHRUEAwoBAjByAgEE
411GA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQG
412A1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5
413LmlvMAoGA1UdFQQDCgEDMHICAQUYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQR
414GA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgw
415FgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQQwcgIBBhgPMjAxNTAx
416MDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTAr
417pCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNV
418HRUEAwoBBTByAgEHGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAx
419MDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwP
420Y3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEGMHICAQgYDzIwMTUwMTAxMDAwMDAw
421WjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJ
422BgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQgw
423cgIBCRgPMjAxNTAxMDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAw
424WjA0BgNVHR0ELTArpCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dy
425YXBoeS5pbzAKBgNVHRUEAwoBCTByAgEKGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNV
426HRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJV
427UzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEKMC4CAQsYDzIw
428MTUwMTAxMDAwMDAwWjAYMAoGA1UdFQQDCgEBMAoGAyoDBAQDCgEAMA0GCSqGSIb3
429DQEBCwUAA4IBAQBTaloHlPaCZzYee8LxkWej5meiqxQVNWFoVdjesroa+f1FRrH+
430drRU60Nq97KCKf7f9GNN/J3ZIlQmYhmuDqh12f+XLpotoj1ZRfBz2hjFCkJlv+2c
431oWWGNHgA70ndFoVtcmX088SYpX8E3ARATivS4q2h9WlwV6rO93mhg3HGIe3JpcK4
4327BcW6Poi/ut/zsDOkVbI00SqaujRpdmdCTht82MH3ztjyDkI9KYaD/YEweKSrWOz
433SdEILd164bfBeLuplVI+xpmTEMVNpXBlSXl7+xIw9Vk7p7Q1Pa3k/SvhOldYCm6y
434C1xAg/AAq6w78yzYt18j5Mj0s6eeHi1YpHKw
435-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400436"""
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400437
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400438
439# A broken RSA private key which can be used to test the error path through
440# PKey.check.
Alex Gaynore7f51982016-09-11 11:48:14 -0400441inconsistentPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400442MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
4435kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
444OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
445zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
446nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
447HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
448oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
449-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400450"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400451
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400452# certificate with NULL bytes in subjectAltName and common name
453
Alex Gaynore7f51982016-09-11 11:48:14 -0400454nulbyteSubjectAltNamePEM = b"""-----BEGIN CERTIFICATE-----
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400455MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
456DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
457eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
458RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
459ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
460NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
461DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
462ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
463ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
464hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
465BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
466pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
467vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
468KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
469oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
47008LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
471HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
472BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
473Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
474bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
475AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
476i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
477HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
478kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
479VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
480RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
Alex Gaynore7f51982016-09-11 11:48:14 -0400481-----END CERTIFICATE-----"""
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400482
Alex Gaynore7f51982016-09-11 11:48:14 -0400483large_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Colleen Murphye09399b2016-03-01 17:40:49 -0800484MIIJYgIBAAKCAg4AtRua8eIeevRfsj+fkcHr1vmse7Kgb+oX1ssJAvCb1R7JQMnH
485hNDjDP6b3vEkZuPUzlDHymP+cNkXvvi4wJ4miVbO3+SeU4Sh+jmsHeHzGIXat9xW
4869PFtuPM5FQq8zvkY8aDeRYmYwN9JKu4/neMBCBqostYlTEWg+bSytO/qWnyHTHKh
487g0GfaDdqUQPsGQw+J0MgaYIjQOCVASHAPlzbDQLCtuOb587rwTLkZA2GwoHB/LyJ
488BwT0HHgBaiObE12Vs6wi2en0Uu11CiwEuK1KIBcZ2XbE6eApaZa6VH9ysEmUxPt7
489TqyZ4E2oMIYaLPNRxuvozdwTlj1svI1k1FrkaXGc5MTjbgigPMKjIb0T7b/4GNzt
490DhP1LvAeUMnrEi3hJJrcJPXHPqS8/RiytR9xQQW6Sdh4LaA3f9MQm3WSevWage3G
491P8YcCLssOVKsArDjuA52NF5LmYuAeUzXprm4ITDi2oO+0iFBpFW6VPEK4A9vO0Yk
492M/6Wt6tG8zyWhaSH1zFUTwfQ9Yvjyt5w1lrUaAJuoTpwbMVZaDJaEhjOaXU0dyPQ
493jOsePDOQcU6dkeTWsQ3LsHPEEug/X6819TLG5mb3V7bvV9nPFBfTJSCEG794kr90
494XgZfIN71FrdByxLerlbuJI21pPs/nZi9SXi9jAWeiS45/azUxMsyYgJArui+gjq7
495sV1pWiBm6/orAgMBAAECggINQp5L6Yu+oIXBqcSjgq8tfF9M5hd30pLuf/EheHZf
496LA7uAqn2fVGFI2OInIJhXIOT5OxsAXO0xXfltzawZxIFpOFMqajj4F7aYjvSpw9V
497J4EdSiJ/zgv8y1qUdbwEZbHVThRZjoSlrtSzilonBoHZAE0mHtqMz7iRFSk1zz6t
498GunRrvo/lROPentf3TsvHquVNUYI5yaapyO1S7xJhecMIIYSb8nbsHI54FBDGNas
4996mFmpPwI/47/6HTwOEWupnn3NicsjrHzUInOUpaMig4cRR+aP5bjqg/ty8xI8AoN
500evEmCytiWTc+Rvbp1ieN+1jpjN18PjUk80/W7qioHUDt4ieLic8uxWH2VD9SCEnX
501Mpi9tA/FqoZ+2A/3m1OfrY6jiZVE2g+asi9lCK7QVWL39eK82H4rPvtp0/dyo1/i
502ZZz68TXg+m8IgEZcp88hngbkuoTTzpGE73QuPKhGA1uMIimDdqPPB5WP76q+03Oi
503IRR5DfZnqPERed49by0enJ7tKa/gFPZizOV8ALKr0Dp+vfAkxGDLPLBLd2A3//tw
504xg0Q/wltihHSBujv4nYlDXdc5oYyMYZ+Lhc/VuOghHfBq3tgEQ1ECM/ofqXEIdy7
505nVcpZn3Eeq8Jl5CrqxE1ee3NxlzsJHn99yGQpr7mOhW/psJF3XNz80Meg3L4m1T8
506sMBK0GbaassuJhdzb5whAoIBBw48sx1b1WR4XxQc5O/HjHva+l16i2pjUnOUTcDF
507RWmSbIhBm2QQ2rVhO8+fak0tkl6ZnMWW4i0U/X5LOEBbC7+IS8bO3j3Revi+Vw5x
508j96LMlIe9XEub5i/saEWgiz7maCvfzLFU08e1OpT4qPDpP293V400ubA6R7WQTCv
509pBkskGwHeu0l/TuKkVqBFFUTu7KEbps8Gjg7MkJaFriAOv1zis/umK8pVS3ZAM6e
5108w5jfpRccn8Xzta2fRwTB5kCmfxdDsY0oYGxPLRAbW72bORoLGuyyPp/ojeGwoik
511JX9RttErc6FjyZtks370Pa8UL5QskyhMbDhrZW2jFD+RXYM1BrvmZRjbAoIBBwy4
512iFJpuDfytJfz1MWtaL5DqEL/kmiZYAXl6hifNhGu5GAipVIIGsDqEYW4i+VC15aa
5137kOCwz/I5zsB3vSDW96IRs4wXtqEZSibc2W/bqfVi+xcvPPl1ZhQ2EAwa4D/x035
514kyf20ffWOU+1yf2cnijzqs3IzlveUm+meLw5s3Rc+iG7DPWWeCoe1hVwANI1euNc
515pqKwKY905yFyjOje2OgiEU2kS4YME4zGeBys8yo7E42hNnN2EPK6xkkUqzdudLLQ
5168OUlKRTc8AbIf3XG1rpA4VUpTv3hhxGGwCRy6If8zgZQsNYchgNztRGk72Gcb8Dm
517vFSEN3ZtwxU64G3YZzntdcr2WPzxAoIBBw30g6Fgdb/gmVnOpL0//T0ePNDKIMPs
518jVJLaRduhoZgB1Bb9qPUPX0SzRzLZtg1tkZSDjBDoHmOHJfhxUaXt+FLCPPbrE4t
519+nq9n/nBaMM779w9ClqhqLOyGrwKoxjSmhi+TVEHyIxCbXMvPHVHfX9WzxjbcGrN
520ZvRaEVZWo+QlIX8yqdSwqxLk1WtAIRzvlcj7NKum8xBxPed6BNFep/PtgIAmoLT5
521L8wb7EWb2iUdc2KbZ4OaY51lDScqpATgXu3WjXfM+Q52G0mX6Wyd0cjlL711Zrjb
522yLbiueZT94lgIHHRRKtKc8CEqcjkQV5OzABS3P/gQSfgZXBdLKjOpTnKDUq7IBeH
523AoIBBweAOEIAPLQg1QRUrr3xRrYKRwlakgZDii9wJt1l5AgBTICzbTA1vzDJ1JM5
524AqSpCV6w9JWyYVcXK+HLdKBRZLaPPNEQDJ5lOxD6uMziWGl2rg8tj+1xNMWfxiPz
525aTCjoe4EoBUMoTq2gwzRcM2usEQNikXVhnj9Wzaivsaeb4bJ3GRPW5DkrO6JSEtT
526w+gvyMqQM2Hy5k7E7BT46sXVwaj/jZxuqGnebRixXtnp0WixdRIqYWUr1UqLf6hQ
527G7WP2BgoxCMaCmNW8+HMD/xuxucEotoIhZ+GgJKBFoNnjl3BX+qxYdSe9RbL/5Tr
5284It6Jxtj8uETJXEbv9Cg6v1agWPS9YY8RLTBAoIBBwrU2AsAUts6h1LgGLKK3UWZ
529oLH5E+4o+7HqSGRcRodVeN9NBXIYdHHOLeEG6YNGJiJ3bFP5ZQEu9iDsyoFVKJ9O
530Mw/y6dKZuxOCZ+X8FopSROg3yWfdOpAm6cnQZp3WqLNX4n/Q6WvKojfyEiPphjwT
5310ymrUJELXLWJmjUyPoAk6HgC0Gs28ZnEXbyhx7CSbZNFyCU/PNUDZwto3GisIPD3
532le7YjqHugezmjMGlA0sDw5aCXjfbl74vowRFYMO6e3ItApfSRgNV86CDoX74WI/5
533AYU/QVM4wGt8XGT2KwDFJaxYGKsGDMWmXY04dS+WPuetCbouWUusyFwRb9SzFave
534vYeU7Ab/
Alex Gaynore7f51982016-09-11 11:48:14 -0400535-----END RSA PRIVATE KEY-----"""
Colleen Murphye09399b2016-03-01 17:40:49 -0800536
Paul Kehrer72d968b2016-07-29 15:31:04 +0800537ec_private_key_pem = b"""-----BEGIN PRIVATE KEY-----
538MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgYirTZSx+5O8Y6tlG
539cka6W6btJiocdrdolfcukSoTEk+hRANCAAQkvPNu7Pa1GcsWU4v7ptNfqCJVq8Cx
540zo0MUVPQgwJ3aJtNM1QMOQUayCrRwfklg+D/rFSUwEUqtZh7fJDiFqz3
541-----END PRIVATE KEY-----
542"""
543
Paul Kehrer59d26252017-07-20 10:45:54 +0200544ec_root_key_pem = b"""-----BEGIN EC PRIVATE KEY-----
545MIGlAgEBBDEAz/HOBFPYLB0jLWeTpJn4Yc4m/C4mdWymVHBjOmnwiPHKT326iYN/
546ZhmSs+RM94RsoAcGBSuBBAAioWQDYgAEwE5vDdla/nLpWAPAQ0yFGqwLuw4BcN2r
547U+sKab5EAEHzLeceRa8ffncYdCXNoVsBcdob1y66CFZMEWLetPTmGapyWkBAs6/L
5488kUlkU9OsE+7IVo4QQJkgV5gM+Dim1XE
549-----END EC PRIVATE KEY-----
550"""
551
552ec_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
553MIICLTCCAbKgAwIBAgIMWW/hwTl6ufz6/WkCMAoGCCqGSM49BAMDMFgxGDAWBgNV
554BAMTD1Rlc3RpbmcgUm9vdCBDQTEQMA4GA1UEChMHVGVzdGluZzEQMA4GA1UEBxMH
555Q2hpY2FnbzELMAkGA1UECBMCSUwxCzAJBgNVBAYTAlVTMCAXDTE3MDcxOTIyNDgz
556M1oYDzk5OTkxMjMxMjM1OTU5WjBYMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0Ex
557EDAOBgNVBAoTB1Rlc3RpbmcxEDAOBgNVBAcTB0NoaWNhZ28xCzAJBgNVBAgTAklM
558MQswCQYDVQQGEwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABMBObw3ZWv5y6VgD
559wENMhRqsC7sOAXDdq1PrCmm+RABB8y3nHkWvH353GHQlzaFbAXHaG9cuughWTBFi
5603rT05hmqclpAQLOvy/JFJZFPTrBPuyFaOEECZIFeYDPg4ptVxKNDMEEwDwYDVR0T
561AQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwQAMB0GA1UdDgQWBBSoTrF0H2m8RDzB
562MnY2KReEPfz7ZjAKBggqhkjOPQQDAwNpADBmAjEA3+G1oVCxGjYX4iUN93QYcNHe
563e3fJQJwX9+KsHRut6qNZDUbvRbtO1YIAwB4UJZjwAjEAtXCPURS5A4McZHnSwgTi
564Td8GMrwKz0557OxxtKN6uVVy4ACFMqEw0zN/KJI1vxc9
565-----END CERTIFICATE-----"""
566
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400567
Alex Chanc6077062016-11-18 13:53:39 +0000568@pytest.fixture
569def x509_data():
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400570 """
Alex Chanc6077062016-11-18 13:53:39 +0000571 Create a new private key and start a certificate request (for a test
572 to finish in one way or another).
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400573 """
Alex Chanc6077062016-11-18 13:53:39 +0000574 # Basic setup stuff to generate a certificate
575 pkey = PKey()
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400576 pkey.generate_key(TYPE_RSA, 512)
Alex Chanc6077062016-11-18 13:53:39 +0000577 req = X509Req()
578 req.set_pubkey(pkey)
579 # Authority good you have.
580 req.get_subject().commonName = "Yoda root CA"
581 x509 = X509()
582 subject = x509.get_subject()
583 subject.commonName = req.get_subject().commonName
584 x509.set_issuer(subject)
585 x509.set_pubkey(pkey)
586 now = datetime.now()
587 expire = datetime.now() + timedelta(days=100)
588 x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
589 x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
590 yield pkey, x509
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400591
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400592
Alex Chanc6077062016-11-18 13:53:39 +0000593class TestX509Ext(object):
594 """
595 Tests for `OpenSSL.crypto.X509Extension`.
596 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -0800597
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400598 def test_str(self):
599 """
Alex Chanc6077062016-11-18 13:53:39 +0000600 The string representation of `X509Extension` instances as
601 returned by `str` includes stuff.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400602 """
603 # This isn't necessarily the best string representation. Perhaps it
604 # will be changed/improved in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000605 assert (
606 str(X509Extension(b'basicConstraints', True, b'CA:false')) ==
607 'CA:FALSE'
608 )
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400609
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400610 def test_type(self):
611 """
Alex Chanc6077062016-11-18 13:53:39 +0000612 `X509Extension` and `X509ExtensionType` refer to the same type object
613 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400614 """
Alex Chanc6077062016-11-18 13:53:39 +0000615 assert X509Extension is X509ExtensionType
616 assert is_consistent_type(
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400617 X509Extension,
Alex Gaynore7f51982016-09-11 11:48:14 -0400618 'X509Extension', b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400619
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500620 def test_construction(self):
621 """
Alex Chanc6077062016-11-18 13:53:39 +0000622 `X509Extension` accepts an extension type name, a critical flag,
623 and an extension value and returns an `X509ExtensionType` instance.
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500624 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400625 basic = X509Extension(b'basicConstraints', True, b'CA:true')
Alex Chanc6077062016-11-18 13:53:39 +0000626 assert isinstance(basic, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500627
Alex Chanc6077062016-11-18 13:53:39 +0000628 comment = X509Extension(b'nsComment', False, b'pyOpenSSL unit test')
629 assert isinstance(comment, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500630
Alex Chanc6077062016-11-18 13:53:39 +0000631 @pytest.mark.parametrize('type_name, critical, value', [
632 (b'thisIsMadeUp', False, b'hi'),
633 (b'basicConstraints', False, b'blah blah'),
Jean-Paul Calderone391585f2008-12-31 14:36:31 -0500634
Jean-Paul Calderone2ee1e7c2008-12-31 14:58:38 -0500635 # Exercise a weird one (an extension which uses the r2i method). This
636 # exercises the codepath that requires a non-NULL ctx to be passed to
637 # X509V3_EXT_nconf. It can't work now because we provide no
638 # configuration database. It might be made to work in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000639 (b'proxyCertInfo', True,
640 b'language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')
641 ])
642 def test_invalid_extension(self, type_name, critical, value):
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500643 """
Alex Chanc6077062016-11-18 13:53:39 +0000644 `X509Extension` raises something if it is passed a bad
645 extension name or value.
646 """
647 with pytest.raises(Error):
648 X509Extension(type_name, critical, value)
649
650 @pytest.mark.parametrize('critical_flag', [True, False])
651 def test_get_critical(self, critical_flag):
652 """
653 `X509ExtensionType.get_critical` returns the value of the
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500654 extension's critical flag.
655 """
Alex Chanc6077062016-11-18 13:53:39 +0000656 ext = X509Extension(b'basicConstraints', critical_flag, b'CA:true')
657 assert ext.get_critical() == critical_flag
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500658
Alex Chanc6077062016-11-18 13:53:39 +0000659 @pytest.mark.parametrize('short_name, value', [
660 (b'basicConstraints', b'CA:true'),
661 (b'nsComment', b'foo bar'),
662 ])
663 def test_get_short_name(self, short_name, value):
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500664 """
Alex Chanc6077062016-11-18 13:53:39 +0000665 `X509ExtensionType.get_short_name` returns a string giving the
Alex Gaynor31287502015-09-05 16:11:27 -0400666 short type name of the extension.
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500667 """
Alex Chanc6077062016-11-18 13:53:39 +0000668 ext = X509Extension(short_name, True, value)
669 assert ext.get_short_name() == short_name
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500670
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400671 def test_get_data(self):
672 """
Alex Chanc6077062016-11-18 13:53:39 +0000673 `X509Extension.get_data` returns a string giving the data of
Alex Gaynor31287502015-09-05 16:11:27 -0400674 the extension.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400675 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400676 ext = X509Extension(b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400677 # Expect to get back the DER encoded form of CA:true.
Alex Chanc6077062016-11-18 13:53:39 +0000678 assert ext.get_data() == b'0\x03\x01\x01\xff'
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400679
Alex Chanc6077062016-11-18 13:53:39 +0000680 def test_unused_subject(self, x509_data):
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400681 """
Alex Chanc6077062016-11-18 13:53:39 +0000682 The `subject` parameter to `X509Extension` may be provided for an
683 extension which does not use it and is ignored in this case.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400684 """
Alex Chanc6077062016-11-18 13:53:39 +0000685 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400686 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000687 b'basicConstraints', False, b'CA:TRUE', subject=x509)
688 x509.add_extensions([ext1])
689 x509.sign(pkey, 'sha1')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400690 # This is a little lame. Can we think of a better way?
Alex Chanc6077062016-11-18 13:53:39 +0000691 text = dump_certificate(FILETYPE_TEXT, x509)
692 assert b'X509v3 Basic Constraints:' in text
693 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400694
Alex Chanc6077062016-11-18 13:53:39 +0000695 def test_subject(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400696 """
Alex Chanc6077062016-11-18 13:53:39 +0000697 If an extension requires a subject, the `subject` parameter to
698 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400699 """
Alex Chanc6077062016-11-18 13:53:39 +0000700 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400701 ext3 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000702 b'subjectKeyIdentifier', False, b'hash', subject=x509)
703 x509.add_extensions([ext3])
704 x509.sign(pkey, 'sha1')
705 text = dump_certificate(FILETYPE_TEXT, x509)
706 assert b'X509v3 Subject Key Identifier:' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400707
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400708 def test_missing_subject(self):
709 """
Alex Chanc6077062016-11-18 13:53:39 +0000710 If an extension requires a subject and the `subject` parameter
Alex Gaynor31287502015-09-05 16:11:27 -0400711 is given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400712 """
Alex Chanc6077062016-11-18 13:53:39 +0000713 with pytest.raises(Error):
714 X509Extension(b'subjectKeyIdentifier', False, b'hash')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400715
Alex Chanc6077062016-11-18 13:53:39 +0000716 @pytest.mark.parametrize('bad_obj', [
717 True,
718 object(),
719 "hello",
720 [],
721 ])
722 def test_invalid_subject(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400723 """
Alex Chanc6077062016-11-18 13:53:39 +0000724 If the `subject` parameter is given a value which is not an
725 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400726 """
Alex Chanc6077062016-11-18 13:53:39 +0000727 with pytest.raises(TypeError):
728 X509Extension(
729 'basicConstraints', False, 'CA:TRUE', subject=bad_obj)
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400730
Alex Chanc6077062016-11-18 13:53:39 +0000731 def test_unused_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400732 """
Alex Chanc6077062016-11-18 13:53:39 +0000733 The `issuer` parameter to `X509Extension` may be provided for an
734 extension which does not use it and is ignored in this case.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400735 """
Alex Chanc6077062016-11-18 13:53:39 +0000736 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400737 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000738 b'basicConstraints', False, b'CA:TRUE', issuer=x509)
739 x509.add_extensions([ext1])
740 x509.sign(pkey, 'sha1')
741 text = dump_certificate(FILETYPE_TEXT, x509)
742 assert b'X509v3 Basic Constraints:' in text
743 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400744
Alex Chanc6077062016-11-18 13:53:39 +0000745 def test_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400746 """
Alex Chanc6077062016-11-18 13:53:39 +0000747 If an extension requires an issuer, the `issuer` parameter to
748 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400749 """
Alex Chanc6077062016-11-18 13:53:39 +0000750 pkey, x509 = x509_data
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400751 ext2 = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -0400752 b'authorityKeyIdentifier', False, b'issuer:always',
Alex Chanc6077062016-11-18 13:53:39 +0000753 issuer=x509)
754 x509.add_extensions([ext2])
755 x509.sign(pkey, 'sha1')
756 text = dump_certificate(FILETYPE_TEXT, x509)
757 assert b'X509v3 Authority Key Identifier:' in text
758 assert b'DirName:/CN=Yoda root CA' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400759
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400760 def test_missing_issuer(self):
761 """
Alex Chanc6077062016-11-18 13:53:39 +0000762 If an extension requires an issue and the `issuer` parameter is
763 given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400764 """
Alex Chanc6077062016-11-18 13:53:39 +0000765 with pytest.raises(Error):
766 X509Extension(
767 b'authorityKeyIdentifier',
768 False, b'keyid:always,issuer:always')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400769
Alex Chanc6077062016-11-18 13:53:39 +0000770 @pytest.mark.parametrize('bad_obj', [
771 True,
772 object(),
773 "hello",
774 [],
775 ])
776 def test_invalid_issuer(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400777 """
Alex Chanc6077062016-11-18 13:53:39 +0000778 If the `issuer` parameter is given a value which is not an
779 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400780 """
Alex Chanc6077062016-11-18 13:53:39 +0000781 with pytest.raises(TypeError):
782 X509Extension(
783 'basicConstraints', False, 'keyid:always,issuer:always',
784 issuer=bad_obj)
Rick Dean47262da2009-07-08 16:17:17 -0500785
786
Paul Kehrer72d968b2016-07-29 15:31:04 +0800787class TestPKey(object):
788 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +0100789 Tests for `OpenSSL.crypto.PKey`.
Paul Kehrer72d968b2016-07-29 15:31:04 +0800790 """
791
792 def test_convert_from_cryptography_private_key(self):
793 """
794 PKey.from_cryptography_key creates a proper private PKey.
795 """
796 key = serialization.load_pem_private_key(
797 intermediate_key_pem, None, backend
798 )
799 pkey = PKey.from_cryptography_key(key)
800
801 assert isinstance(pkey, PKey)
802 assert pkey.bits() == key.key_size
803 assert pkey._only_public is False
804 assert pkey._initialized is True
805
806 def test_convert_from_cryptography_public_key(self):
807 """
808 PKey.from_cryptography_key creates a proper public PKey.
809 """
810 key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
811 pkey = PKey.from_cryptography_key(key)
812
813 assert isinstance(pkey, PKey)
814 assert pkey.bits() == key.key_size
815 assert pkey._only_public is True
816 assert pkey._initialized is True
817
818 def test_convert_from_cryptography_unsupported_type(self):
819 """
820 PKey.from_cryptography_key raises TypeError with an unsupported type.
821 """
822 key = serialization.load_pem_private_key(
823 ec_private_key_pem, None, backend
824 )
825 with pytest.raises(TypeError):
826 PKey.from_cryptography_key(key)
827
828 def test_convert_public_pkey_to_cryptography_key(self):
829 """
830 PKey.to_cryptography_key creates a proper cryptography public key.
831 """
832 pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
833 key = pkey.to_cryptography_key()
834
835 assert isinstance(key, rsa.RSAPublicKey)
836 assert pkey.bits() == key.key_size
837
838 def test_convert_private_pkey_to_cryptography_key(self):
839 """
840 PKey.to_cryptography_key creates a proper cryptography private key.
841 """
842 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
843 key = pkey.to_cryptography_key()
844
845 assert isinstance(key, rsa.RSAPrivateKey)
846 assert pkey.bits() == key.key_size
847
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400848 def test_type(self):
849 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000850 `PKey` and `PKeyType` refer to the same type object and can be used to
851 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400852 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000853 assert PKey is PKeyType
854 assert is_consistent_type(PKey, 'PKey')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400855
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500856 def test_construction(self):
857 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000858 `PKey` takes no arguments and returns a new `PKey` instance.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500859 """
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500860 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000861 assert isinstance(key, PKey)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500862
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500863 def test_pregeneration(self):
864 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000865 `PKey.bits` and `PKey.type` return `0` before the key is generated.
866 `PKey.check` raises `TypeError` before the key is generated.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500867 """
868 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000869 assert key.type() == 0
870 assert key.bits() == 0
871 with pytest.raises(TypeError):
872 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500873
Alex Chan9e2a9932017-01-25 14:29:19 +0000874 def test_failed_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500875 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000876 `PKey.generate_key` takes two arguments, the first giving the key type
877 as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
878 bits to generate. If an invalid type is specified or generation fails,
879 `Error` is raised. If an invalid number of bits is specified,
880 `ValueError` or `Error` is raised.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500881 """
882 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000883 with pytest.raises(TypeError):
884 key.generate_key("foo", "bar")
885 with pytest.raises(Error):
886 key.generate_key(-1, 0)
Jean-Paul Calderoneab82db72008-03-06 00:09:31 -0500887
Alex Chan9e2a9932017-01-25 14:29:19 +0000888 with pytest.raises(ValueError):
889 key.generate_key(TYPE_RSA, -1)
890 with pytest.raises(ValueError):
891 key.generate_key(TYPE_RSA, 0)
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500892
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400893 with pytest.raises(TypeError):
894 key.generate_key(TYPE_RSA, object())
895
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500896 # XXX RSA generation for small values of bits is fairly buggy in a wide
897 # range of OpenSSL versions. I need to figure out what the safe lower
898 # bound for a reasonable number of OpenSSL versions is and explicitly
899 # check for that in the wrapper. The failure behavior is typically an
900 # infinite loop inside OpenSSL.
901
Alex Chan9e2a9932017-01-25 14:29:19 +0000902 # with pytest.raises(Error):
903 # key.generate_key(TYPE_RSA, 2)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500904
905 # XXX DSA generation seems happy with any number of bits. The DSS
906 # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
907 # generator doesn't seem to care about the upper limit at all. For
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500908 # the lower limit, it uses 512 if anything smaller is specified.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500909 # So, it doesn't seem possible to make generate_key fail for
910 # TYPE_DSA with a bits argument which is at least an int.
911
Alex Chan9e2a9932017-01-25 14:29:19 +0000912 # with pytest.raises(Error):
913 # key.generate_key(TYPE_DSA, -7)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500914
Alex Chan9e2a9932017-01-25 14:29:19 +0000915 def test_rsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500916 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000917 `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
918 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500919 """
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400920 bits = 512
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500921 key = PKey()
922 key.generate_key(TYPE_RSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000923 assert key.type() == TYPE_RSA
924 assert key.bits() == bits
925 assert key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500926
Alex Chan9e2a9932017-01-25 14:29:19 +0000927 def test_dsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500928 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000929 `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
930 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500931 """
932 # 512 is a magic number. The DSS (Digital Signature Standard)
933 # allows a minimum of 512 bits for DSA. DSA_generate_parameters
934 # will silently promote any value below 512 to 512.
935 bits = 512
936 key = PKey()
937 key.generate_key(TYPE_DSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000938 assert key.type() == TYPE_DSA
939 assert key.bits() == bits
940 with pytest.raises(TypeError):
941 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500942
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500943 def test_regeneration(self):
944 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000945 `PKey.generate_key` can be called multiple times on the same key to
946 generate new keys.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500947 """
948 key = PKey()
949 for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
Alex Gaynor7f636492015-09-04 13:26:52 -0400950 key.generate_key(type, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000951 assert key.type() == type
952 assert key.bits() == bits
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500953
Alex Chan9e2a9932017-01-25 14:29:19 +0000954 def test_inconsistent_key(self):
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400955 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000956 `PKey.check` returns `Error` if the key is not consistent.
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400957 """
958 key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
Alex Chan9e2a9932017-01-25 14:29:19 +0000959 with pytest.raises(Error):
960 key.check()
Jean-Paul Calderonee81020e2011-06-12 21:48:57 -0400961
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400962 def test_check_public_key(self):
963 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000964 `PKey.check` raises `TypeError` if only the public part of the key
965 is available.
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400966 """
967 # A trick to get a public-only key
968 key = PKey()
969 key.generate_key(TYPE_RSA, 512)
970 cert = X509()
971 cert.set_pubkey(key)
972 pub = cert.get_pubkey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000973 with pytest.raises(TypeError):
974 pub.check()
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400975
976
Alex Chan9e2a9932017-01-25 14:29:19 +0000977def x509_name(**attrs):
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500978 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000979 Return a new X509Name with the given attributes.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500980 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000981 # XXX There's no other way to get a new X509Name yet.
982 name = X509().get_subject()
983 attrs = list(attrs.items())
Alex Gaynoraceb3e22015-09-05 12:00:22 -0400984
Alex Chan9e2a9932017-01-25 14:29:19 +0000985 # Make the order stable - order matters!
986 def key(attr):
987 return attr[1]
988 attrs.sort(key=key)
989 for k, v in attrs:
990 setattr(name, k, v)
991 return name
Alex Gaynor85b49702015-09-05 16:30:59 -0400992
Alex Chan9e2a9932017-01-25 14:29:19 +0000993
994class TestX509Name(object):
995 """
996 Unit tests for `OpenSSL.crypto.X509Name`.
997 """
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -0500998
Rick Deane15b1472009-07-09 15:53:42 -0500999 def test_type(self):
1000 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001001 The type of X509Name objects is `X509NameType`.
Rick Deane15b1472009-07-09 15:53:42 -05001002 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001003 assert X509Name is X509NameType
1004 assert X509NameType.__name__ == 'X509Name'
1005 assert isinstance(X509NameType, type)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001006
Alex Chan9e2a9932017-01-25 14:29:19 +00001007 name = x509_name()
1008 assert isinstance(name, X509NameType)
Rick Deane15b1472009-07-09 15:53:42 -05001009
Alex Chan9e2a9932017-01-25 14:29:19 +00001010 def test_only_string_attributes(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001011 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001012 Attempting to set a non-`str` attribute name on an `X509Name` instance
1013 causes `TypeError` to be raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001014 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001015 name = x509_name()
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001016 # Beyond these cases, you may also think that unicode should be
Alex Gaynor31287502015-09-05 16:11:27 -04001017 # rejected. Sorry, you're wrong. unicode is automatically converted
1018 # to str outside of the control of X509Name, so there's no way to
1019 # reject it.
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -08001020
Alex Gaynor31287502015-09-05 16:11:27 -04001021 # Also, this used to test str subclasses, but that test is less
1022 # relevant now that the implementation is in Python instead of C. Also
1023 # PyPy automatically converts str subclasses to str when they are
1024 # passed to setattr, so we can't test it on PyPy. Apparently CPython
1025 # does this sometimes as well.
Alex Chan9e2a9932017-01-25 14:29:19 +00001026 with pytest.raises(TypeError):
1027 setattr(name, None, "hello")
1028 with pytest.raises(TypeError):
1029 setattr(name, 30, "hello")
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001030
Alex Chan9e2a9932017-01-25 14:29:19 +00001031 def test_set_invalid_attribute(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001032 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001033 Attempting to set any attribute name on an `X509Name` instance for
1034 which no corresponding NID is defined causes `AttributeError` to be
1035 raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001036 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001037 name = x509_name()
1038 with pytest.raises(AttributeError):
1039 setattr(name, "no such thing", None)
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001040
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001041 def test_attributes(self):
1042 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001043 `X509Name` instances have attributes for each standard (?)
1044 X509Name field.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001045 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001046 name = x509_name()
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001047 name.commonName = "foo"
Alex Gaynor37726112016-07-04 09:51:32 -04001048 assert name.commonName == "foo"
1049 assert name.CN == "foo"
1050
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001051 name.CN = "baz"
Alex Gaynor37726112016-07-04 09:51:32 -04001052 assert name.commonName == "baz"
1053 assert name.CN == "baz"
1054
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001055 name.commonName = "bar"
Alex Gaynor37726112016-07-04 09:51:32 -04001056 assert name.commonName == "bar"
1057 assert name.CN == "bar"
1058
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001059 name.CN = "quux"
Alex Gaynor37726112016-07-04 09:51:32 -04001060 assert name.commonName == "quux"
1061 assert name.CN == "quux"
1062
1063 assert name.OU is None
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001064
Alex Gaynor7778e792016-07-03 23:38:48 -04001065 with pytest.raises(AttributeError):
1066 name.foobar
1067
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001068 def test_copy(self):
1069 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001070 `X509Name` creates a new `X509Name` instance with all the same
1071 attributes as an existing `X509Name` instance when called with one.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001072 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001073 name = x509_name(commonName="foo", emailAddress="bar@example.com")
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001074
1075 copy = X509Name(name)
Alex Chan9e2a9932017-01-25 14:29:19 +00001076 assert copy.commonName == "foo"
1077 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001078
1079 # Mutate the copy and ensure the original is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001080 copy.commonName = "baz"
Alex Chan9e2a9932017-01-25 14:29:19 +00001081 assert name.commonName == "foo"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001082
1083 # Mutate the original and ensure the copy is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001084 name.emailAddress = "quux@example.com"
Alex Chan9e2a9932017-01-25 14:29:19 +00001085 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001086
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001087 def test_repr(self):
1088 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001089 `repr` passed an `X509Name` instance should return a string containing
1090 a description of the type and the NIDs which have been set on it.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001091 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001092 name = x509_name(commonName="foo", emailAddress="bar")
1093 assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001094
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001095 def test_comparison(self):
1096 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001097 `X509Name` instances should compare based on their NIDs.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001098 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001099 def _equality(a, b, assert_true, assert_false):
1100 assert_true(a == b)
1101 assert_false(a != b)
1102 assert_true(b == a)
1103 assert_false(b != a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001104
Alex Chan9e2a9932017-01-25 14:29:19 +00001105 def assert_true(x):
1106 assert x
1107
1108 def assert_false(x):
1109 assert not x
1110
1111 def assert_equal(a, b):
1112 _equality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001113
1114 # Instances compare equal to themselves.
Alex Chan9e2a9932017-01-25 14:29:19 +00001115 name = x509_name()
1116 assert_equal(name, name)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001117
1118 # Empty instances should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001119 assert_equal(x509_name(), x509_name())
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001120
1121 # Instances with equal NIDs should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001122 assert_equal(x509_name(commonName="foo"),
1123 x509_name(commonName="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001124
1125 # Instance with equal NIDs set using different aliases should compare
1126 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001127 assert_equal(x509_name(commonName="foo"),
1128 x509_name(CN="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001129
1130 # Instances with more than one NID with the same values should compare
1131 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001132 assert_equal(x509_name(CN="foo", organizationalUnitName="bar"),
1133 x509_name(commonName="foo", OU="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001134
Alex Chan9e2a9932017-01-25 14:29:19 +00001135 def assert_not_equal(a, b):
1136 _equality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001137
1138 # Instances with different values for the same NID should not compare
1139 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001140 assert_not_equal(x509_name(CN="foo"),
1141 x509_name(CN="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001142
1143 # Instances with different NIDs should not compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001144 assert_not_equal(x509_name(CN="foo"),
1145 x509_name(OU="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001146
Alex Chan9e2a9932017-01-25 14:29:19 +00001147 assert_not_equal(x509_name(), object())
Alex Gaynor7778e792016-07-03 23:38:48 -04001148
Alex Chan9e2a9932017-01-25 14:29:19 +00001149 def _inequality(a, b, assert_true, assert_false):
1150 assert_true(a < b)
1151 assert_true(a <= b)
1152 assert_true(b > a)
1153 assert_true(b >= a)
1154 assert_false(a > b)
1155 assert_false(a >= b)
1156 assert_false(b < a)
1157 assert_false(b <= a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001158
Alex Chan9e2a9932017-01-25 14:29:19 +00001159 def assert_less_than(a, b):
1160 _inequality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001161
1162 # An X509Name with a NID with a value which sorts less than the value
1163 # of the same NID on another X509Name compares less than the other
1164 # X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001165 assert_less_than(x509_name(CN="abc"),
1166 x509_name(CN="def"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001167
Alex Chan9e2a9932017-01-25 14:29:19 +00001168 def assert_greater_than(a, b):
1169 _inequality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001170
1171 # An X509Name with a NID with a value which sorts greater than the
1172 # value of the same NID on another X509Name compares greater than the
1173 # other X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001174 assert_greater_than(x509_name(CN="def"),
1175 x509_name(CN="abc"))
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001176
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001177 def test_hash(self):
1178 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001179 `X509Name.hash` returns an integer hash based on the value of the name.
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001180 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001181 a = x509_name(CN="foo")
1182 b = x509_name(CN="foo")
1183 assert a.hash() == b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001184 a.CN = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001185 assert a.hash() != b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001186
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001187 def test_der(self):
1188 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001189 `X509Name.der` returns the DER encoded form of the name.
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001190 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001191 a = x509_name(CN="foo", C="US")
1192 assert (a.der() ==
1193 b'0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
1194 b'1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo')
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001195
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001196 def test_get_components(self):
1197 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001198 `X509Name.get_components` returns a `list` of two-tuples of `str`
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001199 giving the NIDs and associated values which make up the name.
1200 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001201 a = x509_name()
1202 assert a.get_components() == []
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001203 a.CN = "foo"
Alex Chan9e2a9932017-01-25 14:29:19 +00001204 assert a.get_components() == [(b"CN", b"foo")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001205 a.organizationalUnitName = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001206 assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001207
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001208 def test_load_nul_byte_attribute(self):
1209 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001210 An `X509Name` from an `X509` instance loaded from a file can have a
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001211 NUL byte in the value of one of its attributes.
1212 """
1213 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1214 subject = cert.get_subject()
Alex Chan9e2a9932017-01-25 14:29:19 +00001215 assert "null.python.org\x00example.org" == subject.commonName
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001216
Romuald Brunet4183beb2019-01-21 19:38:33 +01001217 def test_load_nul_byte_components(self):
1218 """
1219 An `X509Name` from an `X509` instance loaded from a file can have a
1220 NUL byte in the value of its components
1221 """
1222 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1223 subject = cert.get_subject()
1224 components = subject.get_components()
1225 ccn = [value for name, value in components if name == b'CN']
1226 assert ccn[0] == b'null.python.org\x00example.org'
1227
Alex Chan9e2a9932017-01-25 14:29:19 +00001228 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001229 """
1230 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001231 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001232 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001233 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001234 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001235 with pytest.raises(Error):
1236 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001237
1238
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001239class _PKeyInteractionTestsMixin:
1240 """
1241 Tests which involve another thing and a PKey.
1242 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001243
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001244 def signable(self):
1245 """
Alex Chanfb078d82017-04-20 11:16:15 +01001246 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001247 """
1248 raise NotImplementedError()
1249
Alex Chanb00ede22017-01-30 07:24:40 +00001250 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001251 """
Alex Chanb00ede22017-01-30 07:24:40 +00001252 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001253 """
1254 request = self.signable()
1255 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001256 with pytest.raises(ValueError):
1257 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001258
Alex Chanb00ede22017-01-30 07:24:40 +00001259 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001260 """
Alex Chanb00ede22017-01-30 07:24:40 +00001261 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1262 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001263 """
1264 request = self.signable()
1265 key = PKey()
1266 key.generate_key(TYPE_RSA, 512)
1267 request.set_pubkey(key)
1268 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001269 with pytest.raises(ValueError):
1270 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001271
Alex Chanb00ede22017-01-30 07:24:40 +00001272 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001273 """
Alex Chanb00ede22017-01-30 07:24:40 +00001274 `X509Req.sign` raises `ValueError` when passed a digest name which is
1275 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001276 """
1277 request = self.signable()
1278 key = PKey()
1279 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001280 with pytest.raises(ValueError):
1281 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001282
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001283 def test_sign(self):
1284 """
Alex Chanb00ede22017-01-30 07:24:40 +00001285 `X509Req.sign` succeeds when passed a private key object and a
1286 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001287 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001288 """
1289 request = self.signable()
1290 key = PKey()
1291 key.generate_key(TYPE_RSA, 512)
1292 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001293 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001294 # If the type has a verify method, cover that too.
1295 if getattr(request, 'verify', None) is not None:
1296 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001297 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001298 # Make another key that won't verify.
1299 key = PKey()
1300 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001301 with pytest.raises(Error):
1302 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001303
1304
Alex Chanb00ede22017-01-30 07:24:40 +00001305class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001306 """
Alex Chanb00ede22017-01-30 07:24:40 +00001307 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001308 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001309
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001310 def signable(self):
1311 """
Alex Chanb00ede22017-01-30 07:24:40 +00001312 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001313 """
1314 return X509Req()
1315
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001316 def test_type(self):
1317 """
Alex Chanb00ede22017-01-30 07:24:40 +00001318 `X509Req` and `X509ReqType` refer to the same type object and can be
1319 used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001320 """
Alex Chanb00ede22017-01-30 07:24:40 +00001321 assert X509Req is X509ReqType
1322 assert is_consistent_type(X509Req, 'X509Req')
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001323
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001324 def test_construction(self):
1325 """
Alex Chanb00ede22017-01-30 07:24:40 +00001326 `X509Req` takes no arguments and returns an `X509ReqType` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001327 """
1328 request = X509Req()
Alex Gaynor31287502015-09-05 16:11:27 -04001329 assert isinstance(request, X509ReqType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001330
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001331 def test_version(self):
1332 """
Alex Chanb00ede22017-01-30 07:24:40 +00001333 `X509Req.set_version` sets the X.509 version of the certificate
1334 request. `X509Req.get_version` returns the X.509 version of the
1335 certificate request. The initial value of the version is 0.
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001336 """
1337 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001338 assert request.get_version() == 0
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001339 request.set_version(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001340 assert request.get_version() == 1
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001341 request.set_version(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001342 assert request.get_version() == 3
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001343
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001344 def test_version_wrong_args(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001345 """
Alex Chanb00ede22017-01-30 07:24:40 +00001346 `X509Req.set_version` raises `TypeError` if called with a non-`int`
1347 argument.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001348 """
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001349 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001350 with pytest.raises(TypeError):
1351 request.set_version("foo")
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001352
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001353 def test_get_subject(self):
1354 """
Alex Chanb00ede22017-01-30 07:24:40 +00001355 `X509Req.get_subject` returns an `X509Name` for the subject of the
1356 request and which is valid even after the request object is
1357 otherwise dead.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001358 """
1359 request = X509Req()
1360 subject = request.get_subject()
Alex Gaynor31287502015-09-05 16:11:27 -04001361 assert isinstance(subject, X509NameType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001362 subject.commonName = "foo"
Alex Chanb00ede22017-01-30 07:24:40 +00001363 assert request.get_subject().commonName == "foo"
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001364 del request
1365 subject.commonName = "bar"
Alex Chanb00ede22017-01-30 07:24:40 +00001366 assert subject.commonName == "bar"
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001367
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001368 def test_add_extensions(self):
1369 """
Alex Chanb00ede22017-01-30 07:24:40 +00001370 `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
1371 and adds them to the X509 request.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001372 """
1373 request = X509Req()
1374 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001375 X509Extension(b'basicConstraints', True, b'CA:false')])
Stephen Holsappleca545b72014-01-28 21:43:25 -08001376 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001377 assert len(exts) == 1
1378 assert exts[0].get_short_name() == b'basicConstraints'
1379 assert exts[0].get_critical() == 1
1380 assert exts[0].get_data() == b'0\x00'
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001381
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001382 def test_get_extensions(self):
1383 """
Alex Chanb00ede22017-01-30 07:24:40 +00001384 `X509Req.get_extensions` returns a `list` of extensions added to this
1385 X509 request.
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001386 """
1387 request = X509Req()
1388 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001389 assert exts == []
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001390 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001391 X509Extension(b'basicConstraints', True, b'CA:true'),
1392 X509Extension(b'keyUsage', False, b'digitalSignature')])
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001393 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001394 assert len(exts) == 2
1395 assert exts[0].get_short_name() == b'basicConstraints'
1396 assert exts[0].get_critical() == 1
1397 assert exts[0].get_data() == b'0\x03\x01\x01\xff'
1398 assert exts[1].get_short_name() == b'keyUsage'
1399 assert exts[1].get_critical() == 0
1400 assert exts[1].get_data() == b'\x03\x02\x07\x80'
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001401
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001402 def test_add_extensions_wrong_args(self):
1403 """
Alex Chanb00ede22017-01-30 07:24:40 +00001404 `X509Req.add_extensions` raises `TypeError` if called with a
1405 non-`list`. Or it raises `ValueError` if called with a `list`
1406 containing objects other than `X509Extension` instances.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001407 """
1408 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001409 with pytest.raises(TypeError):
1410 request.add_extensions(object())
1411 with pytest.raises(ValueError):
1412 request.add_extensions([object()])
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001413
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001414 def test_verify_wrong_args(self):
1415 """
Alex Chanb00ede22017-01-30 07:24:40 +00001416 `X509Req.verify` raises `TypeError` if passed anything other than a
1417 `PKey` instance as its single argument.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001418 """
1419 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001420 with pytest.raises(TypeError):
1421 request.verify(object())
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001422
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001423 def test_verify_uninitialized_key(self):
1424 """
Alex Chanb00ede22017-01-30 07:24:40 +00001425 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1426 `OpenSSL.crypto.PKey` which contains no key data.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001427 """
1428 request = X509Req()
1429 pkey = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001430 with pytest.raises(Error):
1431 request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001432
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001433 def test_verify_wrong_key(self):
1434 """
Alex Chanb00ede22017-01-30 07:24:40 +00001435 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1436 `OpenSSL.crypto.PKey` which does not represent the public part of the
Alex Gaynor31287502015-09-05 16:11:27 -04001437 key which signed the request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001438 """
1439 request = X509Req()
1440 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001441 request.sign(pkey, GOOD_DIGEST)
Alex Chanb00ede22017-01-30 07:24:40 +00001442 another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
1443 with pytest.raises(Error):
1444 request.verify(another_pkey)
1445
1446 def test_verify_success(self):
1447 """
1448 `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
1449 which represents the public part of the key which signed the request.
1450 """
1451 request = X509Req()
1452 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
1453 request.sign(pkey, GOOD_DIGEST)
1454 assert request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001455
Paul Kehrer41c10242017-06-29 18:24:17 -05001456 def test_convert_from_cryptography(self):
1457 crypto_req = x509.load_pem_x509_csr(
1458 cleartextCertificateRequestPEM, backend
1459 )
1460 req = X509Req.from_cryptography(crypto_req)
1461 assert isinstance(req, X509Req)
1462
1463 def test_convert_from_cryptography_unsupported_type(self):
1464 with pytest.raises(TypeError):
1465 X509Req.from_cryptography(object())
1466
1467 def test_convert_to_cryptography_key(self):
1468 req = load_certificate_request(
1469 FILETYPE_PEM, cleartextCertificateRequestPEM
1470 )
1471 crypto_req = req.to_cryptography()
1472 assert isinstance(crypto_req, x509.CertificateSigningRequest)
1473
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001474
Alex Chanb00ede22017-01-30 07:24:40 +00001475class TestX509(_PKeyInteractionTestsMixin):
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001476 """
Alex Chanb00ede22017-01-30 07:24:40 +00001477 Tests for `OpenSSL.crypto.X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001478 """
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001479 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Jean-Paul Calderone8114b452008-03-25 15:27:59 -04001480
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001481 extpem = """
1482-----BEGIN CERTIFICATE-----
1483MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
1484BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
1485eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
1486MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
1487aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
1488hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
1489Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
1490zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
1491hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
1492TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
149303HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
1494MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
1495b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
1496MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
1497uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
1498WpOdIpB8KksUTCzV591Nr1wd
1499-----END CERTIFICATE-----
1500 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001501
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001502 def signable(self):
1503 """
Alex Chanb00ede22017-01-30 07:24:40 +00001504 Create and return a new `X509`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001505 """
1506 return X509()
1507
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001508 def test_type(self):
1509 """
Alex Chanb00ede22017-01-30 07:24:40 +00001510 `X509` and `X509Type` refer to the same type object and can be used to
1511 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001512 """
Alex Chanb00ede22017-01-30 07:24:40 +00001513 assert X509 is X509Type
1514 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001515
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001516 def test_construction(self):
1517 """
Alex Chanb00ede22017-01-30 07:24:40 +00001518 `X509` takes no arguments and returns an instance of `X509Type`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001519 """
1520 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001521 assert isinstance(certificate, X509Type)
1522 assert type(X509Type).__name__ == 'type'
1523 assert type(certificate).__name__ == 'X509'
1524 assert type(certificate) == X509Type
1525 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001526
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001527 def test_set_version_wrong_args(self):
1528 """
Alex Chanb00ede22017-01-30 07:24:40 +00001529 `X509.set_version` raises `TypeError` if invoked with an argument
1530 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001531 """
1532 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001533 with pytest.raises(TypeError):
1534 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001535
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001536 def test_version(self):
1537 """
Alex Chanb00ede22017-01-30 07:24:40 +00001538 `X509.set_version` sets the certificate version number.
1539 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001540 """
1541 cert = X509()
1542 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001543 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001544
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001545 def test_serial_number(self):
1546 """
Alex Chanb00ede22017-01-30 07:24:40 +00001547 The serial number of an `X509` can be retrieved and
1548 modified with `X509.get_serial_number` and
1549 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001550 """
1551 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001552 with pytest.raises(TypeError):
1553 certificate.set_serial_number("1")
1554 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001555 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001556 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001557 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001558 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001559 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001560 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001561 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001562 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001563
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001564 def _setBoundTest(self, which):
1565 """
Alex Chanb00ede22017-01-30 07:24:40 +00001566 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001567 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1568 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001569 """
1570 certificate = X509()
1571 set = getattr(certificate, 'set_not' + which)
1572 get = getattr(certificate, 'get_not' + which)
1573
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001574 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001575 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001576
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001577 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001578 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001579 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001580 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001581
1582 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001583 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001584 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001585 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001586
1587 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001588 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001589 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001590 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001591
1592 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001593 with pytest.raises(ValueError):
1594 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001595
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001596 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001597 with pytest.raises(TypeError):
1598 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001599 with pytest.raises(TypeError):
1600 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001601 with pytest.raises(TypeError):
1602 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001603
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001604 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001605
1606 def test_set_notBefore(self):
1607 """
Alex Chanb00ede22017-01-30 07:24:40 +00001608 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001609 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1610 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001611 """
1612 self._setBoundTest("Before")
1613
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001614 def test_set_notAfter(self):
1615 """
Alex Chanb00ede22017-01-30 07:24:40 +00001616 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001617 GENERALIZEDTIME and sets the end of the certificate's validity period
1618 to it.
1619 """
1620 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001621
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001622 def test_get_notBefore(self):
1623 """
Alex Chanb00ede22017-01-30 07:24:40 +00001624 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001625 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001626 internally.
1627 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001628 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001629 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001630
Rick Dean38a05c82009-07-18 01:41:30 -05001631 def test_get_notAfter(self):
1632 """
Alex Chanb00ede22017-01-30 07:24:40 +00001633 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001634 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001635 internally.
1636 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001637 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001638 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001639
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001640 def test_gmtime_adj_notBefore_wrong_args(self):
1641 """
Alex Chanb00ede22017-01-30 07:24:40 +00001642 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1643 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001644 """
1645 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001646 with pytest.raises(TypeError):
1647 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001648
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001649 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001650 def test_gmtime_adj_notBefore(self):
1651 """
Alex Chanb00ede22017-01-30 07:24:40 +00001652 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1653 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001654 """
1655 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001656 not_before_min = (
1657 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1658 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001659 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001660 not_before = datetime.strptime(
1661 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1662 )
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001663 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001664 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001665
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001666 def test_gmtime_adj_notAfter_wrong_args(self):
1667 """
Alex Chanb00ede22017-01-30 07:24:40 +00001668 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1669 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001670 """
1671 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001672 with pytest.raises(TypeError):
1673 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001674
Alex Gaynor642de6f2017-07-24 00:57:38 -04001675 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001676 def test_gmtime_adj_notAfter(self):
1677 """
Alex Chanb00ede22017-01-30 07:24:40 +00001678 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001679 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001680 """
1681 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001682 not_after_min = (
1683 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1684 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001685 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001686 not_after = datetime.strptime(
1687 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1688 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001689 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001690 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001691
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001692 def test_has_expired(self):
1693 """
Alex Chanb00ede22017-01-30 07:24:40 +00001694 `X509.has_expired` returns `True` if the certificate's not-after time
1695 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001696 """
1697 cert = X509()
1698 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001699 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001700
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001701 def test_has_not_expired(self):
1702 """
Alex Chanb00ede22017-01-30 07:24:40 +00001703 `X509.has_expired` returns `False` if the certificate's not-after time
1704 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001705 """
1706 cert = X509()
1707 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001708 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001709
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001710 def test_root_has_not_expired(self):
1711 """
Alex Chanb00ede22017-01-30 07:24:40 +00001712 `X509.has_expired` returns `False` if the certificate's not-after time
1713 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001714 """
1715 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001716 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001717
Rick Dean38a05c82009-07-18 01:41:30 -05001718 def test_digest(self):
1719 """
Alex Chanb00ede22017-01-30 07:24:40 +00001720 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001721 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001722 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001723 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001724 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001725 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1726 # actually matters to the assertion (ie, another arbitrary, good
1727 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001728 # Digest verified with the command:
1729 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001730 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001731 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001732
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001733 def _extcert(self, pkey, extensions):
1734 cert = X509()
1735 cert.set_pubkey(pkey)
1736 cert.get_subject().commonName = "Unit Tests"
1737 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001738 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001739 cert.set_notBefore(when)
1740 cert.set_notAfter(when)
1741
1742 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001743 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001744 return load_certificate(
1745 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1746
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001747 def test_extension_count(self):
1748 """
Alex Chanb00ede22017-01-30 07:24:40 +00001749 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001750 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001751 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001752 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001753 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1754 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001755 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001756 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001757
1758 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001759 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001760 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001761
1762 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001763 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001764 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001765
1766 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001767 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001768 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001769
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001770 def test_get_extension(self):
1771 """
Alex Chanb00ede22017-01-30 07:24:40 +00001772 `X509.get_extension` takes an integer and returns an
1773 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001774 """
1775 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001776 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1777 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001778 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001779 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001780
1781 cert = self._extcert(pkey, [ca, key, subjectAltName])
1782
1783 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001784 assert isinstance(ext, X509Extension)
1785 assert ext.get_critical()
1786 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001787
1788 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001789 assert isinstance(ext, X509Extension)
1790 assert ext.get_critical()
1791 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001792
1793 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001794 assert isinstance(ext, X509Extension)
1795 assert not ext.get_critical()
1796 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001797
Alex Chanb00ede22017-01-30 07:24:40 +00001798 with pytest.raises(IndexError):
1799 cert.get_extension(-1)
1800 with pytest.raises(IndexError):
1801 cert.get_extension(4)
1802 with pytest.raises(TypeError):
1803 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001804
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001805 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001806 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001807 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001808 bytes and this value is reflected in the string representation of the
1809 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001810 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001811 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001812
1813 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001814 assert ext.get_short_name() == b'subjectAltName'
1815 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001816 b"DNS:altnull.python.org\x00example.com, "
1817 b"email:null@python.org\x00user@example.org, "
1818 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001819 b"IP Address:192.0.2.1, IP Address:2001:DB8:0:0:0:0:0:1\n" ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001820 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001821
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001822 def test_invalid_digest_algorithm(self):
1823 """
Alex Chanb00ede22017-01-30 07:24:40 +00001824 `X509.digest` raises `ValueError` if called with an unrecognized hash
1825 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001826 """
1827 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001828 with pytest.raises(ValueError):
1829 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001830
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001831 def test_get_subject(self):
1832 """
Alex Chanb00ede22017-01-30 07:24:40 +00001833 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001834 """
1835 cert = load_certificate(FILETYPE_PEM, self.pemData)
1836 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001837 assert isinstance(subj, X509Name)
1838 assert (
1839 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001840 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1841 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001842
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001843 def test_set_subject_wrong_args(self):
1844 """
Alex Chanb00ede22017-01-30 07:24:40 +00001845 `X509.set_subject` raises a `TypeError` if called with an argument not
1846 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001847 """
1848 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001849 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001850 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001851
1852 def test_set_subject(self):
1853 """
Alex Chanb00ede22017-01-30 07:24:40 +00001854 `X509.set_subject` changes the subject of the certificate to the one
1855 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001856 """
1857 cert = X509()
1858 name = cert.get_subject()
1859 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001860 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001861 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001862 assert (
1863 cert.get_subject().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001864 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001865
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001866 def test_get_issuer(self):
1867 """
Alex Chanb00ede22017-01-30 07:24:40 +00001868 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001869 """
1870 cert = load_certificate(FILETYPE_PEM, self.pemData)
1871 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001872 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001873 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001874 assert (
1875 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001876 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1877 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001878
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001879 def test_set_issuer_wrong_args(self):
1880 """
Alex Chanb00ede22017-01-30 07:24:40 +00001881 `X509.set_issuer` raises a `TypeError` if called with an argument not
1882 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001883 """
1884 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001885 with pytest.raises(TypeError):
1886 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001887
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001888 def test_set_issuer(self):
1889 """
Alex Chanb00ede22017-01-30 07:24:40 +00001890 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001891 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001892 """
1893 cert = X509()
1894 name = cert.get_issuer()
1895 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001896 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001897 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001898 assert (
1899 cert.get_issuer().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001900 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001901
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001902 def test_get_pubkey_uninitialized(self):
1903 """
Alex Chanb00ede22017-01-30 07:24:40 +00001904 When called on a certificate with no public key, `X509.get_pubkey`
1905 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001906 """
1907 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001908 with pytest.raises(Error):
1909 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001910
Alex Gaynor7778e792016-07-03 23:38:48 -04001911 def test_set_pubkey_wrong_type(self):
1912 """
Alex Chanb00ede22017-01-30 07:24:40 +00001913 `X509.set_pubkey` raises `TypeError` when given an object of the
1914 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001915 """
1916 cert = X509()
1917 with pytest.raises(TypeError):
1918 cert.set_pubkey(object())
1919
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001920 def test_subject_name_hash(self):
1921 """
Alex Chanb00ede22017-01-30 07:24:40 +00001922 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001923 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001924 """
1925 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor4cb05202019-02-02 11:06:41 -05001926 # SHA1
1927 assert cert.subject_name_hash() == 3278919224
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001928
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001929 def test_get_signature_algorithm(self):
1930 """
Alex Chanb00ede22017-01-30 07:24:40 +00001931 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001932 the algorithm used to sign the certificate.
1933 """
1934 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001935 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001936
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001937 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001938 """
Alex Chanb00ede22017-01-30 07:24:40 +00001939 `X509.get_signature_algorithm` raises `ValueError` if the signature
1940 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001941 """
1942 # This certificate has been modified to indicate a bogus OID in the
1943 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001944 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001945-----BEGIN CERTIFICATE-----
1946MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1947EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1948cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1949MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1950EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1951CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1952AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1953+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1954hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1955BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1956FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1957dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1958aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1959MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1960jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1961PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1962tgI5
1963-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001964"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001965 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001966 with pytest.raises(ValueError):
1967 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001968
Alex Gaynor37726112016-07-04 09:51:32 -04001969 def test_sign_bad_pubkey_type(self):
1970 """
Alex Chanb00ede22017-01-30 07:24:40 +00001971 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001972 """
1973 cert = X509()
1974 with pytest.raises(TypeError):
1975 cert.sign(object(), b"sha256")
1976
Alex Gaynor9939ba12017-06-25 16:28:24 -04001977 def test_convert_from_cryptography(self):
1978 crypto_cert = x509.load_pem_x509_certificate(
1979 intermediate_cert_pem, backend
1980 )
1981 cert = X509.from_cryptography(crypto_cert)
1982
1983 assert isinstance(cert, X509)
1984 assert cert.get_version() == crypto_cert.version.value
1985
1986 def test_convert_from_cryptography_unsupported_type(self):
1987 with pytest.raises(TypeError):
1988 X509.from_cryptography(object())
1989
1990 def test_convert_to_cryptography_key(self):
1991 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1992 crypto_cert = cert.to_cryptography()
1993
1994 assert isinstance(crypto_cert, x509.Certificate)
1995 assert crypto_cert.version.value == cert.get_version()
1996
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001997
Alex Chan9e2a9932017-01-25 14:29:19 +00001998class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001999 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002000 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002001 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002002
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002003 def test_type(self):
2004 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002005 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002007 assert X509Store is X509StoreType
2008 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002010 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002011 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002012 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002013 """
2014 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002015 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002016 store.add_cert(cert)
2017
Alex Chanfb078d82017-04-20 11:16:15 +01002018 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2019 def test_add_cert_wrong_args(self, cert):
2020 """
2021 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2022 as its first argument.
2023 """
2024 store = X509Store()
2025 with pytest.raises(TypeError):
2026 store.add_cert(cert)
2027
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002028 def test_add_cert_accepts_duplicate(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002029 """
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002030 `X509Store.add_cert` doesn't raise `OpenSSL.crypto.Error` if an attempt
2031 is made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002032 """
2033 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2034 store = X509Store()
2035 store.add_cert(cert)
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002036 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002037
2038
Alex Chanb00ede22017-01-30 07:24:40 +00002039class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002040 """
Alex Chanb00ede22017-01-30 07:24:40 +00002041 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002042 """
2043 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2044
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002045 def test_type(self):
2046 """
Alex Chanb00ede22017-01-30 07:24:40 +00002047 `PKCS12Type` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002048 """
Alex Chanb00ede22017-01-30 07:24:40 +00002049 assert PKCS12 is PKCS12Type
2050 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002051
Rick Deanf94096c2009-07-18 14:23:06 -05002052 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002053 """
Alex Chanb00ede22017-01-30 07:24:40 +00002054 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2055 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002056 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002057 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002058 assert None is p12.get_certificate()
2059 assert None is p12.get_privatekey()
2060 assert None is p12.get_ca_certificates()
2061 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002062
2063 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002064 """
Alex Chanb00ede22017-01-30 07:24:40 +00002065 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2066 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2067 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002068 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002069 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002070 for bad_arg in [3, PKey(), X509]:
2071 with pytest.raises(TypeError):
2072 p12.set_certificate(bad_arg)
2073 for bad_arg in [3, 'legbone', X509()]:
2074 with pytest.raises(TypeError):
2075 p12.set_privatekey(bad_arg)
2076 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2077 with pytest.raises(TypeError):
2078 p12.set_ca_certificates(bad_arg)
2079 for bad_arg in [6, ('foo', 'bar')]:
2080 with pytest.raises(TypeError):
2081 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002082
2083 def test_key_only(self):
2084 """
Alex Chanb00ede22017-01-30 07:24:40 +00002085 A `PKCS12` with only a private key can be exported using
2086 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002087 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002088 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002089 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002090 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002091 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002092 assert None is p12.get_certificate()
2093 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002094 try:
2095 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2096 except Error:
2097 # Some versions of OpenSSL will throw an exception
2098 # for this nearly useless PKCS12 we tried to generate:
2099 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2100 return
Rick Dean623ee362009-07-17 12:22:16 -05002101 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002102 assert None is p12.get_ca_certificates()
2103 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002104
2105 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2106 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002107 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002108
2109 def test_cert_only(self):
2110 """
Alex Chanb00ede22017-01-30 07:24:40 +00002111 A `PKCS12` with only a certificate can be exported using
2112 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002113 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002114 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002115 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002116 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002117 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002118 assert cert == p12.get_certificate()
2119 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002120 try:
2121 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2122 except Error:
2123 # Some versions of OpenSSL will throw an exception
2124 # for this nearly useless PKCS12 we tried to generate:
2125 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2126 return
Rick Dean623ee362009-07-17 12:22:16 -05002127 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002128 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002129
2130 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002131 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002132
2133 # Oh ho. It puts the certificate into the ca certificates list, in
2134 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2135 # that to check to see if it reconstructed the certificate we expected
2136 # it to. At some point, hopefully this will change so that
2137 # p12.get_certificate() is actually what returns the loaded
2138 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002139 assert (
2140 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002141 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002142
Alex Gaynor31287502015-09-05 16:11:27 -04002143 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2144 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002145 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002146 Generate a PKCS12 object with components from PEM. Verify that the set
2147 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002148 """
Rick Deanf94096c2009-07-18 14:23:06 -05002149 p12 = PKCS12()
2150 if cert_pem:
2151 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002152 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002153 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002154 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002155 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002156 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002157 ret = p12.set_ca_certificates(
2158 (load_certificate(FILETYPE_PEM, ca_pem),)
2159 )
Alex Chanb00ede22017-01-30 07:24:40 +00002160 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002161 if friendly_name:
2162 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002163 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002164 return p12
2165
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002166 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002167 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002168 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002169 Use openssl program to confirm three components are recoverable from a
2170 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002171 """
2172 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002173 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002174 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2175 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002176 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002177 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002178 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002179 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2180 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002181 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002182 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002183 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002184 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2185 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002186 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002187
Stephen Holsapple38482622014-04-05 20:29:34 -07002188 def verify_pkcs12_container(self, p12):
2189 """
2190 Verify that the PKCS#12 container contains the correct client
2191 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002192
2193 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002194 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002195 """
2196 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2197 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002198 assert (
2199 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002200 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002201
Rick Deanf94096c2009-07-18 14:23:06 -05002202 def test_load_pkcs12(self):
2203 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002204 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002205 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002206 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002207 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002208 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002209 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002210 pem,
2211 b"pkcs12",
2212 b"-export",
2213 b"-clcerts",
2214 b"-passout",
2215 b"pass:" + passwd
2216 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002217 p12 = load_pkcs12(p12_str, passphrase=passwd)
2218 self.verify_pkcs12_container(p12)
2219
Abraham Martinc5484ba2015-03-25 15:33:05 +00002220 def test_load_pkcs12_text_passphrase(self):
2221 """
2222 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002223 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002224 Using text as passphrase instead of bytes. DeprecationWarning expected.
2225 """
2226 pem = client_key_pem + client_cert_pem
2227 passwd = b"whatever"
2228 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2229 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002230 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002231 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002232 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002233 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002234 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002235 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002236 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002237
Abraham Martinc5484ba2015-03-25 15:33:05 +00002238 self.verify_pkcs12_container(p12)
2239
Stephen Holsapple38482622014-04-05 20:29:34 -07002240 def test_load_pkcs12_no_passphrase(self):
2241 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002242 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002243 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002244 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002245 """
2246 pem = client_key_pem + client_cert_pem
2247 p12_str = _runopenssl(
2248 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2249 p12 = load_pkcs12(p12_str)
2250 self.verify_pkcs12_container(p12)
2251
Stephen Holsapple38482622014-04-05 20:29:34 -07002252 def _dump_and_load(self, dump_passphrase, load_passphrase):
2253 """
2254 A helper method to dump and load a PKCS12 object.
2255 """
2256 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2257 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2258 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2259
Stephen Holsapple38482622014-04-05 20:29:34 -07002260 def test_load_pkcs12_null_passphrase_load_empty(self):
2261 """
2262 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002263 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002264 extracted and examined.
2265 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002266 self.verify_pkcs12_container(
2267 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002268
Stephen Holsapple38482622014-04-05 20:29:34 -07002269 def test_load_pkcs12_null_passphrase_load_null(self):
2270 """
2271 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002272 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002273 extracted and examined.
2274 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002275 self.verify_pkcs12_container(
2276 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002277
Stephen Holsapple38482622014-04-05 20:29:34 -07002278 def test_load_pkcs12_empty_passphrase_load_empty(self):
2279 """
2280 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002281 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002282 extracted and examined.
2283 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002284 self.verify_pkcs12_container(
2285 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002286
Stephen Holsapple38482622014-04-05 20:29:34 -07002287 def test_load_pkcs12_empty_passphrase_load_null(self):
2288 """
2289 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002290 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002291 extracted and examined.
2292 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002293 self.verify_pkcs12_container(
2294 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002295
Rick Deanee568302009-07-24 09:56:29 -05002296 def test_load_pkcs12_garbage(self):
2297 """
Alex Chanb00ede22017-01-30 07:24:40 +00002298 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002299 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002300 """
2301 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002302 with pytest.raises(Error) as err:
2303 load_pkcs12(b'fruit loops', passwd)
2304 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2305 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002306
Rick Deanf94096c2009-07-18 14:23:06 -05002307 def test_replace(self):
2308 """
Alex Chanb00ede22017-01-30 07:24:40 +00002309 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2310 cluster. `PKCS12.set_privatekey` replaces the private key.
2311 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002312 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002313 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2314 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2315 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002316 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002317 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002318 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002319 assert 1 == len(p12.get_ca_certificates())
2320 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002321 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002322 assert 2 == len(p12.get_ca_certificates())
2323 assert client_cert == p12.get_ca_certificates()[0]
2324 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002325
Rick Deanf94096c2009-07-18 14:23:06 -05002326 def test_friendly_name(self):
2327 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002328 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002329 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2330 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002331 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002332 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002333 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002334 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002335 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002336 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002337 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002338 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002339 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002340 # We would use the openssl program to confirm the friendly
2341 # name, but it is not possible. The pkcs12 command
2342 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002343 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002344 self.check_recovery(
2345 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2346 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002347
Rick Deanf94096c2009-07-18 14:23:06 -05002348 def test_various_empty_passphrases(self):
2349 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002350 Test that missing, None, and '' passphrases are identical for PKCS12
2351 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002352 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002353 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002354 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002355 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2356 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2357 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2358 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2359 self.check_recovery(
2360 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2361 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002362
Rick Deanf94096c2009-07-18 14:23:06 -05002363 def test_removing_ca_cert(self):
2364 """
Alex Chanb00ede22017-01-30 07:24:40 +00002365 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2366 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002367 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002368 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2369 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002370 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002371
Rick Deanf94096c2009-07-18 14:23:06 -05002372 def test_export_without_mac(self):
2373 """
Alex Chanb00ede22017-01-30 07:24:40 +00002374 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002375 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002376 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002377 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002378 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002379 self.check_recovery(
2380 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002381 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002382
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002383 def test_load_without_mac(self):
2384 """
2385 Loading a PKCS12 without a MAC does something other than crash.
2386 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002387 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002388 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2389 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002390 try:
2391 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2392 # The person who generated this PCKS12 should be flogged,
2393 # or better yet we should have a means to determine
2394 # whether a PCKS12 had a MAC that was verified.
2395 # Anyway, libopenssl chooses to allow it, so the
2396 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002397 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002398 except Error:
2399 # Failing here with an exception is preferred as some openssl
2400 # versions do.
2401 pass
Rick Dean623ee362009-07-17 12:22:16 -05002402
Rick Dean25bcc1f2009-07-20 11:53:13 -05002403 def test_zero_len_list_for_ca(self):
2404 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002405 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002406 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002407 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002408 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002409 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002410 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002411 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2412 self.check_recovery(
2413 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2414 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002415
Rick Deanf94096c2009-07-18 14:23:06 -05002416 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002417 """
Alex Chanb00ede22017-01-30 07:24:40 +00002418 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002419 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002420 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002421 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002422 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002423 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002424
Abraham Martinc5484ba2015-03-25 15:33:05 +00002425 def test_export_without_bytes(self):
2426 """
Alex Chanb00ede22017-01-30 07:24:40 +00002427 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002428 """
2429 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2430
Alex Chanb00ede22017-01-30 07:24:40 +00002431 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002432 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002433 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002434 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002435 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002436 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002437 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002438 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002439 dumped_p12,
2440 key=server_key_pem,
2441 cert=server_cert_pem,
2442 passwd=b"randomtext"
2443 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002444
Rick Deanf94096c2009-07-18 14:23:06 -05002445 def test_key_cert_mismatch(self):
2446 """
Alex Chanb00ede22017-01-30 07:24:40 +00002447 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002448 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002449 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002450 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002451 with pytest.raises(Error):
2452 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002453
2454
Rick Dean4c9ad612009-07-17 15:05:22 -05002455def _runopenssl(pem, *args):
2456 """
2457 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002458 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002459 """
Alex Gaynor6cbc69a2017-07-25 09:07:04 -04002460 proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002461 proc.stdin.write(pem)
2462 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002463 output = proc.stdout.read()
2464 proc.stdout.close()
2465 proc.wait()
2466 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002467
2468
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002469class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002470 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002471 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002472 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002473 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002474 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002475 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002476 """
2477 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002478
2479 assert True is key._only_public
2480 assert 2048 == key.bits()
2481 assert TYPE_RSA == key.type()
2482
2483 def test_invalid_type(self):
2484 """
2485 load_publickey doesn't support FILETYPE_TEXT.
2486 """
2487 with pytest.raises(ValueError):
2488 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2489
2490 def test_invalid_key_format(self):
2491 """
2492 load_publickey explodes on incorrect keys.
2493 """
2494 with pytest.raises(Error):
2495 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2496
2497 def test_tolerates_unicode_strings(self):
2498 """
2499 load_publickey works with text strings, not just bytes.
2500 """
2501 serialized = cleartextPublicKeyPEM.decode('ascii')
2502 key = load_publickey(FILETYPE_PEM, serialized)
2503 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2504
2505 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002506
2507
Alex Chanb00ede22017-01-30 07:24:40 +00002508class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002509 """
Alex Chanb00ede22017-01-30 07:24:40 +00002510 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002511 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002512
2513 def test_load_privatekey_invalid_format(self):
2514 """
Alex Chanb00ede22017-01-30 07:24:40 +00002515 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002516 """
Alex Chanb00ede22017-01-30 07:24:40 +00002517 with pytest.raises(ValueError):
2518 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002519
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002520 def test_load_privatekey_invalid_passphrase_type(self):
2521 """
Alex Chanb00ede22017-01-30 07:24:40 +00002522 `load_privatekey` raises `TypeError` if passed a passphrase that is
2523 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002524 """
Alex Chanb00ede22017-01-30 07:24:40 +00002525 with pytest.raises(TypeError):
2526 load_privatekey(
2527 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002528
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002529 def test_load_privatekey_wrongPassphrase(self):
2530 """
Alex Chanb00ede22017-01-30 07:24:40 +00002531 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2532 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002533 """
Alex Chanb00ede22017-01-30 07:24:40 +00002534 with pytest.raises(Error) as err:
2535 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2536 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002537
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002538 def test_load_privatekey_passphraseWrongType(self):
2539 """
Alex Chanb00ede22017-01-30 07:24:40 +00002540 `load_privatekey` raises `ValueError` when it is passeda passphrase
2541 with a private key encoded in a format, that doesn't support
2542 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002543 """
2544 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2545 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002546 with pytest.raises(ValueError):
2547 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002548
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002549 def test_load_privatekey_passphrase(self):
2550 """
Alex Chanb00ede22017-01-30 07:24:40 +00002551 `load_privatekey` can create a `PKey` object from an encrypted PEM
2552 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002553 """
2554 key = load_privatekey(
2555 FILETYPE_PEM, encryptedPrivateKeyPEM,
2556 encryptedPrivateKeyPEMPassphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002557 assert isinstance(key, PKeyType)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002558
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002559 def test_load_privatekey_passphrase_exception(self):
2560 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002561 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002562 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002563 """
2564 def cb(ignored):
2565 raise ArithmeticError
2566
Alex Gaynor791212d2015-09-05 15:46:08 -04002567 with pytest.raises(ArithmeticError):
2568 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002569
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002570 def test_load_privatekey_wrongPassphraseCallback(self):
2571 """
Alex Chanb00ede22017-01-30 07:24:40 +00002572 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002573 is passed an encrypted PEM and a passphrase callback which returns an
2574 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002575 """
2576 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002577
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002578 def cb(*a):
2579 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002580 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002581 with pytest.raises(Error) as err:
2582 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2583 assert called
2584 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002585
2586 def test_load_privatekey_passphraseCallback(self):
2587 """
Alex Chanb00ede22017-01-30 07:24:40 +00002588 `load_privatekey` can create a `PKey` object from an encrypted PEM
2589 string if given a passphrase callback which returns the correct
2590 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002591 """
2592 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002593
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002594 def cb(writing):
2595 called.append(writing)
2596 return encryptedPrivateKeyPEMPassphrase
2597 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002598 assert isinstance(key, PKeyType)
2599 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002600
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002601 def test_load_privatekey_passphrase_wrong_return_type(self):
2602 """
Alex Chanb00ede22017-01-30 07:24:40 +00002603 `load_privatekey` raises `ValueError` if the passphrase callback
2604 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002605 """
Alex Chanb00ede22017-01-30 07:24:40 +00002606 with pytest.raises(ValueError):
2607 load_privatekey(
2608 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002609
Alex Chanfb078d82017-04-20 11:16:15 +01002610 def test_dump_privatekey_wrong_args(self):
2611 """
2612 `dump_privatekey` raises `TypeError` if called with a `cipher`
2613 argument but no `passphrase` argument.
2614 """
2615 key = PKey()
2616 key.generate_key(TYPE_RSA, 512)
2617 with pytest.raises(TypeError):
2618 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2619
Paul Kehrercded9932017-06-29 18:43:42 -05002620 def test_dump_privatekey_not_rsa_key(self):
2621 """
2622 `dump_privatekey` raises `TypeError` if called with a key that is
2623 not RSA.
2624 """
2625 key = PKey()
2626 key.generate_key(TYPE_DSA, 512)
2627 with pytest.raises(TypeError):
2628 dump_privatekey(FILETYPE_TEXT, key)
2629
2630 def test_dump_privatekey_invalid_pkey(self):
2631 with pytest.raises(TypeError):
2632 dump_privatekey(FILETYPE_TEXT, object())
2633
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002634 def test_dump_privatekey_unknown_cipher(self):
2635 """
Alex Chanb00ede22017-01-30 07:24:40 +00002636 `dump_privatekey` raises `ValueError` if called with an unrecognized
2637 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002638 """
2639 key = PKey()
2640 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002641 with pytest.raises(ValueError):
2642 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002643
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002644 def test_dump_privatekey_invalid_passphrase_type(self):
2645 """
Alex Chanb00ede22017-01-30 07:24:40 +00002646 `dump_privatekey` raises `TypeError` if called with a passphrase which
2647 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002648 """
2649 key = PKey()
2650 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002651 with pytest.raises(TypeError):
2652 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002653
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002654 def test_dump_privatekey_invalid_filetype(self):
2655 """
Alex Chanb00ede22017-01-30 07:24:40 +00002656 `dump_privatekey` raises `ValueError` if called with an unrecognized
2657 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002658 """
2659 key = PKey()
2660 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002661 with pytest.raises(ValueError):
2662 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002663
Alex Chanb00ede22017-01-30 07:24:40 +00002664 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002665 """
Alex Chanb00ede22017-01-30 07:24:40 +00002666 `crypto.load_privatekey` should raise an error when the passphrase
2667 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002668 """
2669 def cb(ignored):
2670 return "a" * 1025
2671
Alex Gaynor791212d2015-09-05 15:46:08 -04002672 with pytest.raises(ValueError):
2673 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002674
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002675 def test_dump_privatekey_passphrase(self):
2676 """
Alex Chanb00ede22017-01-30 07:24:40 +00002677 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002678 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002679 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002680 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002681 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002682 assert isinstance(pem, binary_type)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002683 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002684 assert isinstance(loadedKey, PKeyType)
2685 assert loadedKey.type() == key.type()
2686 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002687
Alex Chanb00ede22017-01-30 07:24:40 +00002688 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002689 """
Alex Chanb00ede22017-01-30 07:24:40 +00002690 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2691 with a private key encoded in a format, that doesn't support
2692 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002693 """
2694 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002695 with pytest.raises(ValueError):
2696 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002697
Rick Dean5b7b6372009-04-01 11:34:06 -05002698 def test_dump_certificate(self):
2699 """
Alex Chanb00ede22017-01-30 07:24:40 +00002700 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002701 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002702 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002703 cert = load_certificate(FILETYPE_PEM, pemData)
2704 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002705 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002706 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002707 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002708 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002709 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2710 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002711 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002712 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002713 good_text = _runopenssl(
2714 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002715 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002716
Alex Gaynor37726112016-07-04 09:51:32 -04002717 def test_dump_certificate_bad_type(self):
2718 """
Alex Chanb00ede22017-01-30 07:24:40 +00002719 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002720 a bad type.
2721 """
2722 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2723 with pytest.raises(ValueError):
2724 dump_certificate(object(), cert)
2725
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002726 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002727 """
Alex Chanb00ede22017-01-30 07:24:40 +00002728 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002729 """
2730 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002731 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002732 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002733 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002734
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002735 def test_dump_privatekey_asn1(self):
2736 """
Alex Chanb00ede22017-01-30 07:24:40 +00002737 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002738 """
2739 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2740 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2741
Rick Dean5b7b6372009-04-01 11:34:06 -05002742 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002743 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002744 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002745 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002746 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2747 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002748 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002749
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002750 def test_dump_privatekey_text(self):
2751 """
Alex Chanb00ede22017-01-30 07:24:40 +00002752 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002753 """
2754 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2755 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2756
Rick Dean5b7b6372009-04-01 11:34:06 -05002757 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002758 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002759 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002760
Cory Benfield6492f7c2015-10-27 16:57:58 +09002761 def test_dump_publickey_pem(self):
2762 """
Cory Benfield11c10192015-10-27 17:23:03 +09002763 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002764 """
2765 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2766 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002767 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002768
2769 def test_dump_publickey_asn1(self):
2770 """
Cory Benfield11c10192015-10-27 17:23:03 +09002771 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002772 """
2773 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2774 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2775 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2776 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002777 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002778
Cory Benfielde02c7d82015-10-27 17:34:49 +09002779 def test_dump_publickey_invalid_type(self):
2780 """
2781 dump_publickey doesn't support FILETYPE_TEXT.
2782 """
2783 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2784
2785 with pytest.raises(ValueError):
2786 dump_publickey(FILETYPE_TEXT, key)
2787
Rick Dean5b7b6372009-04-01 11:34:06 -05002788 def test_dump_certificate_request(self):
2789 """
Alex Chanb00ede22017-01-30 07:24:40 +00002790 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002791 """
Alex Gaynor31287502015-09-05 16:11:27 -04002792 req = load_certificate_request(
2793 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002794 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002795 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002796 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002797 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002798 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002799 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2800 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002801 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002802 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002803 good_text = _runopenssl(
2804 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002805 assert dumped_text == good_text
2806 with pytest.raises(ValueError):
2807 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002808
Alex Chanb00ede22017-01-30 07:24:40 +00002809 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002810 """
Alex Chanb00ede22017-01-30 07:24:40 +00002811 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002812 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002813 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002814 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002815 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002816
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002817 def cb(writing):
2818 called.append(writing)
2819 return passphrase
2820 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002821 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002822 assert isinstance(pem, binary_type)
2823 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002824 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002825 assert isinstance(loadedKey, PKeyType)
2826 assert loadedKey.type() == key.type()
2827 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002828
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002829 def test_dump_privatekey_passphrase_exception(self):
2830 """
Alex Chanb00ede22017-01-30 07:24:40 +00002831 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002832 by the passphrase callback.
2833 """
2834 def cb(ignored):
2835 raise ArithmeticError
2836
2837 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002838 with pytest.raises(ArithmeticError):
2839 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002840
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002841 def test_dump_privatekey_passphraseCallbackLength(self):
2842 """
Alex Chanb00ede22017-01-30 07:24:40 +00002843 `crypto.dump_privatekey` should raise an error when the passphrase
2844 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002845 """
2846 def cb(ignored):
2847 return "a" * 1025
2848
2849 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002850 with pytest.raises(ValueError):
2851 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002852
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002853 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002854 """
Alex Chanb00ede22017-01-30 07:24:40 +00002855 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2856 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002857 """
2858 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002859 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002860
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002861 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002862 """
Alex Chanb00ede22017-01-30 07:24:40 +00002863 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2864 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002865 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002866 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002867 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002868
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002869 def test_load_pkcs7_data_invalid(self):
2870 """
Alex Chanb00ede22017-01-30 07:24:40 +00002871 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002872 """
Alex Chanb00ede22017-01-30 07:24:40 +00002873 with pytest.raises(Error):
2874 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002875
Alex Gaynor09a386e2016-07-03 09:32:44 -04002876 def test_load_pkcs7_type_invalid(self):
2877 """
Alex Chanb00ede22017-01-30 07:24:40 +00002878 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002879 """
2880 with pytest.raises(ValueError):
2881 load_pkcs7_data(object(), b"foo")
2882
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002883
Alex Chan9e2a9932017-01-25 14:29:19 +00002884class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002885 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002886 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002887 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002888
Alex Chan9e2a9932017-01-25 14:29:19 +00002889 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002890 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002891 If the file type passed to `load_certificate_request` is neither
2892 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002893 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002894 with pytest.raises(ValueError):
2895 load_certificate_request(object(), b"")
2896 with pytest.raises(ValueError):
2897 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002898
Alex Gaynor37726112016-07-04 09:51:32 -04002899 def test_bad_certificate(self):
2900 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002901 If the bytes passed to `load_certificate` are not a valid certificate,
2902 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002903 """
2904 with pytest.raises(Error):
2905 load_certificate(FILETYPE_ASN1, b"lol")
2906
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002907
Alex Chanb00ede22017-01-30 07:24:40 +00002908class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002909 """
Alex Chanb00ede22017-01-30 07:24:40 +00002910 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002911 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002912
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002913 def test_type(self):
2914 """
Alex Chanb00ede22017-01-30 07:24:40 +00002915 `PKCS7` is a type object.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002916 """
Alex Chanb00ede22017-01-30 07:24:40 +00002917 assert isinstance(PKCS7, type)
2918 assert PKCS7Type.__name__ == 'PKCS7'
2919 assert PKCS7 is PKCS7Type
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002920
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002921 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002922 """
Alex Chanb00ede22017-01-30 07:24:40 +00002923 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2924 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002925 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002926 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002927 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002928
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002929 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002930 """
Alex Chanb00ede22017-01-30 07:24:40 +00002931 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2932 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002933 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002934 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002935 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002936
Alex Chanb00ede22017-01-30 07:24:40 +00002937 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002938 """
Alex Chanb00ede22017-01-30 07:24:40 +00002939 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002940 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002941 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002942 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002943 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002944
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002945 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002946 """
Alex Chanb00ede22017-01-30 07:24:40 +00002947 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2948 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002949 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002950 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002951 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002952
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002953 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002954 """
Alex Chanb00ede22017-01-30 07:24:40 +00002955 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002956 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002957 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002958 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002959 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002960
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002961 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002962 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002963 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002964 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002965 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002966 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002967 with pytest.raises(AttributeError):
2968 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002969
2970
Alex Chanb00ede22017-01-30 07:24:40 +00002971class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002972 """
Alex Chanb00ede22017-01-30 07:24:40 +00002973 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002974 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002975
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002976 def signable(self):
2977 """
Alex Chanb00ede22017-01-30 07:24:40 +00002978 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002979 """
2980 return NetscapeSPKI()
2981
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002982 def test_type(self):
2983 """
Alex Chanb00ede22017-01-30 07:24:40 +00002984 `NetscapeSPKI` and `NetscapeSPKIType` refer to the same type object
2985 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002986 """
Alex Chanb00ede22017-01-30 07:24:40 +00002987 assert NetscapeSPKI is NetscapeSPKIType
2988 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002989
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002990 def test_construction(self):
2991 """
Alex Chanb00ede22017-01-30 07:24:40 +00002992 `NetscapeSPKI` returns an instance of `NetscapeSPKIType`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002993 """
2994 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002995 assert isinstance(nspki, NetscapeSPKIType)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002996
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002997 def test_invalid_attribute(self):
2998 """
Alex Chanb00ede22017-01-30 07:24:40 +00002999 Accessing a non-existent attribute of a `NetscapeSPKI` instance
3000 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04003001 """
3002 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00003003 with pytest.raises(AttributeError):
3004 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04003005
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003006 def test_b64_encode(self):
3007 """
Alex Chanb00ede22017-01-30 07:24:40 +00003008 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003009 """
3010 nspki = NetscapeSPKI()
3011 blob = nspki.b64_encode()
Alex Chanb00ede22017-01-30 07:24:40 +00003012 assert isinstance(blob, binary_type)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003013
3014
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003015class TestRevoked(object):
3016 """
Alex Chandeec9342016-12-19 22:00:38 +00003017 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003018 """
3019 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
3020 """
3021 The get_reason method on the Revoked class checks to see if the
3022 extension is NID_crl_reason and should skip it otherwise. This test
3023 loads a CRL with extensions it should ignore.
3024 """
3025 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3026 revoked = crl.get_revoked()
3027 reason = revoked[1].get_reason()
3028 assert reason == b'Unspecified'
3029
3030 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3031 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3032 revoked = crl.get_revoked()
3033 revoked[1].set_reason(None)
3034 reason = revoked[1].get_reason()
3035 assert reason is None
3036
Rick Dean536ba022009-07-24 23:57:27 -05003037 def test_construction(self):
3038 """
Alex Chandeec9342016-12-19 22:00:38 +00003039 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3040 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003041 """
3042 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003043 assert isinstance(revoked, Revoked)
3044 assert type(revoked) == Revoked
3045 assert revoked.get_serial() == b'00'
3046 assert revoked.get_rev_date() is None
3047 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003048
Rick Dean536ba022009-07-24 23:57:27 -05003049 def test_serial(self):
3050 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003051 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003052 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003053 """
3054 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003055 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003056 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003057 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003058 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003059
Alex Gaynore7f51982016-09-11 11:48:14 -04003060 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003061 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003062 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003063
Alex Chandeec9342016-12-19 22:00:38 +00003064 with pytest.raises(ValueError):
3065 revoked.set_serial(b'pqrst')
3066 with pytest.raises(TypeError):
3067 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003068
Rick Dean536ba022009-07-24 23:57:27 -05003069 def test_date(self):
3070 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003071 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003072 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003073 """
3074 revoked = Revoked()
3075 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003076 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003077
Alex Gaynore7f51982016-09-11 11:48:14 -04003078 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003079 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003080 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003081 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003082 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003083
Rick Dean6385faf2009-07-26 00:07:47 -05003084 def test_reason(self):
3085 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003086 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003087 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3088 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003089 """
3090 revoked = Revoked()
3091 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003092 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003093 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003094 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003095 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003096 assert (
3097 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003098 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003099 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003100
3101 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003102 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003103
Alex Chanfb078d82017-04-20 11:16:15 +01003104 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3105 def test_set_reason_wrong_args(self, reason):
3106 """
3107 `Revoked.set_reason` raises `TypeError` if called with an argument
3108 which is neither `None` nor a byte string.
3109 """
3110 revoked = Revoked()
3111 with pytest.raises(TypeError):
3112 revoked.set_reason(reason)
3113
Alex Chandeec9342016-12-19 22:00:38 +00003114 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003115 """
Alex Chandeec9342016-12-19 22:00:38 +00003116 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3117 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003118 """
3119 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003120 with pytest.raises(ValueError):
3121 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003122
3123
Alex Chan7be83a52017-01-24 15:19:29 +00003124class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003125 """
Alex Chan7be83a52017-01-24 15:19:29 +00003126 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003127 """
3128 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3129 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3130
Dan Sully44e767a2016-06-04 18:05:27 -07003131 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3132 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3133 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3134 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3135 intermediate_server_cert = load_certificate(
3136 FILETYPE_PEM, intermediate_server_cert_pem)
3137 intermediate_server_key = load_privatekey(
3138 FILETYPE_PEM, intermediate_server_key_pem)
3139
Rick Dean536ba022009-07-24 23:57:27 -05003140 def test_construction(self):
3141 """
Alex Chan7be83a52017-01-24 15:19:29 +00003142 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003143 that it is empty
3144 """
3145 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003146 assert isinstance(crl, CRL)
3147 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003148
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003149 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003150 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003151 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003152 """
3153 crl = CRL()
3154 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003155 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003156 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003157 revoked.set_serial(b'3ab')
3158 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003159 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003160 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003161
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003162 def test_export_pem(self):
3163 """
3164 If not passed a format, ``CRL.export`` returns a "PEM" format string
3165 representing a serial number, a revoked reason, and certificate issuer
3166 information.
3167 """
Rick Dean536ba022009-07-24 23:57:27 -05003168 # PEM format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003169 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003170 self.cert, self.pkey, days=20, digest=b"sha256"
3171 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003172 crl = x509.load_pem_x509_crl(dumped_crl, backend)
3173 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3174 assert revoked is not None
3175 assert crl.issuer == x509.Name([
3176 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3177 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3178 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3179 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3180 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3181 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003182
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003183 def test_export_der(self):
3184 """
3185 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3186 "DER" format string representing a serial number, a revoked reason, and
3187 certificate issuer information.
3188 """
3189 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003190
3191 # DER format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003192 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003193 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3194 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003195 crl = x509.load_der_x509_crl(dumped_crl, backend)
3196 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3197 assert revoked is not None
3198 assert crl.issuer == x509.Name([
3199 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3200 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3201 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3202 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3203 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3204 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003205
Alex Gaynore466bc92017-07-06 23:43:47 -04003206 # Flaky because we compare the output of running commands which sometimes
3207 # varies by 1 second
3208 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003209 def test_export_text(self):
3210 """
3211 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3212 text format string like the one produced by the openssl command line
3213 tool.
3214 """
3215 crl = self._get_crl()
3216
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003217 dumped_crl = crl.export(
3218 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3219 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003220 text = _runopenssl(
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003221 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER",
3222 b"-nameopt", b""
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003223 )
Rick Dean536ba022009-07-24 23:57:27 -05003224
3225 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003226 dumped_text = crl.export(
3227 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3228 )
Alex Chan7be83a52017-01-24 15:19:29 +00003229 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003230
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003231 def test_export_custom_digest(self):
3232 """
3233 If passed the name of a digest function, ``CRL.export`` uses a
3234 signature algorithm based on that digest function.
3235 """
3236 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003237 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003238 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003239 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003240
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003241 def test_export_md5_digest(self):
3242 """
3243 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3244 not emit a deprecation warning.
3245 """
3246 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003247 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003248 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003249 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003250 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3251 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003252 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003253
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003254 def test_export_default_digest(self):
3255 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003256 If not passed the name of a digest function, ``CRL.export`` raises a
3257 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003258 """
3259 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003260 with pytest.raises(TypeError):
3261 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003262
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003263 def test_export_invalid(self):
3264 """
Alex Chan7be83a52017-01-24 15:19:29 +00003265 If `CRL.export` is used with an uninitialized `X509` instance,
3266 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003267 """
3268 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003269 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003270 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003271
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003272 def test_add_revoked_keyword(self):
3273 """
Alex Chan7be83a52017-01-24 15:19:29 +00003274 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003275 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003276 """
3277 crl = CRL()
3278 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003279 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003280 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003281 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003282 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003283
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003284 def test_export_wrong_args(self):
3285 """
Alex Chan7be83a52017-01-24 15:19:29 +00003286 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003287 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003288 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003289 """
3290 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003291 with pytest.raises(TypeError):
3292 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3293 with pytest.raises(TypeError):
3294 crl.export(self.cert, None, FILETYPE_PEM, 10)
3295 with pytest.raises(TypeError):
3296 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003297 with pytest.raises(TypeError):
3298 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003299
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003300 def test_export_unknown_filetype(self):
3301 """
Alex Chan7be83a52017-01-24 15:19:29 +00003302 Calling `OpenSSL.CRL.export` with a file type other than
3303 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3304 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003305 """
3306 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003307 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003308 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003309
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003310 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003311 """
Alex Chan7be83a52017-01-24 15:19:29 +00003312 Calling `OpenSSL.CRL.export` with an unsupported digest results
3313 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003314 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003315 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003316 with pytest.raises(ValueError):
3317 crl.export(
3318 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003319
Rick Dean536ba022009-07-24 23:57:27 -05003320 def test_get_revoked(self):
3321 """
Alex Chan7be83a52017-01-24 15:19:29 +00003322 Use python to create a simple CRL with two revocations. Get back the
3323 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003324 """
3325 crl = CRL()
3326
3327 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003328 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003329 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003330 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003331 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003332 revoked.set_serial(b'100')
3333 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003334 crl.add_revoked(revoked)
3335
3336 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003337 assert len(revs) == 2
3338 assert type(revs[0]) == Revoked
3339 assert type(revs[1]) == Revoked
3340 assert revs[0].get_serial() == b'03AB'
3341 assert revs[1].get_serial() == b'0100'
3342 assert revs[0].get_rev_date() == now
3343 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003344
Rick Dean536ba022009-07-24 23:57:27 -05003345 def test_load_crl(self):
3346 """
Alex Chan7be83a52017-01-24 15:19:29 +00003347 Load a known CRL and inspect its revocations. Both EM and DER formats
3348 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003349 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003350 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003351 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003352 assert len(revs) == 2
3353 assert revs[0].get_serial() == b'03AB'
3354 assert revs[0].get_reason() is None
3355 assert revs[1].get_serial() == b'0100'
3356 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003357
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003358 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003359 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003360 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003361 assert len(revs) == 2
3362 assert revs[0].get_serial() == b'03AB'
3363 assert revs[0].get_reason() is None
3364 assert revs[1].get_serial() == b'0100'
3365 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003366
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003367 def test_load_crl_bad_filetype(self):
3368 """
Alex Chan7be83a52017-01-24 15:19:29 +00003369 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3370 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003371 """
Alex Chan7be83a52017-01-24 15:19:29 +00003372 with pytest.raises(ValueError):
3373 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003374
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003375 def test_load_crl_bad_data(self):
3376 """
Alex Chan7be83a52017-01-24 15:19:29 +00003377 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3378 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003379 """
Alex Chan7be83a52017-01-24 15:19:29 +00003380 with pytest.raises(Error):
3381 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003382
Dan Sully44e767a2016-06-04 18:05:27 -07003383 def test_get_issuer(self):
3384 """
Alex Chan7be83a52017-01-24 15:19:29 +00003385 Load a known CRL and assert its issuer's common name is what we expect
3386 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003387 """
3388 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003389 assert isinstance(crl.get_issuer(), X509Name)
3390 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003391
Dominic Chenf05b2122015-10-13 16:32:35 +00003392 def test_dump_crl(self):
3393 """
3394 The dumped CRL matches the original input.
3395 """
3396 crl = load_crl(FILETYPE_PEM, crlData)
3397 buf = dump_crl(FILETYPE_PEM, crl)
3398 assert buf == crlData
3399
Dan Sully44e767a2016-06-04 18:05:27 -07003400 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3401 """
3402 Create a CRL.
3403
3404 :param list[X509] certs: A list of certificates to revoke.
3405 :rtype: CRL
3406 """
3407 crl = CRL()
3408 for cert in certs:
3409 revoked = Revoked()
3410 # FIXME: This string splicing is an unfortunate implementation
3411 # detail that has been reported in
3412 # https://github.com/pyca/pyopenssl/issues/258
3413 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3414 revoked.set_serial(serial)
3415 revoked.set_reason(b'unspecified')
3416 revoked.set_rev_date(b'20140601000000Z')
3417 crl.add_revoked(revoked)
3418 crl.set_version(1)
3419 crl.set_lastUpdate(b'20140601000000Z')
3420 crl.set_nextUpdate(b'20180601000000Z')
3421 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3422 return crl
3423
3424 def test_verify_with_revoked(self):
3425 """
Alex Chan7be83a52017-01-24 15:19:29 +00003426 `verify_certificate` raises error when an intermediate certificate is
3427 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003428 """
3429 store = X509Store()
3430 store.add_cert(self.root_cert)
3431 store.add_cert(self.intermediate_cert)
3432 root_crl = self._make_test_crl(
3433 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3434 intermediate_crl = self._make_test_crl(
3435 self.intermediate_cert, self.intermediate_key, certs=[])
3436 store.add_crl(root_crl)
3437 store.add_crl(intermediate_crl)
3438 store.set_flags(
3439 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3440 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003441 with pytest.raises(X509StoreContextError) as err:
3442 store_ctx.verify_certificate()
3443 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003444
3445 def test_verify_with_missing_crl(self):
3446 """
Alex Chan7be83a52017-01-24 15:19:29 +00003447 `verify_certificate` raises error when an intermediate certificate's
3448 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003449 """
3450 store = X509Store()
3451 store.add_cert(self.root_cert)
3452 store.add_cert(self.intermediate_cert)
3453 root_crl = self._make_test_crl(
3454 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3455 store.add_crl(root_crl)
3456 store.set_flags(
3457 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3458 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003459 with pytest.raises(X509StoreContextError) as err:
3460 store_ctx.verify_certificate()
3461 assert err.value.args[0][2] == 'unable to get certificate CRL'
3462 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003463
Paul Kehrer41c10242017-06-29 18:24:17 -05003464 def test_convert_from_cryptography(self):
3465 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3466 crl = CRL.from_cryptography(crypto_crl)
3467 assert isinstance(crl, CRL)
3468
3469 def test_convert_from_cryptography_unsupported_type(self):
3470 with pytest.raises(TypeError):
3471 CRL.from_cryptography(object())
3472
3473 def test_convert_to_cryptography_key(self):
3474 crl = load_crl(FILETYPE_PEM, crlData)
3475 crypto_crl = crl.to_cryptography()
3476 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3477
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003478
Alex Chan7be83a52017-01-24 15:19:29 +00003479class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003480 """
Alex Chan7be83a52017-01-24 15:19:29 +00003481 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003482 """
3483 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3484 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003485 intermediate_server_cert = load_certificate(
3486 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003487
3488 def test_valid(self):
3489 """
Alex Chan7be83a52017-01-24 15:19:29 +00003490 `verify_certificate` returns ``None`` when called with a certificate
3491 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003492 """
3493 store = X509Store()
3494 store.add_cert(self.root_cert)
3495 store.add_cert(self.intermediate_cert)
3496 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003497 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003498
3499 def test_reuse(self):
3500 """
Alex Chan7be83a52017-01-24 15:19:29 +00003501 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003502 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003503 """
3504 store = X509Store()
3505 store.add_cert(self.root_cert)
3506 store.add_cert(self.intermediate_cert)
3507 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003508 assert store_ctx.verify_certificate() is None
3509 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003510
3511 def test_trusted_self_signed(self):
3512 """
Alex Chan7be83a52017-01-24 15:19:29 +00003513 `verify_certificate` returns ``None`` when called with a self-signed
3514 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003515 """
3516 store = X509Store()
3517 store.add_cert(self.root_cert)
3518 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003519 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003520
3521 def test_untrusted_self_signed(self):
3522 """
Alex Chan7be83a52017-01-24 15:19:29 +00003523 `verify_certificate` raises error when a self-signed certificate is
3524 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003525 """
3526 store = X509Store()
3527 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003528 with pytest.raises(X509StoreContextError) as exc:
3529 store_ctx.verify_certificate()
3530
3531 assert exc.value.args[0][2] == 'self signed certificate'
3532 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003533
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003534 def test_invalid_chain_no_root(self):
3535 """
Alex Chan7be83a52017-01-24 15:19:29 +00003536 `verify_certificate` raises error when a root certificate is missing
3537 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003538 """
3539 store = X509Store()
3540 store.add_cert(self.intermediate_cert)
3541 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003542
3543 with pytest.raises(X509StoreContextError) as exc:
3544 store_ctx.verify_certificate()
3545
3546 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3547 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003548
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003549 def test_invalid_chain_no_intermediate(self):
3550 """
Alex Chan7be83a52017-01-24 15:19:29 +00003551 `verify_certificate` raises error when an intermediate certificate is
3552 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003553 """
3554 store = X509Store()
3555 store.add_cert(self.root_cert)
3556 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003557
Alex Gaynor85b49702015-09-05 16:30:59 -04003558 with pytest.raises(X509StoreContextError) as exc:
3559 store_ctx.verify_certificate()
3560
3561 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3562 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003563
Stephen Holsapple46a09252015-02-12 14:45:43 -08003564 def test_modification_pre_verify(self):
3565 """
Alex Chan7be83a52017-01-24 15:19:29 +00003566 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003567 instantiation.
3568 """
3569 store_bad = X509Store()
3570 store_bad.add_cert(self.intermediate_cert)
3571 store_good = X509Store()
3572 store_good.add_cert(self.root_cert)
3573 store_good.add_cert(self.intermediate_cert)
3574 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003575
3576 with pytest.raises(X509StoreContextError) as exc:
3577 store_ctx.verify_certificate()
3578
3579 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3580 assert exc.value.certificate.get_subject().CN == 'intermediate'
3581
Stephen Holsapple46a09252015-02-12 14:45:43 -08003582 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003583 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003584
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003585 def test_verify_with_time(self):
3586 """
3587 `verify_certificate` raises error when the verification time is
3588 set at notAfter.
3589 """
3590 store = X509Store()
3591 store.add_cert(self.root_cert)
3592 store.add_cert(self.intermediate_cert)
3593
3594 expire_time = self.intermediate_server_cert.get_notAfter()
3595 expire_datetime = datetime.strptime(
3596 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3597 )
3598 store.set_time(expire_datetime)
3599
3600 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3601 with pytest.raises(X509StoreContextError) as exc:
3602 store_ctx.verify_certificate()
3603
3604 assert exc.value.args[0][2] == 'certificate has expired'
3605
Stephen Holsapple46a09252015-02-12 14:45:43 -08003606
Alex Chan7be83a52017-01-24 15:19:29 +00003607class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003608 """
Alex Chan7be83a52017-01-24 15:19:29 +00003609 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003610 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003611
James Yonan7c2e5d32010-02-27 05:45:50 -07003612 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003613 """
Alex Chan7be83a52017-01-24 15:19:29 +00003614 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003615 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003616 content = (
3617 b"It was a bright cold day in April, and the clocks were striking "
3618 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3619 b"effort to escape the vile wind, slipped quickly through the "
3620 b"glass doors of Victory Mansions, though not quickly enough to "
3621 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003622
3623 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003624 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003625 # verify the content with this cert
3626 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3627 # certificate unrelated to priv_key, used to trigger an error
3628 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003629
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003630 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003631 sig = sign(priv_key, content, digest)
3632
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003633 # Verify the signature of content, will throw an exception if
3634 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003635 verify(good_cert, sig, content, digest)
3636
3637 # This should fail because the certificate doesn't match the
3638 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003639 with pytest.raises(Error):
3640 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003641
3642 # This should fail because we've "tainted" the content after
3643 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003644 with pytest.raises(Error):
3645 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003646
3647 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003648 with pytest.raises(ValueError):
3649 sign(priv_key, content, "strange-digest")
3650 with pytest.raises(ValueError):
3651 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003652
Abraham Martinc5484ba2015-03-25 15:33:05 +00003653 def test_sign_verify_with_text(self):
3654 """
Alex Chan7be83a52017-01-24 15:19:29 +00003655 `sign` generates a cryptographic signature which
3656 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003657 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003658 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003659 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003660 b"It was a bright cold day in April, and the clocks were striking "
3661 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3662 b"effort to escape the vile wind, slipped quickly through the "
3663 b"glass doors of Victory Mansions, though not quickly enough to "
3664 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003665 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003666
3667 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3668 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3669 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003670 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003671 simplefilter("always")
3672 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003673 assert (
3674 "{0} for data is no longer accepted, use bytes".format(
3675 WARNING_TYPE_EXPECTED
3676 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003677
Alex Chan7be83a52017-01-24 15:19:29 +00003678 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003679 simplefilter("always")
3680 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003681 assert (
3682 "{0} for data is no longer accepted, use bytes".format(
3683 WARNING_TYPE_EXPECTED
3684 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003685
Paul Kehrer59d26252017-07-20 10:45:54 +02003686 def test_sign_verify_ecdsa(self):
3687 """
3688 `sign` generates a cryptographic signature which `verify` can check.
3689 ECDSA Signatures in the X9.62 format may have variable length,
3690 different from the length of the private key.
3691 """
3692 content = (
3693 b"It was a bright cold day in April, and the clocks were striking "
3694 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3695 b"effort to escape the vile wind, slipped quickly through the "
3696 b"glass doors of Victory Mansions, though not quickly enough to "
3697 b"prevent a swirl of gritty dust from entering along with him."
3698 ).decode("ascii")
3699 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3700 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3701 sig = sign(priv_key, content, "sha1")
3702 verify(cert, sig, content, "sha1")
3703
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003704 def test_sign_nulls(self):
3705 """
Alex Chan7be83a52017-01-24 15:19:29 +00003706 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003707 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003708 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003709 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3710 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3711 sig = sign(priv_key, content, "sha1")
3712 verify(good_cert, sig, content, "sha1")
3713
Colleen Murphye09399b2016-03-01 17:40:49 -08003714 def test_sign_with_large_key(self):
3715 """
Alex Chan7be83a52017-01-24 15:19:29 +00003716 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003717 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003718 content = (
3719 b"It was a bright cold day in April, and the clocks were striking "
3720 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3721 b"effort to escape the vile wind, slipped quickly through the "
3722 b"glass doors of Victory Mansions, though not quickly enough to "
3723 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003724
3725 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3726 sign(priv_key, content, "sha1")
3727
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003728
Alex Chan63ef9bc2016-12-19 12:02:06 +00003729class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003730 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003731 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3732 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003733 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003734
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003735 def test_set(self):
3736 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003737 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003738 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003739 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003740
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003741 def test_a_curve(self):
3742 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003743 `get_elliptic_curve` can be used to retrieve a particular supported
3744 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003745 """
3746 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003747 curve = next(iter(curves))
3748 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003749
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003750 def test_not_a_curve(self):
3751 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003752 `get_elliptic_curve` raises `ValueError` if called with a name which
3753 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003754 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003755 with pytest.raises(ValueError):
3756 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003757
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003758 def test_repr(self):
3759 """
3760 The string representation of a curve object includes simply states the
3761 object is a curve and what its name is.
3762 """
3763 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003764 curve = next(iter(curves))
3765 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003766
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003767 def test_to_EC_KEY(self):
3768 """
3769 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003770 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003771 """
3772 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003773 curve = next(iter(curves))
3774 # It's not easy to assert anything about this object. However, see
3775 # leakcheck/crypto.py for a test that demonstrates it at least does
3776 # not leak memory.
3777 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003778
3779
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003780class EllipticCurveFactory(object):
3781 """
3782 A helper to get the names of two curves.
3783 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003784
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003785 def __init__(self):
3786 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003787 self.curve_name = next(curves).name
3788 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003789
3790
Alex Chan63ef9bc2016-12-19 12:02:06 +00003791class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003792 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003793 Tests `_EllipticCurve`'s implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003794 """
3795 curve_factory = EllipticCurveFactory()
3796
3797 if curve_factory.curve_name is None:
3798 skip = "There are no curves available there can be no curve objects."
3799
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003800 def anInstance(self):
3801 """
3802 Get the curve object for an arbitrary curve supported by the system.
3803 """
3804 return get_elliptic_curve(self.curve_factory.curve_name)
3805
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003806 def anotherInstance(self):
3807 """
3808 Get the curve object for an arbitrary curve supported by the system -
3809 but not the one returned by C{anInstance}.
3810 """
3811 return get_elliptic_curve(self.curve_factory.another_curve_name)
3812
3813
Alex Chan63ef9bc2016-12-19 12:02:06 +00003814class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003815 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003816 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3817 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003818 """
3819 curve_factory = EllipticCurveFactory()
3820
3821 if curve_factory.curve_name is None:
3822 skip = "There are no curves available there can be no curve objects."
3823
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003824 def test_contains(self):
3825 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003826 The ``in`` operator reports that a `set` containing a curve does
3827 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003828 """
3829 curve = get_elliptic_curve(self.curve_factory.curve_name)
3830 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003831 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003832
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003833 def test_does_not_contain(self):
3834 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003835 The ``in`` operator reports that a `set` not containing a curve
3836 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003837 """
3838 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003839 curves = set([
3840 get_elliptic_curve(self.curve_factory.another_curve_name)
3841 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003842 assert curve not in curves