blob: 22a5c886eddaee87abb3e1b83b0ba0cab0523053 [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()
576 pkey.generate_key(TYPE_RSA, 384)
577 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 """
920 bits = 128
921 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
Alex Chan9e2a9932017-01-25 14:29:19 +00001217 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001218 """
1219 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001220 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001221 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001222 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001223 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001224 with pytest.raises(Error):
1225 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001226
1227
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001228class _PKeyInteractionTestsMixin:
1229 """
1230 Tests which involve another thing and a PKey.
1231 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001232
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001233 def signable(self):
1234 """
Alex Chanfb078d82017-04-20 11:16:15 +01001235 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001236 """
1237 raise NotImplementedError()
1238
Alex Chanb00ede22017-01-30 07:24:40 +00001239 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001240 """
Alex Chanb00ede22017-01-30 07:24:40 +00001241 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001242 """
1243 request = self.signable()
1244 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001245 with pytest.raises(ValueError):
1246 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001247
Alex Chanb00ede22017-01-30 07:24:40 +00001248 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001249 """
Alex Chanb00ede22017-01-30 07:24:40 +00001250 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1251 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001252 """
1253 request = self.signable()
1254 key = PKey()
1255 key.generate_key(TYPE_RSA, 512)
1256 request.set_pubkey(key)
1257 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001258 with pytest.raises(ValueError):
1259 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001260
Alex Chanb00ede22017-01-30 07:24:40 +00001261 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001262 """
Alex Chanb00ede22017-01-30 07:24:40 +00001263 `X509Req.sign` raises `ValueError` when passed a digest name which is
1264 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001265 """
1266 request = self.signable()
1267 key = PKey()
1268 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001269 with pytest.raises(ValueError):
1270 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001271
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001272 def test_sign(self):
1273 """
Alex Chanb00ede22017-01-30 07:24:40 +00001274 `X509Req.sign` succeeds when passed a private key object and a
1275 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001276 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001277 """
1278 request = self.signable()
1279 key = PKey()
1280 key.generate_key(TYPE_RSA, 512)
1281 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001282 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001283 # If the type has a verify method, cover that too.
1284 if getattr(request, 'verify', None) is not None:
1285 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001286 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001287 # Make another key that won't verify.
1288 key = PKey()
1289 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001290 with pytest.raises(Error):
1291 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001292
1293
Alex Chanb00ede22017-01-30 07:24:40 +00001294class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001295 """
Alex Chanb00ede22017-01-30 07:24:40 +00001296 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001297 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001298
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001299 def signable(self):
1300 """
Alex Chanb00ede22017-01-30 07:24:40 +00001301 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001302 """
1303 return X509Req()
1304
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001305 def test_type(self):
1306 """
Alex Chanb00ede22017-01-30 07:24:40 +00001307 `X509Req` and `X509ReqType` refer to the same type object and can be
1308 used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001309 """
Alex Chanb00ede22017-01-30 07:24:40 +00001310 assert X509Req is X509ReqType
1311 assert is_consistent_type(X509Req, 'X509Req')
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001312
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001313 def test_construction(self):
1314 """
Alex Chanb00ede22017-01-30 07:24:40 +00001315 `X509Req` takes no arguments and returns an `X509ReqType` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001316 """
1317 request = X509Req()
Alex Gaynor31287502015-09-05 16:11:27 -04001318 assert isinstance(request, X509ReqType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001319
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001320 def test_version(self):
1321 """
Alex Chanb00ede22017-01-30 07:24:40 +00001322 `X509Req.set_version` sets the X.509 version of the certificate
1323 request. `X509Req.get_version` returns the X.509 version of the
1324 certificate request. The initial value of the version is 0.
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001325 """
1326 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001327 assert request.get_version() == 0
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001328 request.set_version(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001329 assert request.get_version() == 1
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001330 request.set_version(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001331 assert request.get_version() == 3
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001332
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001333 def test_version_wrong_args(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001334 """
Alex Chanb00ede22017-01-30 07:24:40 +00001335 `X509Req.set_version` raises `TypeError` if called with a non-`int`
1336 argument.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001337 """
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001338 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001339 with pytest.raises(TypeError):
1340 request.set_version("foo")
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001341
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001342 def test_get_subject(self):
1343 """
Alex Chanb00ede22017-01-30 07:24:40 +00001344 `X509Req.get_subject` returns an `X509Name` for the subject of the
1345 request and which is valid even after the request object is
1346 otherwise dead.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001347 """
1348 request = X509Req()
1349 subject = request.get_subject()
Alex Gaynor31287502015-09-05 16:11:27 -04001350 assert isinstance(subject, X509NameType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001351 subject.commonName = "foo"
Alex Chanb00ede22017-01-30 07:24:40 +00001352 assert request.get_subject().commonName == "foo"
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001353 del request
1354 subject.commonName = "bar"
Alex Chanb00ede22017-01-30 07:24:40 +00001355 assert subject.commonName == "bar"
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001356
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001357 def test_add_extensions(self):
1358 """
Alex Chanb00ede22017-01-30 07:24:40 +00001359 `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
1360 and adds them to the X509 request.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001361 """
1362 request = X509Req()
1363 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001364 X509Extension(b'basicConstraints', True, b'CA:false')])
Stephen Holsappleca545b72014-01-28 21:43:25 -08001365 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001366 assert len(exts) == 1
1367 assert exts[0].get_short_name() == b'basicConstraints'
1368 assert exts[0].get_critical() == 1
1369 assert exts[0].get_data() == b'0\x00'
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001370
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001371 def test_get_extensions(self):
1372 """
Alex Chanb00ede22017-01-30 07:24:40 +00001373 `X509Req.get_extensions` returns a `list` of extensions added to this
1374 X509 request.
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001375 """
1376 request = X509Req()
1377 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001378 assert exts == []
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001379 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001380 X509Extension(b'basicConstraints', True, b'CA:true'),
1381 X509Extension(b'keyUsage', False, b'digitalSignature')])
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001382 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001383 assert len(exts) == 2
1384 assert exts[0].get_short_name() == b'basicConstraints'
1385 assert exts[0].get_critical() == 1
1386 assert exts[0].get_data() == b'0\x03\x01\x01\xff'
1387 assert exts[1].get_short_name() == b'keyUsage'
1388 assert exts[1].get_critical() == 0
1389 assert exts[1].get_data() == b'\x03\x02\x07\x80'
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001390
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001391 def test_add_extensions_wrong_args(self):
1392 """
Alex Chanb00ede22017-01-30 07:24:40 +00001393 `X509Req.add_extensions` raises `TypeError` if called with a
1394 non-`list`. Or it raises `ValueError` if called with a `list`
1395 containing objects other than `X509Extension` instances.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001396 """
1397 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001398 with pytest.raises(TypeError):
1399 request.add_extensions(object())
1400 with pytest.raises(ValueError):
1401 request.add_extensions([object()])
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001402
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001403 def test_verify_wrong_args(self):
1404 """
Alex Chanb00ede22017-01-30 07:24:40 +00001405 `X509Req.verify` raises `TypeError` if passed anything other than a
1406 `PKey` instance as its single argument.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001407 """
1408 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001409 with pytest.raises(TypeError):
1410 request.verify(object())
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001411
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001412 def test_verify_uninitialized_key(self):
1413 """
Alex Chanb00ede22017-01-30 07:24:40 +00001414 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1415 `OpenSSL.crypto.PKey` which contains no key data.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001416 """
1417 request = X509Req()
1418 pkey = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001419 with pytest.raises(Error):
1420 request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001421
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001422 def test_verify_wrong_key(self):
1423 """
Alex Chanb00ede22017-01-30 07:24:40 +00001424 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1425 `OpenSSL.crypto.PKey` which does not represent the public part of the
Alex Gaynor31287502015-09-05 16:11:27 -04001426 key which signed the request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001427 """
1428 request = X509Req()
1429 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001430 request.sign(pkey, GOOD_DIGEST)
Alex Chanb00ede22017-01-30 07:24:40 +00001431 another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
1432 with pytest.raises(Error):
1433 request.verify(another_pkey)
1434
1435 def test_verify_success(self):
1436 """
1437 `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
1438 which represents the public part of the key which signed the request.
1439 """
1440 request = X509Req()
1441 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
1442 request.sign(pkey, GOOD_DIGEST)
1443 assert request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001444
Paul Kehrer41c10242017-06-29 18:24:17 -05001445 def test_convert_from_cryptography(self):
1446 crypto_req = x509.load_pem_x509_csr(
1447 cleartextCertificateRequestPEM, backend
1448 )
1449 req = X509Req.from_cryptography(crypto_req)
1450 assert isinstance(req, X509Req)
1451
1452 def test_convert_from_cryptography_unsupported_type(self):
1453 with pytest.raises(TypeError):
1454 X509Req.from_cryptography(object())
1455
1456 def test_convert_to_cryptography_key(self):
1457 req = load_certificate_request(
1458 FILETYPE_PEM, cleartextCertificateRequestPEM
1459 )
1460 crypto_req = req.to_cryptography()
1461 assert isinstance(crypto_req, x509.CertificateSigningRequest)
1462
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001463
Alex Chanb00ede22017-01-30 07:24:40 +00001464class TestX509(_PKeyInteractionTestsMixin):
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001465 """
Alex Chanb00ede22017-01-30 07:24:40 +00001466 Tests for `OpenSSL.crypto.X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001467 """
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001468 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Jean-Paul Calderone8114b452008-03-25 15:27:59 -04001469
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001470 extpem = """
1471-----BEGIN CERTIFICATE-----
1472MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
1473BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
1474eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
1475MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
1476aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
1477hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
1478Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
1479zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
1480hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
1481TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
148203HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
1483MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
1484b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
1485MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
1486uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
1487WpOdIpB8KksUTCzV591Nr1wd
1488-----END CERTIFICATE-----
1489 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001490
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001491 def signable(self):
1492 """
Alex Chanb00ede22017-01-30 07:24:40 +00001493 Create and return a new `X509`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001494 """
1495 return X509()
1496
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001497 def test_type(self):
1498 """
Alex Chanb00ede22017-01-30 07:24:40 +00001499 `X509` and `X509Type` refer to the same type object and can be used to
1500 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001501 """
Alex Chanb00ede22017-01-30 07:24:40 +00001502 assert X509 is X509Type
1503 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001504
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001505 def test_construction(self):
1506 """
Alex Chanb00ede22017-01-30 07:24:40 +00001507 `X509` takes no arguments and returns an instance of `X509Type`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001508 """
1509 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001510 assert isinstance(certificate, X509Type)
1511 assert type(X509Type).__name__ == 'type'
1512 assert type(certificate).__name__ == 'X509'
1513 assert type(certificate) == X509Type
1514 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001515
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001516 def test_set_version_wrong_args(self):
1517 """
Alex Chanb00ede22017-01-30 07:24:40 +00001518 `X509.set_version` raises `TypeError` if invoked with an argument
1519 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001520 """
1521 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001522 with pytest.raises(TypeError):
1523 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001524
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001525 def test_version(self):
1526 """
Alex Chanb00ede22017-01-30 07:24:40 +00001527 `X509.set_version` sets the certificate version number.
1528 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001529 """
1530 cert = X509()
1531 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001532 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001533
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001534 def test_serial_number(self):
1535 """
Alex Chanb00ede22017-01-30 07:24:40 +00001536 The serial number of an `X509` can be retrieved and
1537 modified with `X509.get_serial_number` and
1538 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001539 """
1540 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001541 with pytest.raises(TypeError):
1542 certificate.set_serial_number("1")
1543 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001544 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001545 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001546 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001547 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001548 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001549 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001550 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001551 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001552
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001553 def _setBoundTest(self, which):
1554 """
Alex Chanb00ede22017-01-30 07:24:40 +00001555 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001556 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1557 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001558 """
1559 certificate = X509()
1560 set = getattr(certificate, 'set_not' + which)
1561 get = getattr(certificate, 'get_not' + which)
1562
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001563 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001564 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001565
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001566 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001567 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001568 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001569 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001570
1571 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001572 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001573 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001574 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001575
1576 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001577 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001578 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001579 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001580
1581 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001582 with pytest.raises(ValueError):
1583 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001584
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001585 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001586 with pytest.raises(TypeError):
1587 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001588 with pytest.raises(TypeError):
1589 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001590 with pytest.raises(TypeError):
1591 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001592
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001593 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001594
1595 def test_set_notBefore(self):
1596 """
Alex Chanb00ede22017-01-30 07:24:40 +00001597 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001598 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1599 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001600 """
1601 self._setBoundTest("Before")
1602
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001603 def test_set_notAfter(self):
1604 """
Alex Chanb00ede22017-01-30 07:24:40 +00001605 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001606 GENERALIZEDTIME and sets the end of the certificate's validity period
1607 to it.
1608 """
1609 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001610
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001611 def test_get_notBefore(self):
1612 """
Alex Chanb00ede22017-01-30 07:24:40 +00001613 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001614 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001615 internally.
1616 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001617 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001618 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001619
Rick Dean38a05c82009-07-18 01:41:30 -05001620 def test_get_notAfter(self):
1621 """
Alex Chanb00ede22017-01-30 07:24:40 +00001622 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001623 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001624 internally.
1625 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001626 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001627 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001628
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001629 def test_gmtime_adj_notBefore_wrong_args(self):
1630 """
Alex Chanb00ede22017-01-30 07:24:40 +00001631 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1632 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001633 """
1634 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001635 with pytest.raises(TypeError):
1636 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001637
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001638 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001639 def test_gmtime_adj_notBefore(self):
1640 """
Alex Chanb00ede22017-01-30 07:24:40 +00001641 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1642 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001643 """
1644 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001645 not_before_min = (
1646 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1647 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001648 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001649 not_before = datetime.strptime(
1650 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1651 )
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001652 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001653 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001654
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001655 def test_gmtime_adj_notAfter_wrong_args(self):
1656 """
Alex Chanb00ede22017-01-30 07:24:40 +00001657 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1658 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001659 """
1660 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001661 with pytest.raises(TypeError):
1662 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001663
Alex Gaynor642de6f2017-07-24 00:57:38 -04001664 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001665 def test_gmtime_adj_notAfter(self):
1666 """
Alex Chanb00ede22017-01-30 07:24:40 +00001667 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001668 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001669 """
1670 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001671 not_after_min = (
1672 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1673 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001674 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001675 not_after = datetime.strptime(
1676 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1677 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001678 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001679 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001680
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001681 def test_has_expired(self):
1682 """
Alex Chanb00ede22017-01-30 07:24:40 +00001683 `X509.has_expired` returns `True` if the certificate's not-after time
1684 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001685 """
1686 cert = X509()
1687 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001688 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001689
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001690 def test_has_not_expired(self):
1691 """
Alex Chanb00ede22017-01-30 07:24:40 +00001692 `X509.has_expired` returns `False` if the certificate's not-after time
1693 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001694 """
1695 cert = X509()
1696 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001697 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001698
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001699 def test_root_has_not_expired(self):
1700 """
Alex Chanb00ede22017-01-30 07:24:40 +00001701 `X509.has_expired` returns `False` if the certificate's not-after time
1702 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001703 """
1704 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001705 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001706
Rick Dean38a05c82009-07-18 01:41:30 -05001707 def test_digest(self):
1708 """
Alex Chanb00ede22017-01-30 07:24:40 +00001709 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001710 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001711 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001712 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001713 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001714 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1715 # actually matters to the assertion (ie, another arbitrary, good
1716 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001717 # Digest verified with the command:
1718 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001719 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001720 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001721
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001722 def _extcert(self, pkey, extensions):
1723 cert = X509()
1724 cert.set_pubkey(pkey)
1725 cert.get_subject().commonName = "Unit Tests"
1726 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001727 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001728 cert.set_notBefore(when)
1729 cert.set_notAfter(when)
1730
1731 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001732 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001733 return load_certificate(
1734 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1735
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001736 def test_extension_count(self):
1737 """
Alex Chanb00ede22017-01-30 07:24:40 +00001738 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001739 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001740 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001741 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001742 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1743 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001744 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001745 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001746
1747 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001748 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001749 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001750
1751 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001752 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001753 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001754
1755 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001756 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001757 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001758
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001759 def test_get_extension(self):
1760 """
Alex Chanb00ede22017-01-30 07:24:40 +00001761 `X509.get_extension` takes an integer and returns an
1762 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001763 """
1764 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001765 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1766 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001767 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001768 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001769
1770 cert = self._extcert(pkey, [ca, key, subjectAltName])
1771
1772 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001773 assert isinstance(ext, X509Extension)
1774 assert ext.get_critical()
1775 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001776
1777 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001778 assert isinstance(ext, X509Extension)
1779 assert ext.get_critical()
1780 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001781
1782 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001783 assert isinstance(ext, X509Extension)
1784 assert not ext.get_critical()
1785 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001786
Alex Chanb00ede22017-01-30 07:24:40 +00001787 with pytest.raises(IndexError):
1788 cert.get_extension(-1)
1789 with pytest.raises(IndexError):
1790 cert.get_extension(4)
1791 with pytest.raises(TypeError):
1792 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001793
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001794 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001795 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001796 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001797 bytes and this value is reflected in the string representation of the
1798 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001799 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001800 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001801
1802 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001803 assert ext.get_short_name() == b'subjectAltName'
1804 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001805 b"DNS:altnull.python.org\x00example.com, "
1806 b"email:null@python.org\x00user@example.org, "
1807 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001808 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 -04001809 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001810
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001811 def test_invalid_digest_algorithm(self):
1812 """
Alex Chanb00ede22017-01-30 07:24:40 +00001813 `X509.digest` raises `ValueError` if called with an unrecognized hash
1814 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001815 """
1816 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001817 with pytest.raises(ValueError):
1818 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001819
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001820 def test_get_subject(self):
1821 """
Alex Chanb00ede22017-01-30 07:24:40 +00001822 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001823 """
1824 cert = load_certificate(FILETYPE_PEM, self.pemData)
1825 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001826 assert isinstance(subj, X509Name)
1827 assert (
1828 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001829 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1830 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001831
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001832 def test_set_subject_wrong_args(self):
1833 """
Alex Chanb00ede22017-01-30 07:24:40 +00001834 `X509.set_subject` raises a `TypeError` if called with an argument not
1835 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001836 """
1837 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001838 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001839 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001840
1841 def test_set_subject(self):
1842 """
Alex Chanb00ede22017-01-30 07:24:40 +00001843 `X509.set_subject` changes the subject of the certificate to the one
1844 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001845 """
1846 cert = X509()
1847 name = cert.get_subject()
1848 name.C = 'AU'
1849 name.O = 'Unit Tests'
1850 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001851 assert (
1852 cert.get_subject().get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001853 [(b'C', b'AU'), (b'O', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001854
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001855 def test_get_issuer(self):
1856 """
Alex Chanb00ede22017-01-30 07:24:40 +00001857 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001858 """
1859 cert = load_certificate(FILETYPE_PEM, self.pemData)
1860 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001861 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001862 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001863 assert (
1864 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001865 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1866 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001867
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001868 def test_set_issuer_wrong_args(self):
1869 """
Alex Chanb00ede22017-01-30 07:24:40 +00001870 `X509.set_issuer` raises a `TypeError` if called with an argument not
1871 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001872 """
1873 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001874 with pytest.raises(TypeError):
1875 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001876
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001877 def test_set_issuer(self):
1878 """
Alex Chanb00ede22017-01-30 07:24:40 +00001879 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001880 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001881 """
1882 cert = X509()
1883 name = cert.get_issuer()
1884 name.C = 'AU'
1885 name.O = 'Unit Tests'
1886 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001887 assert (
1888 cert.get_issuer().get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001889 [(b'C', b'AU'), (b'O', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001890
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001891 def test_get_pubkey_uninitialized(self):
1892 """
Alex Chanb00ede22017-01-30 07:24:40 +00001893 When called on a certificate with no public key, `X509.get_pubkey`
1894 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001895 """
1896 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001897 with pytest.raises(Error):
1898 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001899
Alex Gaynor7778e792016-07-03 23:38:48 -04001900 def test_set_pubkey_wrong_type(self):
1901 """
Alex Chanb00ede22017-01-30 07:24:40 +00001902 `X509.set_pubkey` raises `TypeError` when given an object of the
1903 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001904 """
1905 cert = X509()
1906 with pytest.raises(TypeError):
1907 cert.set_pubkey(object())
1908
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001909 def test_subject_name_hash(self):
1910 """
Alex Chanb00ede22017-01-30 07:24:40 +00001911 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001912 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001913 """
1914 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001915 assert cert.subject_name_hash() in [
1916 3350047874, # OpenSSL 0.9.8, MD5
1917 3278919224, # OpenSSL 1.0.0, SHA1
1918 ]
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001919
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001920 def test_get_signature_algorithm(self):
1921 """
Alex Chanb00ede22017-01-30 07:24:40 +00001922 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001923 the algorithm used to sign the certificate.
1924 """
1925 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001926 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001927
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001928 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001929 """
Alex Chanb00ede22017-01-30 07:24:40 +00001930 `X509.get_signature_algorithm` raises `ValueError` if the signature
1931 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001932 """
1933 # This certificate has been modified to indicate a bogus OID in the
1934 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001935 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001936-----BEGIN CERTIFICATE-----
1937MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1938EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1939cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1940MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1941EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1942CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1943AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1944+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1945hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1946BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1947FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1948dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1949aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1950MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1951jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1952PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1953tgI5
1954-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001955"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001956 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001957 with pytest.raises(ValueError):
1958 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001959
Alex Gaynor37726112016-07-04 09:51:32 -04001960 def test_sign_bad_pubkey_type(self):
1961 """
Alex Chanb00ede22017-01-30 07:24:40 +00001962 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001963 """
1964 cert = X509()
1965 with pytest.raises(TypeError):
1966 cert.sign(object(), b"sha256")
1967
Alex Gaynor9939ba12017-06-25 16:28:24 -04001968 def test_convert_from_cryptography(self):
1969 crypto_cert = x509.load_pem_x509_certificate(
1970 intermediate_cert_pem, backend
1971 )
1972 cert = X509.from_cryptography(crypto_cert)
1973
1974 assert isinstance(cert, X509)
1975 assert cert.get_version() == crypto_cert.version.value
1976
1977 def test_convert_from_cryptography_unsupported_type(self):
1978 with pytest.raises(TypeError):
1979 X509.from_cryptography(object())
1980
1981 def test_convert_to_cryptography_key(self):
1982 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1983 crypto_cert = cert.to_cryptography()
1984
1985 assert isinstance(crypto_cert, x509.Certificate)
1986 assert crypto_cert.version.value == cert.get_version()
1987
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001988
Alex Chan9e2a9932017-01-25 14:29:19 +00001989class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001990 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001991 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001992 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001993
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001994 def test_type(self):
1995 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001996 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001997 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001998 assert X509Store is X509StoreType
1999 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002001 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002002 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002003 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002004 """
2005 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002007 store.add_cert(cert)
2008
Alex Chanfb078d82017-04-20 11:16:15 +01002009 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2010 def test_add_cert_wrong_args(self, cert):
2011 """
2012 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2013 as its first argument.
2014 """
2015 store = X509Store()
2016 with pytest.raises(TypeError):
2017 store.add_cert(cert)
2018
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002019 def test_add_cert_rejects_duplicate(self):
2020 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002021 `X509Store.add_cert` raises `OpenSSL.crypto.Error` if an attempt is
2022 made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002023 """
2024 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2025 store = X509Store()
2026 store.add_cert(cert)
Alex Chan9e2a9932017-01-25 14:29:19 +00002027 with pytest.raises(Error):
2028 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002029
2030
Alex Chanb00ede22017-01-30 07:24:40 +00002031class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002032 """
Alex Chanb00ede22017-01-30 07:24:40 +00002033 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002034 """
2035 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2036
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002037 def test_type(self):
2038 """
Alex Chanb00ede22017-01-30 07:24:40 +00002039 `PKCS12Type` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002040 """
Alex Chanb00ede22017-01-30 07:24:40 +00002041 assert PKCS12 is PKCS12Type
2042 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002043
Rick Deanf94096c2009-07-18 14:23:06 -05002044 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002045 """
Alex Chanb00ede22017-01-30 07:24:40 +00002046 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2047 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002048 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002049 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002050 assert None is p12.get_certificate()
2051 assert None is p12.get_privatekey()
2052 assert None is p12.get_ca_certificates()
2053 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002054
2055 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002056 """
Alex Chanb00ede22017-01-30 07:24:40 +00002057 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2058 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2059 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002060 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002061 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002062 for bad_arg in [3, PKey(), X509]:
2063 with pytest.raises(TypeError):
2064 p12.set_certificate(bad_arg)
2065 for bad_arg in [3, 'legbone', X509()]:
2066 with pytest.raises(TypeError):
2067 p12.set_privatekey(bad_arg)
2068 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2069 with pytest.raises(TypeError):
2070 p12.set_ca_certificates(bad_arg)
2071 for bad_arg in [6, ('foo', 'bar')]:
2072 with pytest.raises(TypeError):
2073 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002074
2075 def test_key_only(self):
2076 """
Alex Chanb00ede22017-01-30 07:24:40 +00002077 A `PKCS12` with only a private key can be exported using
2078 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002079 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002080 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002081 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002082 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002083 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002084 assert None is p12.get_certificate()
2085 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002086 try:
2087 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2088 except Error:
2089 # Some versions of OpenSSL will throw an exception
2090 # for this nearly useless PKCS12 we tried to generate:
2091 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2092 return
Rick Dean623ee362009-07-17 12:22:16 -05002093 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002094 assert None is p12.get_ca_certificates()
2095 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002096
2097 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2098 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002099 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002100
2101 def test_cert_only(self):
2102 """
Alex Chanb00ede22017-01-30 07:24:40 +00002103 A `PKCS12` with only a certificate can be exported using
2104 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002105 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002106 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002107 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002108 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002109 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002110 assert cert == p12.get_certificate()
2111 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002112 try:
2113 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2114 except Error:
2115 # Some versions of OpenSSL will throw an exception
2116 # for this nearly useless PKCS12 we tried to generate:
2117 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2118 return
Rick Dean623ee362009-07-17 12:22:16 -05002119 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002120 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002121
2122 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002123 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002124
2125 # Oh ho. It puts the certificate into the ca certificates list, in
2126 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2127 # that to check to see if it reconstructed the certificate we expected
2128 # it to. At some point, hopefully this will change so that
2129 # p12.get_certificate() is actually what returns the loaded
2130 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002131 assert (
2132 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002133 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002134
Alex Gaynor31287502015-09-05 16:11:27 -04002135 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2136 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002137 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002138 Generate a PKCS12 object with components from PEM. Verify that the set
2139 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002140 """
Rick Deanf94096c2009-07-18 14:23:06 -05002141 p12 = PKCS12()
2142 if cert_pem:
2143 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002144 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002145 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002146 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002147 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002148 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002149 ret = p12.set_ca_certificates(
2150 (load_certificate(FILETYPE_PEM, ca_pem),)
2151 )
Alex Chanb00ede22017-01-30 07:24:40 +00002152 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002153 if friendly_name:
2154 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002155 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002156 return p12
2157
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002158 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002159 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002160 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002161 Use openssl program to confirm three components are recoverable from a
2162 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002163 """
2164 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002165 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002166 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2167 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002168 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002169 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002170 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002171 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2172 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002173 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002174 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002175 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002176 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2177 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002178 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002179
Stephen Holsapple38482622014-04-05 20:29:34 -07002180 def verify_pkcs12_container(self, p12):
2181 """
2182 Verify that the PKCS#12 container contains the correct client
2183 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002184
2185 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002186 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002187 """
2188 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2189 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002190 assert (
2191 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002192 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002193
Rick Deanf94096c2009-07-18 14:23:06 -05002194 def test_load_pkcs12(self):
2195 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002196 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002197 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002198 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002199 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002200 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002201 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002202 pem,
2203 b"pkcs12",
2204 b"-export",
2205 b"-clcerts",
2206 b"-passout",
2207 b"pass:" + passwd
2208 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002209 p12 = load_pkcs12(p12_str, passphrase=passwd)
2210 self.verify_pkcs12_container(p12)
2211
Abraham Martinc5484ba2015-03-25 15:33:05 +00002212 def test_load_pkcs12_text_passphrase(self):
2213 """
2214 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002215 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002216 Using text as passphrase instead of bytes. DeprecationWarning expected.
2217 """
2218 pem = client_key_pem + client_cert_pem
2219 passwd = b"whatever"
2220 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2221 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002222 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002223 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002224 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002225 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002226 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002227 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002228 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002229
Abraham Martinc5484ba2015-03-25 15:33:05 +00002230 self.verify_pkcs12_container(p12)
2231
Stephen Holsapple38482622014-04-05 20:29:34 -07002232 def test_load_pkcs12_no_passphrase(self):
2233 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002234 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002235 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002236 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002237 """
2238 pem = client_key_pem + client_cert_pem
2239 p12_str = _runopenssl(
2240 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2241 p12 = load_pkcs12(p12_str)
2242 self.verify_pkcs12_container(p12)
2243
Stephen Holsapple38482622014-04-05 20:29:34 -07002244 def _dump_and_load(self, dump_passphrase, load_passphrase):
2245 """
2246 A helper method to dump and load a PKCS12 object.
2247 """
2248 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2249 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2250 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2251
Stephen Holsapple38482622014-04-05 20:29:34 -07002252 def test_load_pkcs12_null_passphrase_load_empty(self):
2253 """
2254 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002255 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002256 extracted and examined.
2257 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002258 self.verify_pkcs12_container(
2259 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002260
Stephen Holsapple38482622014-04-05 20:29:34 -07002261 def test_load_pkcs12_null_passphrase_load_null(self):
2262 """
2263 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002264 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002265 extracted and examined.
2266 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002267 self.verify_pkcs12_container(
2268 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002269
Stephen Holsapple38482622014-04-05 20:29:34 -07002270 def test_load_pkcs12_empty_passphrase_load_empty(self):
2271 """
2272 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002273 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002274 extracted and examined.
2275 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002276 self.verify_pkcs12_container(
2277 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002278
Stephen Holsapple38482622014-04-05 20:29:34 -07002279 def test_load_pkcs12_empty_passphrase_load_null(self):
2280 """
2281 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002282 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002283 extracted and examined.
2284 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002285 self.verify_pkcs12_container(
2286 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002287
Rick Deanee568302009-07-24 09:56:29 -05002288 def test_load_pkcs12_garbage(self):
2289 """
Alex Chanb00ede22017-01-30 07:24:40 +00002290 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002291 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002292 """
2293 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002294 with pytest.raises(Error) as err:
2295 load_pkcs12(b'fruit loops', passwd)
2296 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2297 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002298
Rick Deanf94096c2009-07-18 14:23:06 -05002299 def test_replace(self):
2300 """
Alex Chanb00ede22017-01-30 07:24:40 +00002301 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2302 cluster. `PKCS12.set_privatekey` replaces the private key.
2303 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002304 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002305 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2306 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2307 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002308 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002309 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002310 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002311 assert 1 == len(p12.get_ca_certificates())
2312 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002313 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002314 assert 2 == len(p12.get_ca_certificates())
2315 assert client_cert == p12.get_ca_certificates()[0]
2316 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002317
Rick Deanf94096c2009-07-18 14:23:06 -05002318 def test_friendly_name(self):
2319 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002320 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002321 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2322 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002323 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002324 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002325 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002326 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002327 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002328 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002329 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002330 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002331 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002332 # We would use the openssl program to confirm the friendly
2333 # name, but it is not possible. The pkcs12 command
2334 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002335 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002336 self.check_recovery(
2337 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2338 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002339
Rick Deanf94096c2009-07-18 14:23:06 -05002340 def test_various_empty_passphrases(self):
2341 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002342 Test that missing, None, and '' passphrases are identical for PKCS12
2343 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002344 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002345 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002346 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002347 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2348 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2349 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2350 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2351 self.check_recovery(
2352 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2353 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002354
Rick Deanf94096c2009-07-18 14:23:06 -05002355 def test_removing_ca_cert(self):
2356 """
Alex Chanb00ede22017-01-30 07:24:40 +00002357 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2358 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002359 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002360 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2361 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002362 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002363
Rick Deanf94096c2009-07-18 14:23:06 -05002364 def test_export_without_mac(self):
2365 """
Alex Chanb00ede22017-01-30 07:24:40 +00002366 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002367 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002368 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002369 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002370 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002371 self.check_recovery(
2372 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002373 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002374
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002375 def test_load_without_mac(self):
2376 """
2377 Loading a PKCS12 without a MAC does something other than crash.
2378 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002379 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002380 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2381 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002382 try:
2383 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2384 # The person who generated this PCKS12 should be flogged,
2385 # or better yet we should have a means to determine
2386 # whether a PCKS12 had a MAC that was verified.
2387 # Anyway, libopenssl chooses to allow it, so the
2388 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002389 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002390 except Error:
2391 # Failing here with an exception is preferred as some openssl
2392 # versions do.
2393 pass
Rick Dean623ee362009-07-17 12:22:16 -05002394
Rick Dean25bcc1f2009-07-20 11:53:13 -05002395 def test_zero_len_list_for_ca(self):
2396 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002397 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002398 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002399 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002400 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002401 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002402 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002403 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2404 self.check_recovery(
2405 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2406 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002407
Rick Deanf94096c2009-07-18 14:23:06 -05002408 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002409 """
Alex Chanb00ede22017-01-30 07:24:40 +00002410 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002411 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002412 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002413 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002414 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002415 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002416
Abraham Martinc5484ba2015-03-25 15:33:05 +00002417 def test_export_without_bytes(self):
2418 """
Alex Chanb00ede22017-01-30 07:24:40 +00002419 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002420 """
2421 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2422
Alex Chanb00ede22017-01-30 07:24:40 +00002423 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002424 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002425 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002426 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002427 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002428 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002429 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002430 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002431 dumped_p12,
2432 key=server_key_pem,
2433 cert=server_cert_pem,
2434 passwd=b"randomtext"
2435 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002436
Rick Deanf94096c2009-07-18 14:23:06 -05002437 def test_key_cert_mismatch(self):
2438 """
Alex Chanb00ede22017-01-30 07:24:40 +00002439 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002440 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002441 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002442 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002443 with pytest.raises(Error):
2444 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002445
2446
Rick Dean4c9ad612009-07-17 15:05:22 -05002447def _runopenssl(pem, *args):
2448 """
2449 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002450 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002451 """
Alex Gaynor6cbc69a2017-07-25 09:07:04 -04002452 proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002453 proc.stdin.write(pem)
2454 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002455 output = proc.stdout.read()
2456 proc.stdout.close()
2457 proc.wait()
2458 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002459
2460
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002461class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002462 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002463 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002464 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002465 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002466 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002467 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002468 """
2469 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002470
2471 assert True is key._only_public
2472 assert 2048 == key.bits()
2473 assert TYPE_RSA == key.type()
2474
2475 def test_invalid_type(self):
2476 """
2477 load_publickey doesn't support FILETYPE_TEXT.
2478 """
2479 with pytest.raises(ValueError):
2480 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2481
2482 def test_invalid_key_format(self):
2483 """
2484 load_publickey explodes on incorrect keys.
2485 """
2486 with pytest.raises(Error):
2487 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2488
2489 def test_tolerates_unicode_strings(self):
2490 """
2491 load_publickey works with text strings, not just bytes.
2492 """
2493 serialized = cleartextPublicKeyPEM.decode('ascii')
2494 key = load_publickey(FILETYPE_PEM, serialized)
2495 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2496
2497 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002498
2499
Alex Chanb00ede22017-01-30 07:24:40 +00002500class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002501 """
Alex Chanb00ede22017-01-30 07:24:40 +00002502 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002503 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002504
2505 def test_load_privatekey_invalid_format(self):
2506 """
Alex Chanb00ede22017-01-30 07:24:40 +00002507 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002508 """
Alex Chanb00ede22017-01-30 07:24:40 +00002509 with pytest.raises(ValueError):
2510 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002511
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002512 def test_load_privatekey_invalid_passphrase_type(self):
2513 """
Alex Chanb00ede22017-01-30 07:24:40 +00002514 `load_privatekey` raises `TypeError` if passed a passphrase that is
2515 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002516 """
Alex Chanb00ede22017-01-30 07:24:40 +00002517 with pytest.raises(TypeError):
2518 load_privatekey(
2519 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002520
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002521 def test_load_privatekey_wrongPassphrase(self):
2522 """
Alex Chanb00ede22017-01-30 07:24:40 +00002523 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2524 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002525 """
Alex Chanb00ede22017-01-30 07:24:40 +00002526 with pytest.raises(Error) as err:
2527 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2528 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002529
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002530 def test_load_privatekey_passphraseWrongType(self):
2531 """
Alex Chanb00ede22017-01-30 07:24:40 +00002532 `load_privatekey` raises `ValueError` when it is passeda passphrase
2533 with a private key encoded in a format, that doesn't support
2534 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002535 """
2536 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2537 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002538 with pytest.raises(ValueError):
2539 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002540
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002541 def test_load_privatekey_passphrase(self):
2542 """
Alex Chanb00ede22017-01-30 07:24:40 +00002543 `load_privatekey` can create a `PKey` object from an encrypted PEM
2544 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002545 """
2546 key = load_privatekey(
2547 FILETYPE_PEM, encryptedPrivateKeyPEM,
2548 encryptedPrivateKeyPEMPassphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002549 assert isinstance(key, PKeyType)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002550
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002551 def test_load_privatekey_passphrase_exception(self):
2552 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002553 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002554 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002555 """
2556 def cb(ignored):
2557 raise ArithmeticError
2558
Alex Gaynor791212d2015-09-05 15:46:08 -04002559 with pytest.raises(ArithmeticError):
2560 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002561
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002562 def test_load_privatekey_wrongPassphraseCallback(self):
2563 """
Alex Chanb00ede22017-01-30 07:24:40 +00002564 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002565 is passed an encrypted PEM and a passphrase callback which returns an
2566 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002567 """
2568 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002569
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002570 def cb(*a):
2571 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002572 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002573 with pytest.raises(Error) as err:
2574 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2575 assert called
2576 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002577
2578 def test_load_privatekey_passphraseCallback(self):
2579 """
Alex Chanb00ede22017-01-30 07:24:40 +00002580 `load_privatekey` can create a `PKey` object from an encrypted PEM
2581 string if given a passphrase callback which returns the correct
2582 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002583 """
2584 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002585
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002586 def cb(writing):
2587 called.append(writing)
2588 return encryptedPrivateKeyPEMPassphrase
2589 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002590 assert isinstance(key, PKeyType)
2591 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002592
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002593 def test_load_privatekey_passphrase_wrong_return_type(self):
2594 """
Alex Chanb00ede22017-01-30 07:24:40 +00002595 `load_privatekey` raises `ValueError` if the passphrase callback
2596 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002597 """
Alex Chanb00ede22017-01-30 07:24:40 +00002598 with pytest.raises(ValueError):
2599 load_privatekey(
2600 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002601
Alex Chanfb078d82017-04-20 11:16:15 +01002602 def test_dump_privatekey_wrong_args(self):
2603 """
2604 `dump_privatekey` raises `TypeError` if called with a `cipher`
2605 argument but no `passphrase` argument.
2606 """
2607 key = PKey()
2608 key.generate_key(TYPE_RSA, 512)
2609 with pytest.raises(TypeError):
2610 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2611
Paul Kehrercded9932017-06-29 18:43:42 -05002612 def test_dump_privatekey_not_rsa_key(self):
2613 """
2614 `dump_privatekey` raises `TypeError` if called with a key that is
2615 not RSA.
2616 """
2617 key = PKey()
2618 key.generate_key(TYPE_DSA, 512)
2619 with pytest.raises(TypeError):
2620 dump_privatekey(FILETYPE_TEXT, key)
2621
2622 def test_dump_privatekey_invalid_pkey(self):
2623 with pytest.raises(TypeError):
2624 dump_privatekey(FILETYPE_TEXT, object())
2625
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002626 def test_dump_privatekey_unknown_cipher(self):
2627 """
Alex Chanb00ede22017-01-30 07:24:40 +00002628 `dump_privatekey` raises `ValueError` if called with an unrecognized
2629 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002630 """
2631 key = PKey()
2632 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002633 with pytest.raises(ValueError):
2634 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002635
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002636 def test_dump_privatekey_invalid_passphrase_type(self):
2637 """
Alex Chanb00ede22017-01-30 07:24:40 +00002638 `dump_privatekey` raises `TypeError` if called with a passphrase which
2639 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002640 """
2641 key = PKey()
2642 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002643 with pytest.raises(TypeError):
2644 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002645
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002646 def test_dump_privatekey_invalid_filetype(self):
2647 """
Alex Chanb00ede22017-01-30 07:24:40 +00002648 `dump_privatekey` raises `ValueError` if called with an unrecognized
2649 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002650 """
2651 key = PKey()
2652 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002653 with pytest.raises(ValueError):
2654 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002655
Alex Chanb00ede22017-01-30 07:24:40 +00002656 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002657 """
Alex Chanb00ede22017-01-30 07:24:40 +00002658 `crypto.load_privatekey` should raise an error when the passphrase
2659 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002660 """
2661 def cb(ignored):
2662 return "a" * 1025
2663
Alex Gaynor791212d2015-09-05 15:46:08 -04002664 with pytest.raises(ValueError):
2665 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002666
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002667 def test_dump_privatekey_passphrase(self):
2668 """
Alex Chanb00ede22017-01-30 07:24:40 +00002669 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002670 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002671 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002672 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002673 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002674 assert isinstance(pem, binary_type)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002675 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002676 assert isinstance(loadedKey, PKeyType)
2677 assert loadedKey.type() == key.type()
2678 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002679
Alex Chanb00ede22017-01-30 07:24:40 +00002680 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002681 """
Alex Chanb00ede22017-01-30 07:24:40 +00002682 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2683 with a private key encoded in a format, that doesn't support
2684 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002685 """
2686 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002687 with pytest.raises(ValueError):
2688 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002689
Rick Dean5b7b6372009-04-01 11:34:06 -05002690 def test_dump_certificate(self):
2691 """
Alex Chanb00ede22017-01-30 07:24:40 +00002692 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002693 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002694 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002695 cert = load_certificate(FILETYPE_PEM, pemData)
2696 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002697 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002698 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002699 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002700 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002701 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2702 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002703 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002704 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002705 good_text = _runopenssl(
2706 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002707 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002708
Alex Gaynor37726112016-07-04 09:51:32 -04002709 def test_dump_certificate_bad_type(self):
2710 """
Alex Chanb00ede22017-01-30 07:24:40 +00002711 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002712 a bad type.
2713 """
2714 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2715 with pytest.raises(ValueError):
2716 dump_certificate(object(), cert)
2717
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002718 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002719 """
Alex Chanb00ede22017-01-30 07:24:40 +00002720 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002721 """
2722 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002723 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002724 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002725 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002726
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002727 def test_dump_privatekey_asn1(self):
2728 """
Alex Chanb00ede22017-01-30 07:24:40 +00002729 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002730 """
2731 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2732 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2733
Rick Dean5b7b6372009-04-01 11:34:06 -05002734 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002735 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002736 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002737 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002738 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2739 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002740 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002741
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002742 def test_dump_privatekey_text(self):
2743 """
Alex Chanb00ede22017-01-30 07:24:40 +00002744 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002745 """
2746 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2747 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2748
Rick Dean5b7b6372009-04-01 11:34:06 -05002749 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002750 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002751 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002752
Cory Benfield6492f7c2015-10-27 16:57:58 +09002753 def test_dump_publickey_pem(self):
2754 """
Cory Benfield11c10192015-10-27 17:23:03 +09002755 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002756 """
2757 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2758 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002759 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002760
2761 def test_dump_publickey_asn1(self):
2762 """
Cory Benfield11c10192015-10-27 17:23:03 +09002763 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002764 """
2765 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2766 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2767 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2768 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002769 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002770
Cory Benfielde02c7d82015-10-27 17:34:49 +09002771 def test_dump_publickey_invalid_type(self):
2772 """
2773 dump_publickey doesn't support FILETYPE_TEXT.
2774 """
2775 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2776
2777 with pytest.raises(ValueError):
2778 dump_publickey(FILETYPE_TEXT, key)
2779
Rick Dean5b7b6372009-04-01 11:34:06 -05002780 def test_dump_certificate_request(self):
2781 """
Alex Chanb00ede22017-01-30 07:24:40 +00002782 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002783 """
Alex Gaynor31287502015-09-05 16:11:27 -04002784 req = load_certificate_request(
2785 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002786 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002787 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002788 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002789 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002790 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002791 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2792 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002793 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002794 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002795 good_text = _runopenssl(
2796 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002797 assert dumped_text == good_text
2798 with pytest.raises(ValueError):
2799 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002800
Alex Chanb00ede22017-01-30 07:24:40 +00002801 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002802 """
Alex Chanb00ede22017-01-30 07:24:40 +00002803 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002804 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002805 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002806 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002807 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002808
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002809 def cb(writing):
2810 called.append(writing)
2811 return passphrase
2812 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002813 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002814 assert isinstance(pem, binary_type)
2815 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002816 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002817 assert isinstance(loadedKey, PKeyType)
2818 assert loadedKey.type() == key.type()
2819 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002820
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002821 def test_dump_privatekey_passphrase_exception(self):
2822 """
Alex Chanb00ede22017-01-30 07:24:40 +00002823 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002824 by the passphrase callback.
2825 """
2826 def cb(ignored):
2827 raise ArithmeticError
2828
2829 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002830 with pytest.raises(ArithmeticError):
2831 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002832
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002833 def test_dump_privatekey_passphraseCallbackLength(self):
2834 """
Alex Chanb00ede22017-01-30 07:24:40 +00002835 `crypto.dump_privatekey` should raise an error when the passphrase
2836 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002837 """
2838 def cb(ignored):
2839 return "a" * 1025
2840
2841 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002842 with pytest.raises(ValueError):
2843 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002844
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002845 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002846 """
Alex Chanb00ede22017-01-30 07:24:40 +00002847 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2848 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002849 """
2850 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002851 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002852
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002853 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002854 """
Alex Chanb00ede22017-01-30 07:24:40 +00002855 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2856 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002857 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002858 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002859 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002860
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002861 def test_load_pkcs7_data_invalid(self):
2862 """
Alex Chanb00ede22017-01-30 07:24:40 +00002863 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002864 """
Alex Chanb00ede22017-01-30 07:24:40 +00002865 with pytest.raises(Error):
2866 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002867
Alex Gaynor09a386e2016-07-03 09:32:44 -04002868 def test_load_pkcs7_type_invalid(self):
2869 """
Alex Chanb00ede22017-01-30 07:24:40 +00002870 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002871 """
2872 with pytest.raises(ValueError):
2873 load_pkcs7_data(object(), b"foo")
2874
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002875
Alex Chan9e2a9932017-01-25 14:29:19 +00002876class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002877 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002878 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002879 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002880
Alex Chan9e2a9932017-01-25 14:29:19 +00002881 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002882 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002883 If the file type passed to `load_certificate_request` is neither
2884 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002885 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002886 with pytest.raises(ValueError):
2887 load_certificate_request(object(), b"")
2888 with pytest.raises(ValueError):
2889 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002890
Alex Gaynor37726112016-07-04 09:51:32 -04002891 def test_bad_certificate(self):
2892 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002893 If the bytes passed to `load_certificate` are not a valid certificate,
2894 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002895 """
2896 with pytest.raises(Error):
2897 load_certificate(FILETYPE_ASN1, b"lol")
2898
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002899
Alex Chanb00ede22017-01-30 07:24:40 +00002900class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002901 """
Alex Chanb00ede22017-01-30 07:24:40 +00002902 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002903 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002904
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002905 def test_type(self):
2906 """
Alex Chanb00ede22017-01-30 07:24:40 +00002907 `PKCS7` is a type object.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002908 """
Alex Chanb00ede22017-01-30 07:24:40 +00002909 assert isinstance(PKCS7, type)
2910 assert PKCS7Type.__name__ == 'PKCS7'
2911 assert PKCS7 is PKCS7Type
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002912
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002913 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002914 """
Alex Chanb00ede22017-01-30 07:24:40 +00002915 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2916 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002917 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002918 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002919 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002920
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002921 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002922 """
Alex Chanb00ede22017-01-30 07:24:40 +00002923 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2924 of the type *enveloped*.
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 not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002928
Alex Chanb00ede22017-01-30 07:24:40 +00002929 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002930 """
Alex Chanb00ede22017-01-30 07:24:40 +00002931 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002932 if the PKCS7 object is not of the type *signed and 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_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002936
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002937 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002938 """
Alex Chanb00ede22017-01-30 07:24:40 +00002939 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2940 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002941 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002942 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002943 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002944
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002945 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002946 """
Alex Chanb00ede22017-01-30 07:24:40 +00002947 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002948 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002949 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002950 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002951 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002952
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002953 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002954 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002955 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002956 on an instance of `PKCS7`, `AttributeError` is raised.
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 with pytest.raises(AttributeError):
2960 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002961
2962
Alex Chanb00ede22017-01-30 07:24:40 +00002963class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002964 """
Alex Chanb00ede22017-01-30 07:24:40 +00002965 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002966 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002967
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002968 def signable(self):
2969 """
Alex Chanb00ede22017-01-30 07:24:40 +00002970 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002971 """
2972 return NetscapeSPKI()
2973
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002974 def test_type(self):
2975 """
Alex Chanb00ede22017-01-30 07:24:40 +00002976 `NetscapeSPKI` and `NetscapeSPKIType` refer to the same type object
2977 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002978 """
Alex Chanb00ede22017-01-30 07:24:40 +00002979 assert NetscapeSPKI is NetscapeSPKIType
2980 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002981
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002982 def test_construction(self):
2983 """
Alex Chanb00ede22017-01-30 07:24:40 +00002984 `NetscapeSPKI` returns an instance of `NetscapeSPKIType`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002985 """
2986 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002987 assert isinstance(nspki, NetscapeSPKIType)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002988
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002989 def test_invalid_attribute(self):
2990 """
Alex Chanb00ede22017-01-30 07:24:40 +00002991 Accessing a non-existent attribute of a `NetscapeSPKI` instance
2992 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002993 """
2994 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002995 with pytest.raises(AttributeError):
2996 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002997
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002998 def test_b64_encode(self):
2999 """
Alex Chanb00ede22017-01-30 07:24:40 +00003000 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003001 """
3002 nspki = NetscapeSPKI()
3003 blob = nspki.b64_encode()
Alex Chanb00ede22017-01-30 07:24:40 +00003004 assert isinstance(blob, binary_type)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003005
3006
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003007class TestRevoked(object):
3008 """
Alex Chandeec9342016-12-19 22:00:38 +00003009 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003010 """
3011 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
3012 """
3013 The get_reason method on the Revoked class checks to see if the
3014 extension is NID_crl_reason and should skip it otherwise. This test
3015 loads a CRL with extensions it should ignore.
3016 """
3017 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3018 revoked = crl.get_revoked()
3019 reason = revoked[1].get_reason()
3020 assert reason == b'Unspecified'
3021
3022 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3023 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3024 revoked = crl.get_revoked()
3025 revoked[1].set_reason(None)
3026 reason = revoked[1].get_reason()
3027 assert reason is None
3028
Rick Dean536ba022009-07-24 23:57:27 -05003029 def test_construction(self):
3030 """
Alex Chandeec9342016-12-19 22:00:38 +00003031 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3032 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003033 """
3034 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003035 assert isinstance(revoked, Revoked)
3036 assert type(revoked) == Revoked
3037 assert revoked.get_serial() == b'00'
3038 assert revoked.get_rev_date() is None
3039 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003040
Rick Dean536ba022009-07-24 23:57:27 -05003041 def test_serial(self):
3042 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003043 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003044 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003045 """
3046 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003047 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003048 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003049 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003050 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003051
Alex Gaynore7f51982016-09-11 11:48:14 -04003052 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003053 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003054 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003055
Alex Chandeec9342016-12-19 22:00:38 +00003056 with pytest.raises(ValueError):
3057 revoked.set_serial(b'pqrst')
3058 with pytest.raises(TypeError):
3059 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003060
Rick Dean536ba022009-07-24 23:57:27 -05003061 def test_date(self):
3062 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003063 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003064 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003065 """
3066 revoked = Revoked()
3067 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003068 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003069
Alex Gaynore7f51982016-09-11 11:48:14 -04003070 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003071 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003072 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003073 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003074 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003075
Rick Dean6385faf2009-07-26 00:07:47 -05003076 def test_reason(self):
3077 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003078 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003079 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3080 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003081 """
3082 revoked = Revoked()
3083 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003084 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003085 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003086 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003087 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003088 assert (
3089 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003090 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003091 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003092
3093 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003094 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003095
Alex Chanfb078d82017-04-20 11:16:15 +01003096 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3097 def test_set_reason_wrong_args(self, reason):
3098 """
3099 `Revoked.set_reason` raises `TypeError` if called with an argument
3100 which is neither `None` nor a byte string.
3101 """
3102 revoked = Revoked()
3103 with pytest.raises(TypeError):
3104 revoked.set_reason(reason)
3105
Alex Chandeec9342016-12-19 22:00:38 +00003106 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003107 """
Alex Chandeec9342016-12-19 22:00:38 +00003108 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3109 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003110 """
3111 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003112 with pytest.raises(ValueError):
3113 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003114
3115
Alex Chan7be83a52017-01-24 15:19:29 +00003116class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003117 """
Alex Chan7be83a52017-01-24 15:19:29 +00003118 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003119 """
3120 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3121 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3122
Dan Sully44e767a2016-06-04 18:05:27 -07003123 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3124 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3125 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3126 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3127 intermediate_server_cert = load_certificate(
3128 FILETYPE_PEM, intermediate_server_cert_pem)
3129 intermediate_server_key = load_privatekey(
3130 FILETYPE_PEM, intermediate_server_key_pem)
3131
Rick Dean536ba022009-07-24 23:57:27 -05003132 def test_construction(self):
3133 """
Alex Chan7be83a52017-01-24 15:19:29 +00003134 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003135 that it is empty
3136 """
3137 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003138 assert isinstance(crl, CRL)
3139 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003140
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003141 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003142 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003143 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003144 """
3145 crl = CRL()
3146 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003147 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003148 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003149 revoked.set_serial(b'3ab')
3150 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003151 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003152 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003153
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003154 def test_export_pem(self):
3155 """
3156 If not passed a format, ``CRL.export`` returns a "PEM" format string
3157 representing a serial number, a revoked reason, and certificate issuer
3158 information.
3159 """
3160 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003161 # PEM format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003162 dumped_crl = crl.export(
3163 self.cert, self.pkey, days=20, digest=b"sha256"
3164 )
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003165 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003166
3167 # These magic values are based on the way the CRL above was constructed
3168 # and with what certificate it was exported.
Alex Gaynore7f51982016-09-11 11:48:14 -04003169 text.index(b'Serial Number: 03AB')
3170 text.index(b'Superseded')
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003171 text.index(
Alex Gaynore7f51982016-09-11 11:48:14 -04003172 b'Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA'
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003173 )
3174
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003175 def test_export_der(self):
3176 """
3177 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3178 "DER" format string representing a serial number, a revoked reason, and
3179 certificate issuer information.
3180 """
3181 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003182
3183 # DER format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003184 dumped_crl = crl.export(
3185 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3186 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003187 text = _runopenssl(
3188 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
3189 )
Alex Gaynore7f51982016-09-11 11:48:14 -04003190 text.index(b'Serial Number: 03AB')
3191 text.index(b'Superseded')
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003192 text.index(
Alex Gaynore7f51982016-09-11 11:48:14 -04003193 b'Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA'
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003194 )
3195
Alex Gaynore466bc92017-07-06 23:43:47 -04003196 # Flaky because we compare the output of running commands which sometimes
3197 # varies by 1 second
3198 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003199 def test_export_text(self):
3200 """
3201 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3202 text format string like the one produced by the openssl command line
3203 tool.
3204 """
3205 crl = self._get_crl()
3206
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003207 dumped_crl = crl.export(
3208 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3209 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003210 text = _runopenssl(
3211 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
3212 )
Rick Dean536ba022009-07-24 23:57:27 -05003213
3214 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003215 dumped_text = crl.export(
3216 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3217 )
Alex Chan7be83a52017-01-24 15:19:29 +00003218 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003219
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003220 def test_export_custom_digest(self):
3221 """
3222 If passed the name of a digest function, ``CRL.export`` uses a
3223 signature algorithm based on that digest function.
3224 """
3225 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003226 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003227 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003228 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003229
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003230 def test_export_md5_digest(self):
3231 """
3232 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3233 not emit a deprecation warning.
3234 """
3235 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003236 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003237 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003238 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003239 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3240 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003241 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003242
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003243 def test_export_default_digest(self):
3244 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003245 If not passed the name of a digest function, ``CRL.export`` raises a
3246 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003247 """
3248 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003249 with pytest.raises(TypeError):
3250 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003251
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003252 def test_export_invalid(self):
3253 """
Alex Chan7be83a52017-01-24 15:19:29 +00003254 If `CRL.export` is used with an uninitialized `X509` instance,
3255 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003256 """
3257 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003258 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003259 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003260
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003261 def test_add_revoked_keyword(self):
3262 """
Alex Chan7be83a52017-01-24 15:19:29 +00003263 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003264 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003265 """
3266 crl = CRL()
3267 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003268 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003269 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003270 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003271 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003272
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003273 def test_export_wrong_args(self):
3274 """
Alex Chan7be83a52017-01-24 15:19:29 +00003275 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003276 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003277 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003278 """
3279 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003280 with pytest.raises(TypeError):
3281 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3282 with pytest.raises(TypeError):
3283 crl.export(self.cert, None, FILETYPE_PEM, 10)
3284 with pytest.raises(TypeError):
3285 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003286 with pytest.raises(TypeError):
3287 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003288
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003289 def test_export_unknown_filetype(self):
3290 """
Alex Chan7be83a52017-01-24 15:19:29 +00003291 Calling `OpenSSL.CRL.export` with a file type other than
3292 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3293 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003294 """
3295 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003296 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003297 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003298
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003299 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003300 """
Alex Chan7be83a52017-01-24 15:19:29 +00003301 Calling `OpenSSL.CRL.export` with an unsupported digest results
3302 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003303 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003304 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003305 with pytest.raises(ValueError):
3306 crl.export(
3307 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003308
Rick Dean536ba022009-07-24 23:57:27 -05003309 def test_get_revoked(self):
3310 """
Alex Chan7be83a52017-01-24 15:19:29 +00003311 Use python to create a simple CRL with two revocations. Get back the
3312 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003313 """
3314 crl = CRL()
3315
3316 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003317 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003318 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003319 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003320 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003321 revoked.set_serial(b'100')
3322 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003323 crl.add_revoked(revoked)
3324
3325 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003326 assert len(revs) == 2
3327 assert type(revs[0]) == Revoked
3328 assert type(revs[1]) == Revoked
3329 assert revs[0].get_serial() == b'03AB'
3330 assert revs[1].get_serial() == b'0100'
3331 assert revs[0].get_rev_date() == now
3332 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003333
Rick Dean536ba022009-07-24 23:57:27 -05003334 def test_load_crl(self):
3335 """
Alex Chan7be83a52017-01-24 15:19:29 +00003336 Load a known CRL and inspect its revocations. Both EM and DER formats
3337 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003338 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003339 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003340 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003341 assert len(revs) == 2
3342 assert revs[0].get_serial() == b'03AB'
3343 assert revs[0].get_reason() is None
3344 assert revs[1].get_serial() == b'0100'
3345 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003346
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003347 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003348 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003349 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003350 assert len(revs) == 2
3351 assert revs[0].get_serial() == b'03AB'
3352 assert revs[0].get_reason() is None
3353 assert revs[1].get_serial() == b'0100'
3354 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003355
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003356 def test_load_crl_bad_filetype(self):
3357 """
Alex Chan7be83a52017-01-24 15:19:29 +00003358 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3359 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003360 """
Alex Chan7be83a52017-01-24 15:19:29 +00003361 with pytest.raises(ValueError):
3362 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003363
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003364 def test_load_crl_bad_data(self):
3365 """
Alex Chan7be83a52017-01-24 15:19:29 +00003366 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3367 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003368 """
Alex Chan7be83a52017-01-24 15:19:29 +00003369 with pytest.raises(Error):
3370 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003371
Dan Sully44e767a2016-06-04 18:05:27 -07003372 def test_get_issuer(self):
3373 """
Alex Chan7be83a52017-01-24 15:19:29 +00003374 Load a known CRL and assert its issuer's common name is what we expect
3375 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003376 """
3377 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003378 assert isinstance(crl.get_issuer(), X509Name)
3379 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003380
Dominic Chenf05b2122015-10-13 16:32:35 +00003381 def test_dump_crl(self):
3382 """
3383 The dumped CRL matches the original input.
3384 """
3385 crl = load_crl(FILETYPE_PEM, crlData)
3386 buf = dump_crl(FILETYPE_PEM, crl)
3387 assert buf == crlData
3388
Dan Sully44e767a2016-06-04 18:05:27 -07003389 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3390 """
3391 Create a CRL.
3392
3393 :param list[X509] certs: A list of certificates to revoke.
3394 :rtype: CRL
3395 """
3396 crl = CRL()
3397 for cert in certs:
3398 revoked = Revoked()
3399 # FIXME: This string splicing is an unfortunate implementation
3400 # detail that has been reported in
3401 # https://github.com/pyca/pyopenssl/issues/258
3402 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3403 revoked.set_serial(serial)
3404 revoked.set_reason(b'unspecified')
3405 revoked.set_rev_date(b'20140601000000Z')
3406 crl.add_revoked(revoked)
3407 crl.set_version(1)
3408 crl.set_lastUpdate(b'20140601000000Z')
3409 crl.set_nextUpdate(b'20180601000000Z')
3410 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3411 return crl
3412
3413 def test_verify_with_revoked(self):
3414 """
Alex Chan7be83a52017-01-24 15:19:29 +00003415 `verify_certificate` raises error when an intermediate certificate is
3416 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003417 """
3418 store = X509Store()
3419 store.add_cert(self.root_cert)
3420 store.add_cert(self.intermediate_cert)
3421 root_crl = self._make_test_crl(
3422 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3423 intermediate_crl = self._make_test_crl(
3424 self.intermediate_cert, self.intermediate_key, certs=[])
3425 store.add_crl(root_crl)
3426 store.add_crl(intermediate_crl)
3427 store.set_flags(
3428 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3429 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003430 with pytest.raises(X509StoreContextError) as err:
3431 store_ctx.verify_certificate()
3432 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003433
3434 def test_verify_with_missing_crl(self):
3435 """
Alex Chan7be83a52017-01-24 15:19:29 +00003436 `verify_certificate` raises error when an intermediate certificate's
3437 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003438 """
3439 store = X509Store()
3440 store.add_cert(self.root_cert)
3441 store.add_cert(self.intermediate_cert)
3442 root_crl = self._make_test_crl(
3443 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3444 store.add_crl(root_crl)
3445 store.set_flags(
3446 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3447 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003448 with pytest.raises(X509StoreContextError) as err:
3449 store_ctx.verify_certificate()
3450 assert err.value.args[0][2] == 'unable to get certificate CRL'
3451 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003452
Paul Kehrer41c10242017-06-29 18:24:17 -05003453 def test_convert_from_cryptography(self):
3454 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3455 crl = CRL.from_cryptography(crypto_crl)
3456 assert isinstance(crl, CRL)
3457
3458 def test_convert_from_cryptography_unsupported_type(self):
3459 with pytest.raises(TypeError):
3460 CRL.from_cryptography(object())
3461
3462 def test_convert_to_cryptography_key(self):
3463 crl = load_crl(FILETYPE_PEM, crlData)
3464 crypto_crl = crl.to_cryptography()
3465 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3466
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003467
Alex Chan7be83a52017-01-24 15:19:29 +00003468class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003469 """
Alex Chan7be83a52017-01-24 15:19:29 +00003470 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003471 """
3472 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3473 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003474 intermediate_server_cert = load_certificate(
3475 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003476
3477 def test_valid(self):
3478 """
Alex Chan7be83a52017-01-24 15:19:29 +00003479 `verify_certificate` returns ``None`` when called with a certificate
3480 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003481 """
3482 store = X509Store()
3483 store.add_cert(self.root_cert)
3484 store.add_cert(self.intermediate_cert)
3485 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003486 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003487
3488 def test_reuse(self):
3489 """
Alex Chan7be83a52017-01-24 15:19:29 +00003490 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003491 ``X509StoreContext`` instance to produce the same result.
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
3498 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003499
3500 def test_trusted_self_signed(self):
3501 """
Alex Chan7be83a52017-01-24 15:19:29 +00003502 `verify_certificate` returns ``None`` when called with a self-signed
3503 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003504 """
3505 store = X509Store()
3506 store.add_cert(self.root_cert)
3507 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003508 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003509
3510 def test_untrusted_self_signed(self):
3511 """
Alex Chan7be83a52017-01-24 15:19:29 +00003512 `verify_certificate` raises error when a self-signed certificate is
3513 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003514 """
3515 store = X509Store()
3516 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003517 with pytest.raises(X509StoreContextError) as exc:
3518 store_ctx.verify_certificate()
3519
3520 assert exc.value.args[0][2] == 'self signed certificate'
3521 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003522
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003523 def test_invalid_chain_no_root(self):
3524 """
Alex Chan7be83a52017-01-24 15:19:29 +00003525 `verify_certificate` raises error when a root certificate is missing
3526 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003527 """
3528 store = X509Store()
3529 store.add_cert(self.intermediate_cert)
3530 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003531
3532 with pytest.raises(X509StoreContextError) as exc:
3533 store_ctx.verify_certificate()
3534
3535 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3536 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003537
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003538 def test_invalid_chain_no_intermediate(self):
3539 """
Alex Chan7be83a52017-01-24 15:19:29 +00003540 `verify_certificate` raises error when an intermediate certificate is
3541 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003542 """
3543 store = X509Store()
3544 store.add_cert(self.root_cert)
3545 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003546
Alex Gaynor85b49702015-09-05 16:30:59 -04003547 with pytest.raises(X509StoreContextError) as exc:
3548 store_ctx.verify_certificate()
3549
3550 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3551 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003552
Stephen Holsapple46a09252015-02-12 14:45:43 -08003553 def test_modification_pre_verify(self):
3554 """
Alex Chan7be83a52017-01-24 15:19:29 +00003555 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003556 instantiation.
3557 """
3558 store_bad = X509Store()
3559 store_bad.add_cert(self.intermediate_cert)
3560 store_good = X509Store()
3561 store_good.add_cert(self.root_cert)
3562 store_good.add_cert(self.intermediate_cert)
3563 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003564
3565 with pytest.raises(X509StoreContextError) as exc:
3566 store_ctx.verify_certificate()
3567
3568 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3569 assert exc.value.certificate.get_subject().CN == 'intermediate'
3570
Stephen Holsapple46a09252015-02-12 14:45:43 -08003571 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003572 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003573
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003574 def test_verify_with_time(self):
3575 """
3576 `verify_certificate` raises error when the verification time is
3577 set at notAfter.
3578 """
3579 store = X509Store()
3580 store.add_cert(self.root_cert)
3581 store.add_cert(self.intermediate_cert)
3582
3583 expire_time = self.intermediate_server_cert.get_notAfter()
3584 expire_datetime = datetime.strptime(
3585 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3586 )
3587 store.set_time(expire_datetime)
3588
3589 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3590 with pytest.raises(X509StoreContextError) as exc:
3591 store_ctx.verify_certificate()
3592
3593 assert exc.value.args[0][2] == 'certificate has expired'
3594
Stephen Holsapple46a09252015-02-12 14:45:43 -08003595
Alex Chan7be83a52017-01-24 15:19:29 +00003596class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003597 """
Alex Chan7be83a52017-01-24 15:19:29 +00003598 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003599 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003600
James Yonan7c2e5d32010-02-27 05:45:50 -07003601 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003602 """
Alex Chan7be83a52017-01-24 15:19:29 +00003603 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003604 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003605 content = (
3606 b"It was a bright cold day in April, and the clocks were striking "
3607 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3608 b"effort to escape the vile wind, slipped quickly through the "
3609 b"glass doors of Victory Mansions, though not quickly enough to "
3610 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003611
3612 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003613 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003614 # verify the content with this cert
3615 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3616 # certificate unrelated to priv_key, used to trigger an error
3617 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003618
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003619 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003620 sig = sign(priv_key, content, digest)
3621
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003622 # Verify the signature of content, will throw an exception if
3623 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003624 verify(good_cert, sig, content, digest)
3625
3626 # This should fail because the certificate doesn't match the
3627 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003628 with pytest.raises(Error):
3629 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003630
3631 # This should fail because we've "tainted" the content after
3632 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003633 with pytest.raises(Error):
3634 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003635
3636 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003637 with pytest.raises(ValueError):
3638 sign(priv_key, content, "strange-digest")
3639 with pytest.raises(ValueError):
3640 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003641
Abraham Martinc5484ba2015-03-25 15:33:05 +00003642 def test_sign_verify_with_text(self):
3643 """
Alex Chan7be83a52017-01-24 15:19:29 +00003644 `sign` generates a cryptographic signature which
3645 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003646 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003647 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003648 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003649 b"It was a bright cold day in April, and the clocks were striking "
3650 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3651 b"effort to escape the vile wind, slipped quickly through the "
3652 b"glass doors of Victory Mansions, though not quickly enough to "
3653 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003654 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003655
3656 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3657 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3658 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003659 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003660 simplefilter("always")
3661 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003662 assert (
3663 "{0} for data is no longer accepted, use bytes".format(
3664 WARNING_TYPE_EXPECTED
3665 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003666
Alex Chan7be83a52017-01-24 15:19:29 +00003667 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003668 simplefilter("always")
3669 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003670 assert (
3671 "{0} for data is no longer accepted, use bytes".format(
3672 WARNING_TYPE_EXPECTED
3673 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003674
Paul Kehrer59d26252017-07-20 10:45:54 +02003675 def test_sign_verify_ecdsa(self):
3676 """
3677 `sign` generates a cryptographic signature which `verify` can check.
3678 ECDSA Signatures in the X9.62 format may have variable length,
3679 different from the length of the private key.
3680 """
3681 content = (
3682 b"It was a bright cold day in April, and the clocks were striking "
3683 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3684 b"effort to escape the vile wind, slipped quickly through the "
3685 b"glass doors of Victory Mansions, though not quickly enough to "
3686 b"prevent a swirl of gritty dust from entering along with him."
3687 ).decode("ascii")
3688 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3689 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3690 sig = sign(priv_key, content, "sha1")
3691 verify(cert, sig, content, "sha1")
3692
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003693 def test_sign_nulls(self):
3694 """
Alex Chan7be83a52017-01-24 15:19:29 +00003695 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003696 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003697 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003698 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3699 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3700 sig = sign(priv_key, content, "sha1")
3701 verify(good_cert, sig, content, "sha1")
3702
Colleen Murphye09399b2016-03-01 17:40:49 -08003703 def test_sign_with_large_key(self):
3704 """
Alex Chan7be83a52017-01-24 15:19:29 +00003705 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003706 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003707 content = (
3708 b"It was a bright cold day in April, and the clocks were striking "
3709 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3710 b"effort to escape the vile wind, slipped quickly through the "
3711 b"glass doors of Victory Mansions, though not quickly enough to "
3712 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003713
3714 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3715 sign(priv_key, content, "sha1")
3716
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003717
Alex Chan63ef9bc2016-12-19 12:02:06 +00003718class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003719 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003720 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3721 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003722 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003723
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003724 def test_set(self):
3725 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003726 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003727 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003728 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003729
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003730 def test_a_curve(self):
3731 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003732 `get_elliptic_curve` can be used to retrieve a particular supported
3733 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003734 """
3735 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003736 curve = next(iter(curves))
3737 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003738
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003739 def test_not_a_curve(self):
3740 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003741 `get_elliptic_curve` raises `ValueError` if called with a name which
3742 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003743 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003744 with pytest.raises(ValueError):
3745 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003746
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003747 def test_repr(self):
3748 """
3749 The string representation of a curve object includes simply states the
3750 object is a curve and what its name is.
3751 """
3752 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003753 curve = next(iter(curves))
3754 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003755
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003756 def test_to_EC_KEY(self):
3757 """
3758 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003759 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003760 """
3761 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003762 curve = next(iter(curves))
3763 # It's not easy to assert anything about this object. However, see
3764 # leakcheck/crypto.py for a test that demonstrates it at least does
3765 # not leak memory.
3766 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003767
3768
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003769class EllipticCurveFactory(object):
3770 """
3771 A helper to get the names of two curves.
3772 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003773
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003774 def __init__(self):
3775 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003776 self.curve_name = next(curves).name
3777 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003778
3779
Alex Chan63ef9bc2016-12-19 12:02:06 +00003780class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003781 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003782 Tests `_EllipticCurve`\ 's implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003783 """
3784 curve_factory = EllipticCurveFactory()
3785
3786 if curve_factory.curve_name is None:
3787 skip = "There are no curves available there can be no curve objects."
3788
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003789 def anInstance(self):
3790 """
3791 Get the curve object for an arbitrary curve supported by the system.
3792 """
3793 return get_elliptic_curve(self.curve_factory.curve_name)
3794
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003795 def anotherInstance(self):
3796 """
3797 Get the curve object for an arbitrary curve supported by the system -
3798 but not the one returned by C{anInstance}.
3799 """
3800 return get_elliptic_curve(self.curve_factory.another_curve_name)
3801
3802
Alex Chan63ef9bc2016-12-19 12:02:06 +00003803class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003804 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003805 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3806 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003807 """
3808 curve_factory = EllipticCurveFactory()
3809
3810 if curve_factory.curve_name is None:
3811 skip = "There are no curves available there can be no curve objects."
3812
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003813 def test_contains(self):
3814 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003815 The ``in`` operator reports that a `set` containing a curve does
3816 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003817 """
3818 curve = get_elliptic_curve(self.curve_factory.curve_name)
3819 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003820 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003821
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003822 def test_does_not_contain(self):
3823 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003824 The ``in`` operator reports that a `set` not containing a curve
3825 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003826 """
3827 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003828 curves = set([
3829 get_elliptic_curve(self.curve_factory.another_curve_name)
3830 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003831 assert curve not in curves