blob: 9d943a943afa6db1a1de0fb9177a9eb11a71dec4 [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
Alex Gaynor01f90a12019-02-07 09:14:48 -050025from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey
26from OpenSSL.crypto import X509, X509Name
Alex Gaynor31287502015-09-05 16:11:27 -040027from OpenSSL.crypto import (
Dan Sully44e767a2016-06-04 18:05:27 -070028 X509Store,
29 X509StoreFlags,
Dan Sully44e767a2016-06-04 18:05:27 -070030 X509StoreContext,
31 X509StoreContextError
Alex Gaynor31287502015-09-05 16:11:27 -040032)
Alex Gaynor01f90a12019-02-07 09:14:48 -050033from OpenSSL.crypto import X509Req
34from OpenSSL.crypto import X509Extension
Rick Dean5b7b6372009-04-01 11:34:06 -050035from OpenSSL.crypto import load_certificate, load_privatekey
Cory Benfield6492f7c2015-10-27 16:57:58 +090036from OpenSSL.crypto import load_publickey, dump_publickey
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -040037from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
Jean-Paul Calderone71919862009-04-01 13:01:19 -040038from OpenSSL.crypto import dump_certificate, load_certificate_request
39from OpenSSL.crypto import dump_certificate_request, dump_privatekey
Alex Gaynor01f90a12019-02-07 09:14:48 -050040from OpenSSL.crypto import PKCS7, load_pkcs7_data
41from OpenSSL.crypto import PKCS12, load_pkcs12
Dominic Chenf05b2122015-10-13 16:32:35 +000042from OpenSSL.crypto import CRL, Revoked, dump_crl, load_crl
Alex Gaynor01f90a12019-02-07 09:14:48 -050043from OpenSSL.crypto import NetscapeSPKI
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040044from OpenSSL.crypto import (
45 sign, verify, get_elliptic_curve, get_elliptic_curves)
Hynek Schlawackf0e66852015-10-16 20:18:38 +020046
Alex Chanb00ede22017-01-30 07:24:40 +000047from .util import EqualityTestsMixin, is_consistent_type, WARNING_TYPE_EXPECTED
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040048
Alex Gaynoraceb3e22015-09-05 12:00:22 -040049
Jean-Paul Calderone9da338d2011-05-04 11:40:54 -040050def normalize_privatekey_pem(pem):
51 return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
52
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040053
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050054GOOD_CIPHER = "blowfish"
55BAD_CIPHER = "zippers"
56
Anthony Alba2ce737f2015-12-04 11:04:56 +080057GOOD_DIGEST = "SHA1"
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050058BAD_DIGEST = "monkeys"
59
Paul Kehrera40898b2017-06-11 16:30:58 -100060old_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
Rick Dean94e46fd2009-07-18 14:51:24 -050061MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
62BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
63ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
64NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
65MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
66ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
67urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
682xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
691dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
70FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
71VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
72BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
73b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
74AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
75hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
76w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
77-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -040078"""
Rick Dean94e46fd2009-07-18 14:51:24 -050079
Paul Kehrera40898b2017-06-11 16:30:58 -100080root_cert_pem = b"""-----BEGIN CERTIFICATE-----
81MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
82BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
83ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
84WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
85BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
86bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
87bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
88LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
89onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
90LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
91yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
92aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
93Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
94R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
95gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
96lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
97-----END CERTIFICATE-----
98"""
99
Alex Gaynore7f51982016-09-11 11:48:14 -0400100root_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500101MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
102jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
1033claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
104AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
105yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
1066JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
107BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
108u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
109PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
110I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
111ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
1126AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
113cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
114-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400115"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500116
Alex Gaynore7f51982016-09-11 11:48:14 -0400117intermediate_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700118MIICVzCCAcCgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQENBQAw
119WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
120DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTQw
121ODI4MDIwNDA4WhcNMjQwODI1MDIwNDA4WjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
122dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
123MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIGfMA0GCSqGSIb3DQEB
124AQUAA4GNADCBiQKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmK
125FGIbljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT
12621H2qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwID
127AQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDQUAA4GBAPIWSkLX
128QRMApOjjyC+tMxumT5e2pMqChHmxobQK4NMdrf2VCx+cRT6EmY8sK3/Xl/X8UBQ+
1299n5zXb1ZwhW/sTWgUvmOceJ4/XVs9FkdWOOn1J0XBch9ZIiFe/s5ASIgG7fUdcUF
1309mAWS6FK2ca3xIh5kIupCXOFa0dPvlw/YUFT
131-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400132"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700133
Alex Gaynore7f51982016-09-11 11:48:14 -0400134intermediate_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700135MIICWwIBAAKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmKFGIb
136ljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT21H2
137qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwIDAQAB
138AoGAfSZVV80pSeOKHTYfbGdNY/jHdU9eFUa/33YWriXU+77EhpIItJjkRRgivIfo
139rhFJpBSGmDLblaqepm8emsXMeH4+2QzOYIf0QGGP6E6scjTt1PLqdqKfVJ1a2REN
140147cujNcmFJb/5VQHHMpaPTgttEjlzuww4+BCDPsVRABWrkCQQD3loH36nLoQTtf
141+kQq0T6Bs9/UWkTAGo0ND81ALj0F8Ie1oeZg6RNT96RxZ3aVuFTESTv6/TbjWywO
142wdzlmV1vAkEA38rTJ6PTwaJlw5OttdDzAXGPB9tDmzh9oSi7cHwQQXizYd8MBYx4
143sjHUKD3dCQnb1dxJFhd3BT5HsnkRMbVZXQJAbXduH17ZTzcIOXc9jHDXYiFVZV5D
14452vV0WCbLzVCZc3jMrtSUKa8lPN5EWrdU3UchWybyG0MR5mX8S5lrF4SoQJAIyUD
145DBKaSqpqONCUUx1BTFS9FYrFjzbL4+c1qHCTTPTblt8kUCrDOZjBrKAqeiTmNSum
146/qUot9YUBF8m6BuGsQJATHHmdFy/fG1VLkyBp49CAa8tN3Z5r/CgTznI4DfMTf4C
147NbRHn2UmYlwQBa+L5lg9phewNe8aEwpPyPLoV85U8Q==
148-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400149"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700150
Alex Gaynore7f51982016-09-11 11:48:14 -0400151server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000152MIICJDCCAY2gAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
153BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
154VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMTA1
155N1oXDTM3MDYwNzAwMTA1N1owGDEWMBQGA1UEAwwNbG92ZWx5IHNlcnZlcjCBnzAN
156BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvqb4brndXS2kEL84qXbZXE6LYK+UrhNi
15770sdIM/24NVN7tXkPlOXqrMWhFHHml+aeSpPkH5b1vKnY1TcULmEubnNICtvjmZ5
158SGMQn+J+RmBs1SMd0EgY/0wBBQdlrlYp2QYgm8YC+zxTNSqWvhMFZAgHbj6Un5SS
159T8JGBqytjB0CAwEAAaM2MDQwHQYDVR0OBBYEFINVdy1eIfFJDAkk51QJEo3IfgSu
160MBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4GBAGki1K6WgHHJ
161qC6aY2EowjaWOXLO6jUZIhGk7BA7vMRfNug429AOZ4m5F6OQhzmJmlw67Jyu2FeI
162h0VtBuQoHPtjqZXF59oX6hMMmGLMs9pV0UA3fJs5MYA4/V5ZcQy0Ie0QoJNejLzE
1636V1Qz1rRTYLUyEcpI7ZCmBg2KQQI8YZI
Rick Dean94e46fd2009-07-18 14:51:24 -0500164-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400165"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500166
Alex Gaynore7f51982016-09-11 11:48:14 -0400167server_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500168MIICWwIBAAKBgQC+pvhuud1dLaQQvzipdtlcTotgr5SuE2LvSx0gz/bg1U3u1eQ+
169U5eqsxaEUceaX5p5Kk+QflvW8qdjVNxQuYS5uc0gK2+OZnlIYxCf4n5GYGzVIx3Q
170SBj/TAEFB2WuVinZBiCbxgL7PFM1Kpa+EwVkCAduPpSflJJPwkYGrK2MHQIDAQAB
171AoGAbwuZ0AR6JveahBaczjfnSpiFHf+mve2UxoQdpyr6ROJ4zg/PLW5K/KXrC48G
172j6f3tXMrfKHcpEoZrQWUfYBRCUsGD5DCazEhD8zlxEHahIsqpwA0WWssJA2VOLEN
173j6DuV2pCFbw67rfTBkTSo32ahfXxEKev5KswZk0JIzH3ooECQQDgzS9AI89h0gs8
174Dt+1m11Rzqo3vZML7ZIyGApUzVan+a7hbc33nbGRkAXjHaUBJO31it/H6dTO+uwX
175msWwNG5ZAkEA2RyFKs5xR5USTFaKLWCgpH/ydV96KPOpBND7TKQx62snDenFNNbn
176FwwOhpahld+vqhYk+pfuWWUpQciE+Bu7ZQJASjfT4sQv4qbbKK/scePicnDdx9th
1774e1EeB9xwb+tXXXUo/6Bor/AcUNwfiQ6Zt9PZOK9sR3lMZSsP7rMi7kzuQJABie6
1781sXXjFH7nNJvRG4S39cIxq8YRYTy68II/dlB2QzGpKxV/POCxbJ/zu0CU79tuYK7
179NaeNCFfH3aeTrX0LyQJAMBWjWmeKM2G2sCExheeQK0ROnaBC8itCECD4Jsve4nqf
180r50+LF74iLXFwqysVCebPKMOpDWp/qQ1BbJQIPs7/A==
181-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400182""")
Rick Dean94e46fd2009-07-18 14:51:24 -0500183
Alex Gaynore7f51982016-09-11 11:48:14 -0400184intermediate_server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700185MIICWDCCAcGgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQENBQAw
186ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
187CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
188biBEaWVnbzAeFw0xNDA4MjgwMjEwNDhaFw0yNDA4MjUwMjEwNDhaMG4xHTAbBgNV
189BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
190CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
191biBEaWVnbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqpJZygd+w1faLOr1
192iOAmbBhx5SZWcTCZ/ZjHQTJM7GuPT624QkqsixFghRKdDROwpwnAP7gMRukLqiy4
193+kRuGT5OfyGggL95i2xqA+zehjj08lSTlvGHpePJgCyTavIy5+Ljsj4DKnKyuhxm
194biXTRrH83NDgixVkObTEmh/OVK0CAwEAATANBgkqhkiG9w0BAQ0FAAOBgQBa0Npw
195UkzjaYEo1OUE1sTI6Mm4riTIHMak4/nswKh9hYup//WVOlr/RBSBtZ7Q/BwbjobN
1963bfAtV7eSAqBsfxYXyof7G1ALANQERkq3+oyLP1iVt08W1WOUlIMPhdCF/QuCwy6
197x9MJLhUCGLJPM+O2rAPWVD9wCmvq10ALsiH3yA==
198-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400199"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700200
Alex Gaynore7f51982016-09-11 11:48:14 -0400201intermediate_server_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700202MIICXAIBAAKBgQCqklnKB37DV9os6vWI4CZsGHHlJlZxMJn9mMdBMkzsa49PrbhC
203SqyLEWCFEp0NE7CnCcA/uAxG6QuqLLj6RG4ZPk5/IaCAv3mLbGoD7N6GOPTyVJOW
2048Yel48mALJNq8jLn4uOyPgMqcrK6HGZuJdNGsfzc0OCLFWQ5tMSaH85UrQIDAQAB
205AoGAIQ594j5zna3/9WaPsTgnmhlesVctt4AAx/n827DA4ayyuHFlXUuVhtoWR5Pk
2065ezj9mtYW8DyeCegABnsu2vZni/CdvU6uiS1Hv6qM1GyYDm9KWgovIP9rQCDSGaz
207d57IWVGxx7ODFkm3gN5nxnSBOFVHytuW1J7FBRnEsehRroECQQDXHFOv82JuXDcz
208z3+4c74IEURdOHcbycxlppmK9kFqm5lsUdydnnGW+mvwDk0APOB7Wg7vyFyr393e
209dpmBDCzNAkEAyv6tVbTKUYhSjW+QhabJo896/EqQEYUmtMXxk4cQnKeR/Ao84Rkf
210EqD5IykMUfUI0jJU4DGX+gWZ10a7kNbHYQJAVFCuHNFxS4Cpwo0aqtnzKoZaHY/8
211X9ABZfafSHCtw3Op92M+7ikkrOELXdS9KdKyyqbKJAKNEHF3LbOfB44WIQJAA2N4
2129UNNVUsXRbElEnYUS529CdUczo4QdVgQjkvk5RiPAUwSdBd9Q0xYnFOlFwEmIowg
213ipWJWe0aAlP18ZcEQQJBAL+5lekZ/GUdQoZ4HAsN5a9syrzavJ9VvU1KOOPorPZK
214nMRZbbQgP+aSB7yl6K0gaLaZ8XaK0pjxNBh6ASqg9f4=
215-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400216"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700217
Alex Gaynore7f51982016-09-11 11:48:14 -0400218client_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000219MIICIjCCAYugAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
220BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
221VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMDQx
222M1oXDTM3MDYwNzAwMDQxM1owFjEUMBIGA1UEAwwLdWdseSBjbGllbnQwgZ8wDQYJ
223KoZIhvcNAQEBBQADgY0AMIGJAoGBAMBmH9JG02bme0xPipvpjMSlOugyWrauf4at
224EdGJn7GQLD8IY2Fu0+Kvv9DFpSPboFKZCsfDVsYoRs+xaJbtt1dJ6ymX7EqKS7gb
2258q+eeZZ14keqyJd5Rm2q6swQtw9ADD3E8cS6GqpQm+8SgxOycISoYz7sO1ugJFqN
226jId+W4BFAgMBAAGjNjA0MB0GA1UdDgQWBBSDVXctXiHxSQwJJOdUCRKNyH4ErjAT
227BgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQAMqcHyweaCOZNN
228dWQQOsBKQlL5wqVVZwucHPWqobjxpULKy9gS2ha2zbgkXcB/BnBOSwe0Fm+MJV0T
229NbnTghcGJNpEH7VKn4xSLvIGZmnZZWgxeIB16z4GhpkK2fShBJ+6GKZjsgjT0lSH
230JRgjHbWutZfZvbSHXr9n7PIphG1Ojg==
Rick Dean94e46fd2009-07-18 14:51:24 -0500231-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400232"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500233
Alex Gaynore7f51982016-09-11 11:48:14 -0400234client_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500235MIICXgIBAAKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2rn+GrRHRiZ+xkCw/CGNh
236btPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xKiku4G/KvnnmWdeJHqsiX
237eUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7DtboCRajYyHfluARQIDAQAB
238AoGATkZ+NceY5Glqyl4mD06SdcKfV65814vg2EL7V9t8+/mi9rYL8KztSXGlQWPX
239zuHgtRoMl78yQ4ZJYOBVo+nsx8KZNRCEBlE19bamSbQLCeQMenWnpeYyQUZ908gF
240h6L9qsFVJepgA9RDgAjyDoS5CaWCdCCPCH2lDkdcqC54SVUCQQDseuduc4wi8h4t
241V8AahUn9fn9gYfhoNuM0gdguTA0nPLVWz4hy1yJiWYQe0H7NLNNTmCKiLQaJpAbb
242TC6vE8C7AkEA0Ee8CMJUc20BnGEmxwgWcVuqFWaKCo8jTH1X38FlATUsyR3krjW2
243dL3yDD9NwHxsYP7nTKp/U8MV7U9IBn4y/wJBAJl7H0/BcLeRmuJk7IqJ7b635iYB
244D/9beFUw3MUXmQXZUfyYz39xf6CDZsu1GEdEC5haykeln3Of4M9d/4Kj+FcCQQCY
245si6xwT7GzMDkk/ko684AV3KPc/h6G0yGtFIrMg7J3uExpR/VdH2KgwMkZXisSMvw
246JJEQjOMCVsEJlRk54WWjAkEAzoZNH6UhDdBK5F38rVt/y4SEHgbSfJHIAmPS32Kq
247f6GGcfNpip0Uk7q7udTKuX7Q/buZi/C4YW7u3VKAquv9NA==
248-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400249""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400250
Alex Gaynore7f51982016-09-11 11:48:14 -0400251cleartextCertificatePEM = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000252MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400253BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
Paul Kehrera40898b2017-06-11 16:30:58 -1000254ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
255WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
256BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
257bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
258bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
259LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
260onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
261LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
262yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
263aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
264Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
265R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
266gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
267lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400268-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400269"""
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400270
Alex Gaynore7f51982016-09-11 11:48:14 -0400271cleartextPrivateKeyPEM = normalize_privatekey_pem(b"""\
Jean-Paul Calderoned50d2042011-05-04 17:00:49 -0400272-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400273MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
274jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
2753claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
276AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
277yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
2786JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
279BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
280u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
281PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
282I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
283ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
2846AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
285cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
286-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400287""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400288
Alex Gaynore7f51982016-09-11 11:48:14 -0400289cleartextCertificateRequestPEM = b"""-----BEGIN CERTIFICATE REQUEST-----
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -0400290MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
291EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
292ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
293BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
294E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
295xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
296gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
297Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
298oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
299-----END CERTIFICATE REQUEST-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400300"""
Rick Dean5b7b6372009-04-01 11:34:06 -0500301
Alex Gaynore7f51982016-09-11 11:48:14 -0400302encryptedPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400303Proc-Type: 4,ENCRYPTED
304DEK-Info: DES-EDE3-CBC,9573604A18579E9E
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400305
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400306SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
307a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
3088+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
309mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
310+00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
311fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
312tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
313rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
314gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
315o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
3167SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
317MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
31811n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
319-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400320"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400321
Alex Gaynore7f51982016-09-11 11:48:14 -0400322encryptedPrivateKeyPEMPassphrase = b"foobar"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400323
Cory Benfield6492f7c2015-10-27 16:57:58 +0900324
Alex Gaynore7f51982016-09-11 11:48:14 -0400325cleartextPublicKeyPEM = b"""-----BEGIN PUBLIC KEY-----
Cory Benfield6492f7c2015-10-27 16:57:58 +0900326MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxszlc+b71LvlLS0ypt/l
327gT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZOtPclNY823Q4pErMTSWC
32890qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLjBuUIkQzEKEFV+8taiRV+
329ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPrUQqYQUEiTmVhh4FBUKZ5
330XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV215k4TeHMFYE5RG0KYAS
3318Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6HXRpQCyASzEG7bgtROLhL
332ywIDAQAB
333-----END PUBLIC KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400334"""
Cory Benfield6492f7c2015-10-27 16:57:58 +0900335
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400336# Some PKCS#7 stuff. Generated with the openssl command line:
337#
338# openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
339#
340# with a certificate and key (but the key should be irrelevant) in s.pem
Alex Gaynore7f51982016-09-11 11:48:14 -0400341pkcs7Data = b"""\
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400342-----BEGIN PKCS7-----
343MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
344BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
345A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
346MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
347cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
348A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
349HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
350SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
351zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
352LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
353A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
35465w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
355Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
356Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
357bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
358VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
359/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
360Ho4EzbYCOaEAMQA=
361-----END PKCS7-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400362"""
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400363
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700364pkcs7DataASN1 = base64.b64decode(b"""
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700365MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
366BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
367A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
368MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
369cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
370A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
371HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
372SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
373zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
374LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
375A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
37665w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
377Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
378Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
379bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
380VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
381/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
382Ho4EzbYCOaEAMQA=
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700383""")
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700384
Alex Gaynore7f51982016-09-11 11:48:14 -0400385crlData = b"""\
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -0500386-----BEGIN X509 CRL-----
387MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
388SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
389D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
390MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
391MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
3924dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
3930yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
394vrzEeLDRiiPl92dyyWmu
395-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400396"""
Jean-Paul Calderonee890db32010-08-22 16:55:15 -0400397
Alex Gaynore7f51982016-09-11 11:48:14 -0400398crlDataUnsupportedExtension = b"""\
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400399-----BEGIN X509 CRL-----
400MIIGRzCCBS8CAQIwDQYJKoZIhvcNAQELBQAwJzELMAkGA1UEBhMCVVMxGDAWBgNV
401BAMMD2NyeXB0b2dyYXBoeS5pbxgPMjAxNTAxMDEwMDAwMDBaGA8yMDE2MDEwMTAw
402MDAwMFowggTOMBQCAQAYDzIwMTUwMTAxMDAwMDAwWjByAgEBGA8yMDE1MDEwMTAw
403MDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAn
404MQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQD
405CgEAMHICAQIYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAw
406MDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlw
407dG9ncmFwaHkuaW8wCgYDVR0VBAMKAQEwcgIBAxgPMjAxNTAxMDEwMDAwMDBaMFww
408GAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTArpCkwJzELMAkGA1UE
409BhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNVHRUEAwoBAjByAgEE
410GA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQG
411A1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5
412LmlvMAoGA1UdFQQDCgEDMHICAQUYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQR
413GA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgw
414FgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQQwcgIBBhgPMjAxNTAx
415MDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTAr
416pCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNV
417HRUEAwoBBTByAgEHGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAx
418MDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwP
419Y3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEGMHICAQgYDzIwMTUwMTAxMDAwMDAw
420WjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJ
421BgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQgw
422cgIBCRgPMjAxNTAxMDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAw
423WjA0BgNVHR0ELTArpCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dy
424YXBoeS5pbzAKBgNVHRUEAwoBCTByAgEKGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNV
425HRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJV
426UzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEKMC4CAQsYDzIw
427MTUwMTAxMDAwMDAwWjAYMAoGA1UdFQQDCgEBMAoGAyoDBAQDCgEAMA0GCSqGSIb3
428DQEBCwUAA4IBAQBTaloHlPaCZzYee8LxkWej5meiqxQVNWFoVdjesroa+f1FRrH+
429drRU60Nq97KCKf7f9GNN/J3ZIlQmYhmuDqh12f+XLpotoj1ZRfBz2hjFCkJlv+2c
430oWWGNHgA70ndFoVtcmX088SYpX8E3ARATivS4q2h9WlwV6rO93mhg3HGIe3JpcK4
4317BcW6Poi/ut/zsDOkVbI00SqaujRpdmdCTht82MH3ztjyDkI9KYaD/YEweKSrWOz
432SdEILd164bfBeLuplVI+xpmTEMVNpXBlSXl7+xIw9Vk7p7Q1Pa3k/SvhOldYCm6y
433C1xAg/AAq6w78yzYt18j5Mj0s6eeHi1YpHKw
434-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400435"""
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400436
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400437
438# A broken RSA private key which can be used to test the error path through
439# PKey.check.
Alex Gaynore7f51982016-09-11 11:48:14 -0400440inconsistentPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400441MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
4425kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
443OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
444zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
445nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
446HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
447oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
448-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400449"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400450
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400451# certificate with NULL bytes in subjectAltName and common name
452
Alex Gaynore7f51982016-09-11 11:48:14 -0400453nulbyteSubjectAltNamePEM = b"""-----BEGIN CERTIFICATE-----
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400454MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
455DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
456eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
457RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
458ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
459NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
460DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
461ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
462ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
463hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
464BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
465pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
466vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
467KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
468oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
46908LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
470HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
471BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
472Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
473bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
474AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
475i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
476HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
477kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
478VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
479RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
Alex Gaynore7f51982016-09-11 11:48:14 -0400480-----END CERTIFICATE-----"""
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400481
Alex Gaynore7f51982016-09-11 11:48:14 -0400482large_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Colleen Murphye09399b2016-03-01 17:40:49 -0800483MIIJYgIBAAKCAg4AtRua8eIeevRfsj+fkcHr1vmse7Kgb+oX1ssJAvCb1R7JQMnH
484hNDjDP6b3vEkZuPUzlDHymP+cNkXvvi4wJ4miVbO3+SeU4Sh+jmsHeHzGIXat9xW
4859PFtuPM5FQq8zvkY8aDeRYmYwN9JKu4/neMBCBqostYlTEWg+bSytO/qWnyHTHKh
486g0GfaDdqUQPsGQw+J0MgaYIjQOCVASHAPlzbDQLCtuOb587rwTLkZA2GwoHB/LyJ
487BwT0HHgBaiObE12Vs6wi2en0Uu11CiwEuK1KIBcZ2XbE6eApaZa6VH9ysEmUxPt7
488TqyZ4E2oMIYaLPNRxuvozdwTlj1svI1k1FrkaXGc5MTjbgigPMKjIb0T7b/4GNzt
489DhP1LvAeUMnrEi3hJJrcJPXHPqS8/RiytR9xQQW6Sdh4LaA3f9MQm3WSevWage3G
490P8YcCLssOVKsArDjuA52NF5LmYuAeUzXprm4ITDi2oO+0iFBpFW6VPEK4A9vO0Yk
491M/6Wt6tG8zyWhaSH1zFUTwfQ9Yvjyt5w1lrUaAJuoTpwbMVZaDJaEhjOaXU0dyPQ
492jOsePDOQcU6dkeTWsQ3LsHPEEug/X6819TLG5mb3V7bvV9nPFBfTJSCEG794kr90
493XgZfIN71FrdByxLerlbuJI21pPs/nZi9SXi9jAWeiS45/azUxMsyYgJArui+gjq7
494sV1pWiBm6/orAgMBAAECggINQp5L6Yu+oIXBqcSjgq8tfF9M5hd30pLuf/EheHZf
495LA7uAqn2fVGFI2OInIJhXIOT5OxsAXO0xXfltzawZxIFpOFMqajj4F7aYjvSpw9V
496J4EdSiJ/zgv8y1qUdbwEZbHVThRZjoSlrtSzilonBoHZAE0mHtqMz7iRFSk1zz6t
497GunRrvo/lROPentf3TsvHquVNUYI5yaapyO1S7xJhecMIIYSb8nbsHI54FBDGNas
4986mFmpPwI/47/6HTwOEWupnn3NicsjrHzUInOUpaMig4cRR+aP5bjqg/ty8xI8AoN
499evEmCytiWTc+Rvbp1ieN+1jpjN18PjUk80/W7qioHUDt4ieLic8uxWH2VD9SCEnX
500Mpi9tA/FqoZ+2A/3m1OfrY6jiZVE2g+asi9lCK7QVWL39eK82H4rPvtp0/dyo1/i
501ZZz68TXg+m8IgEZcp88hngbkuoTTzpGE73QuPKhGA1uMIimDdqPPB5WP76q+03Oi
502IRR5DfZnqPERed49by0enJ7tKa/gFPZizOV8ALKr0Dp+vfAkxGDLPLBLd2A3//tw
503xg0Q/wltihHSBujv4nYlDXdc5oYyMYZ+Lhc/VuOghHfBq3tgEQ1ECM/ofqXEIdy7
504nVcpZn3Eeq8Jl5CrqxE1ee3NxlzsJHn99yGQpr7mOhW/psJF3XNz80Meg3L4m1T8
505sMBK0GbaassuJhdzb5whAoIBBw48sx1b1WR4XxQc5O/HjHva+l16i2pjUnOUTcDF
506RWmSbIhBm2QQ2rVhO8+fak0tkl6ZnMWW4i0U/X5LOEBbC7+IS8bO3j3Revi+Vw5x
507j96LMlIe9XEub5i/saEWgiz7maCvfzLFU08e1OpT4qPDpP293V400ubA6R7WQTCv
508pBkskGwHeu0l/TuKkVqBFFUTu7KEbps8Gjg7MkJaFriAOv1zis/umK8pVS3ZAM6e
5098w5jfpRccn8Xzta2fRwTB5kCmfxdDsY0oYGxPLRAbW72bORoLGuyyPp/ojeGwoik
510JX9RttErc6FjyZtks370Pa8UL5QskyhMbDhrZW2jFD+RXYM1BrvmZRjbAoIBBwy4
511iFJpuDfytJfz1MWtaL5DqEL/kmiZYAXl6hifNhGu5GAipVIIGsDqEYW4i+VC15aa
5127kOCwz/I5zsB3vSDW96IRs4wXtqEZSibc2W/bqfVi+xcvPPl1ZhQ2EAwa4D/x035
513kyf20ffWOU+1yf2cnijzqs3IzlveUm+meLw5s3Rc+iG7DPWWeCoe1hVwANI1euNc
514pqKwKY905yFyjOje2OgiEU2kS4YME4zGeBys8yo7E42hNnN2EPK6xkkUqzdudLLQ
5158OUlKRTc8AbIf3XG1rpA4VUpTv3hhxGGwCRy6If8zgZQsNYchgNztRGk72Gcb8Dm
516vFSEN3ZtwxU64G3YZzntdcr2WPzxAoIBBw30g6Fgdb/gmVnOpL0//T0ePNDKIMPs
517jVJLaRduhoZgB1Bb9qPUPX0SzRzLZtg1tkZSDjBDoHmOHJfhxUaXt+FLCPPbrE4t
518+nq9n/nBaMM779w9ClqhqLOyGrwKoxjSmhi+TVEHyIxCbXMvPHVHfX9WzxjbcGrN
519ZvRaEVZWo+QlIX8yqdSwqxLk1WtAIRzvlcj7NKum8xBxPed6BNFep/PtgIAmoLT5
520L8wb7EWb2iUdc2KbZ4OaY51lDScqpATgXu3WjXfM+Q52G0mX6Wyd0cjlL711Zrjb
521yLbiueZT94lgIHHRRKtKc8CEqcjkQV5OzABS3P/gQSfgZXBdLKjOpTnKDUq7IBeH
522AoIBBweAOEIAPLQg1QRUrr3xRrYKRwlakgZDii9wJt1l5AgBTICzbTA1vzDJ1JM5
523AqSpCV6w9JWyYVcXK+HLdKBRZLaPPNEQDJ5lOxD6uMziWGl2rg8tj+1xNMWfxiPz
524aTCjoe4EoBUMoTq2gwzRcM2usEQNikXVhnj9Wzaivsaeb4bJ3GRPW5DkrO6JSEtT
525w+gvyMqQM2Hy5k7E7BT46sXVwaj/jZxuqGnebRixXtnp0WixdRIqYWUr1UqLf6hQ
526G7WP2BgoxCMaCmNW8+HMD/xuxucEotoIhZ+GgJKBFoNnjl3BX+qxYdSe9RbL/5Tr
5274It6Jxtj8uETJXEbv9Cg6v1agWPS9YY8RLTBAoIBBwrU2AsAUts6h1LgGLKK3UWZ
528oLH5E+4o+7HqSGRcRodVeN9NBXIYdHHOLeEG6YNGJiJ3bFP5ZQEu9iDsyoFVKJ9O
529Mw/y6dKZuxOCZ+X8FopSROg3yWfdOpAm6cnQZp3WqLNX4n/Q6WvKojfyEiPphjwT
5300ymrUJELXLWJmjUyPoAk6HgC0Gs28ZnEXbyhx7CSbZNFyCU/PNUDZwto3GisIPD3
531le7YjqHugezmjMGlA0sDw5aCXjfbl74vowRFYMO6e3ItApfSRgNV86CDoX74WI/5
532AYU/QVM4wGt8XGT2KwDFJaxYGKsGDMWmXY04dS+WPuetCbouWUusyFwRb9SzFave
533vYeU7Ab/
Alex Gaynore7f51982016-09-11 11:48:14 -0400534-----END RSA PRIVATE KEY-----"""
Colleen Murphye09399b2016-03-01 17:40:49 -0800535
Paul Kehrer72d968b2016-07-29 15:31:04 +0800536ec_private_key_pem = b"""-----BEGIN PRIVATE KEY-----
537MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgYirTZSx+5O8Y6tlG
538cka6W6btJiocdrdolfcukSoTEk+hRANCAAQkvPNu7Pa1GcsWU4v7ptNfqCJVq8Cx
539zo0MUVPQgwJ3aJtNM1QMOQUayCrRwfklg+D/rFSUwEUqtZh7fJDiFqz3
540-----END PRIVATE KEY-----
541"""
542
Paul Kehrer59d26252017-07-20 10:45:54 +0200543ec_root_key_pem = b"""-----BEGIN EC PRIVATE KEY-----
544MIGlAgEBBDEAz/HOBFPYLB0jLWeTpJn4Yc4m/C4mdWymVHBjOmnwiPHKT326iYN/
545ZhmSs+RM94RsoAcGBSuBBAAioWQDYgAEwE5vDdla/nLpWAPAQ0yFGqwLuw4BcN2r
546U+sKab5EAEHzLeceRa8ffncYdCXNoVsBcdob1y66CFZMEWLetPTmGapyWkBAs6/L
5478kUlkU9OsE+7IVo4QQJkgV5gM+Dim1XE
548-----END EC PRIVATE KEY-----
549"""
550
551ec_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
552MIICLTCCAbKgAwIBAgIMWW/hwTl6ufz6/WkCMAoGCCqGSM49BAMDMFgxGDAWBgNV
553BAMTD1Rlc3RpbmcgUm9vdCBDQTEQMA4GA1UEChMHVGVzdGluZzEQMA4GA1UEBxMH
554Q2hpY2FnbzELMAkGA1UECBMCSUwxCzAJBgNVBAYTAlVTMCAXDTE3MDcxOTIyNDgz
555M1oYDzk5OTkxMjMxMjM1OTU5WjBYMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0Ex
556EDAOBgNVBAoTB1Rlc3RpbmcxEDAOBgNVBAcTB0NoaWNhZ28xCzAJBgNVBAgTAklM
557MQswCQYDVQQGEwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABMBObw3ZWv5y6VgD
558wENMhRqsC7sOAXDdq1PrCmm+RABB8y3nHkWvH353GHQlzaFbAXHaG9cuughWTBFi
5593rT05hmqclpAQLOvy/JFJZFPTrBPuyFaOEECZIFeYDPg4ptVxKNDMEEwDwYDVR0T
560AQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwQAMB0GA1UdDgQWBBSoTrF0H2m8RDzB
561MnY2KReEPfz7ZjAKBggqhkjOPQQDAwNpADBmAjEA3+G1oVCxGjYX4iUN93QYcNHe
562e3fJQJwX9+KsHRut6qNZDUbvRbtO1YIAwB4UJZjwAjEAtXCPURS5A4McZHnSwgTi
563Td8GMrwKz0557OxxtKN6uVVy4ACFMqEw0zN/KJI1vxc9
564-----END CERTIFICATE-----"""
565
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400566
Alex Chanc6077062016-11-18 13:53:39 +0000567@pytest.fixture
568def x509_data():
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400569 """
Alex Chanc6077062016-11-18 13:53:39 +0000570 Create a new private key and start a certificate request (for a test
571 to finish in one way or another).
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400572 """
Alex Chanc6077062016-11-18 13:53:39 +0000573 # Basic setup stuff to generate a certificate
574 pkey = PKey()
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400575 pkey.generate_key(TYPE_RSA, 512)
Alex Chanc6077062016-11-18 13:53:39 +0000576 req = X509Req()
577 req.set_pubkey(pkey)
578 # Authority good you have.
579 req.get_subject().commonName = "Yoda root CA"
580 x509 = X509()
581 subject = x509.get_subject()
582 subject.commonName = req.get_subject().commonName
583 x509.set_issuer(subject)
584 x509.set_pubkey(pkey)
585 now = datetime.now()
586 expire = datetime.now() + timedelta(days=100)
587 x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
588 x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
589 yield pkey, x509
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400590
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400591
Alex Chanc6077062016-11-18 13:53:39 +0000592class TestX509Ext(object):
593 """
594 Tests for `OpenSSL.crypto.X509Extension`.
595 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -0800596
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400597 def test_str(self):
598 """
Alex Chanc6077062016-11-18 13:53:39 +0000599 The string representation of `X509Extension` instances as
600 returned by `str` includes stuff.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400601 """
602 # This isn't necessarily the best string representation. Perhaps it
603 # will be changed/improved in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000604 assert (
605 str(X509Extension(b'basicConstraints', True, b'CA:false')) ==
606 'CA:FALSE'
607 )
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400608
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400609 def test_type(self):
610 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500611 `X509Extension` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400612 """
Alex Chanc6077062016-11-18 13:53:39 +0000613 assert is_consistent_type(
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400614 X509Extension,
Alex Gaynore7f51982016-09-11 11:48:14 -0400615 'X509Extension', b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400616
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500617 def test_construction(self):
618 """
Alex Chanc6077062016-11-18 13:53:39 +0000619 `X509Extension` accepts an extension type name, a critical flag,
Alex Gaynor01f90a12019-02-07 09:14:48 -0500620 and an extension value and returns an `X509Extension` instance.
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500621 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400622 basic = X509Extension(b'basicConstraints', True, b'CA:true')
Alex Gaynor01f90a12019-02-07 09:14:48 -0500623 assert isinstance(basic, X509Extension)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500624
Alex Chanc6077062016-11-18 13:53:39 +0000625 comment = X509Extension(b'nsComment', False, b'pyOpenSSL unit test')
Alex Gaynor01f90a12019-02-07 09:14:48 -0500626 assert isinstance(comment, X509Extension)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500627
Alex Chanc6077062016-11-18 13:53:39 +0000628 @pytest.mark.parametrize('type_name, critical, value', [
629 (b'thisIsMadeUp', False, b'hi'),
630 (b'basicConstraints', False, b'blah blah'),
Jean-Paul Calderone391585f2008-12-31 14:36:31 -0500631
Jean-Paul Calderone2ee1e7c2008-12-31 14:58:38 -0500632 # Exercise a weird one (an extension which uses the r2i method). This
633 # exercises the codepath that requires a non-NULL ctx to be passed to
634 # X509V3_EXT_nconf. It can't work now because we provide no
635 # configuration database. It might be made to work in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000636 (b'proxyCertInfo', True,
637 b'language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')
638 ])
639 def test_invalid_extension(self, type_name, critical, value):
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500640 """
Alex Chanc6077062016-11-18 13:53:39 +0000641 `X509Extension` raises something if it is passed a bad
642 extension name or value.
643 """
644 with pytest.raises(Error):
645 X509Extension(type_name, critical, value)
646
647 @pytest.mark.parametrize('critical_flag', [True, False])
648 def test_get_critical(self, critical_flag):
649 """
650 `X509ExtensionType.get_critical` returns the value of the
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500651 extension's critical flag.
652 """
Alex Chanc6077062016-11-18 13:53:39 +0000653 ext = X509Extension(b'basicConstraints', critical_flag, b'CA:true')
654 assert ext.get_critical() == critical_flag
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500655
Alex Chanc6077062016-11-18 13:53:39 +0000656 @pytest.mark.parametrize('short_name, value', [
657 (b'basicConstraints', b'CA:true'),
658 (b'nsComment', b'foo bar'),
659 ])
660 def test_get_short_name(self, short_name, value):
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500661 """
Alex Chanc6077062016-11-18 13:53:39 +0000662 `X509ExtensionType.get_short_name` returns a string giving the
Alex Gaynor31287502015-09-05 16:11:27 -0400663 short type name of the extension.
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500664 """
Alex Chanc6077062016-11-18 13:53:39 +0000665 ext = X509Extension(short_name, True, value)
666 assert ext.get_short_name() == short_name
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500667
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400668 def test_get_data(self):
669 """
Alex Chanc6077062016-11-18 13:53:39 +0000670 `X509Extension.get_data` returns a string giving the data of
Alex Gaynor31287502015-09-05 16:11:27 -0400671 the extension.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400672 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400673 ext = X509Extension(b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400674 # Expect to get back the DER encoded form of CA:true.
Alex Chanc6077062016-11-18 13:53:39 +0000675 assert ext.get_data() == b'0\x03\x01\x01\xff'
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400676
Alex Chanc6077062016-11-18 13:53:39 +0000677 def test_unused_subject(self, x509_data):
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400678 """
Alex Chanc6077062016-11-18 13:53:39 +0000679 The `subject` parameter to `X509Extension` may be provided for an
680 extension which does not use it and is ignored in this case.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400681 """
Alex Chanc6077062016-11-18 13:53:39 +0000682 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400683 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000684 b'basicConstraints', False, b'CA:TRUE', subject=x509)
685 x509.add_extensions([ext1])
686 x509.sign(pkey, 'sha1')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400687 # This is a little lame. Can we think of a better way?
Alex Chanc6077062016-11-18 13:53:39 +0000688 text = dump_certificate(FILETYPE_TEXT, x509)
689 assert b'X509v3 Basic Constraints:' in text
690 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400691
Alex Chanc6077062016-11-18 13:53:39 +0000692 def test_subject(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400693 """
Alex Chanc6077062016-11-18 13:53:39 +0000694 If an extension requires a subject, the `subject` parameter to
695 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400696 """
Alex Chanc6077062016-11-18 13:53:39 +0000697 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400698 ext3 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000699 b'subjectKeyIdentifier', False, b'hash', subject=x509)
700 x509.add_extensions([ext3])
701 x509.sign(pkey, 'sha1')
702 text = dump_certificate(FILETYPE_TEXT, x509)
703 assert b'X509v3 Subject Key Identifier:' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400704
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400705 def test_missing_subject(self):
706 """
Alex Chanc6077062016-11-18 13:53:39 +0000707 If an extension requires a subject and the `subject` parameter
Alex Gaynor31287502015-09-05 16:11:27 -0400708 is given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400709 """
Alex Chanc6077062016-11-18 13:53:39 +0000710 with pytest.raises(Error):
711 X509Extension(b'subjectKeyIdentifier', False, b'hash')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400712
Alex Chanc6077062016-11-18 13:53:39 +0000713 @pytest.mark.parametrize('bad_obj', [
714 True,
715 object(),
716 "hello",
717 [],
718 ])
719 def test_invalid_subject(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400720 """
Alex Chanc6077062016-11-18 13:53:39 +0000721 If the `subject` parameter is given a value which is not an
722 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400723 """
Alex Chanc6077062016-11-18 13:53:39 +0000724 with pytest.raises(TypeError):
725 X509Extension(
726 'basicConstraints', False, 'CA:TRUE', subject=bad_obj)
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400727
Alex Chanc6077062016-11-18 13:53:39 +0000728 def test_unused_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400729 """
Alex Chanc6077062016-11-18 13:53:39 +0000730 The `issuer` parameter to `X509Extension` may be provided for an
731 extension which does not use it and is ignored in this case.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400732 """
Alex Chanc6077062016-11-18 13:53:39 +0000733 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400734 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000735 b'basicConstraints', False, b'CA:TRUE', issuer=x509)
736 x509.add_extensions([ext1])
737 x509.sign(pkey, 'sha1')
738 text = dump_certificate(FILETYPE_TEXT, x509)
739 assert b'X509v3 Basic Constraints:' in text
740 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400741
Alex Chanc6077062016-11-18 13:53:39 +0000742 def test_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400743 """
Alex Chanc6077062016-11-18 13:53:39 +0000744 If an extension requires an issuer, the `issuer` parameter to
745 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400746 """
Alex Chanc6077062016-11-18 13:53:39 +0000747 pkey, x509 = x509_data
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400748 ext2 = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -0400749 b'authorityKeyIdentifier', False, b'issuer:always',
Alex Chanc6077062016-11-18 13:53:39 +0000750 issuer=x509)
751 x509.add_extensions([ext2])
752 x509.sign(pkey, 'sha1')
753 text = dump_certificate(FILETYPE_TEXT, x509)
754 assert b'X509v3 Authority Key Identifier:' in text
755 assert b'DirName:/CN=Yoda root CA' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400756
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400757 def test_missing_issuer(self):
758 """
Alex Chanc6077062016-11-18 13:53:39 +0000759 If an extension requires an issue and the `issuer` parameter is
760 given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400761 """
Alex Chanc6077062016-11-18 13:53:39 +0000762 with pytest.raises(Error):
763 X509Extension(
764 b'authorityKeyIdentifier',
765 False, b'keyid:always,issuer:always')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400766
Alex Chanc6077062016-11-18 13:53:39 +0000767 @pytest.mark.parametrize('bad_obj', [
768 True,
769 object(),
770 "hello",
771 [],
772 ])
773 def test_invalid_issuer(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400774 """
Alex Chanc6077062016-11-18 13:53:39 +0000775 If the `issuer` parameter is given a value which is not an
776 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400777 """
Alex Chanc6077062016-11-18 13:53:39 +0000778 with pytest.raises(TypeError):
779 X509Extension(
780 'basicConstraints', False, 'keyid:always,issuer:always',
781 issuer=bad_obj)
Rick Dean47262da2009-07-08 16:17:17 -0500782
783
Paul Kehrer72d968b2016-07-29 15:31:04 +0800784class TestPKey(object):
785 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +0100786 Tests for `OpenSSL.crypto.PKey`.
Paul Kehrer72d968b2016-07-29 15:31:04 +0800787 """
788
789 def test_convert_from_cryptography_private_key(self):
790 """
791 PKey.from_cryptography_key creates a proper private PKey.
792 """
793 key = serialization.load_pem_private_key(
794 intermediate_key_pem, None, backend
795 )
796 pkey = PKey.from_cryptography_key(key)
797
798 assert isinstance(pkey, PKey)
799 assert pkey.bits() == key.key_size
800 assert pkey._only_public is False
801 assert pkey._initialized is True
802
803 def test_convert_from_cryptography_public_key(self):
804 """
805 PKey.from_cryptography_key creates a proper public PKey.
806 """
807 key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
808 pkey = PKey.from_cryptography_key(key)
809
810 assert isinstance(pkey, PKey)
811 assert pkey.bits() == key.key_size
812 assert pkey._only_public is True
813 assert pkey._initialized is True
814
815 def test_convert_from_cryptography_unsupported_type(self):
816 """
817 PKey.from_cryptography_key raises TypeError with an unsupported type.
818 """
819 key = serialization.load_pem_private_key(
820 ec_private_key_pem, None, backend
821 )
822 with pytest.raises(TypeError):
823 PKey.from_cryptography_key(key)
824
825 def test_convert_public_pkey_to_cryptography_key(self):
826 """
827 PKey.to_cryptography_key creates a proper cryptography public key.
828 """
829 pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
830 key = pkey.to_cryptography_key()
831
832 assert isinstance(key, rsa.RSAPublicKey)
833 assert pkey.bits() == key.key_size
834
835 def test_convert_private_pkey_to_cryptography_key(self):
836 """
837 PKey.to_cryptography_key creates a proper cryptography private key.
838 """
839 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
840 key = pkey.to_cryptography_key()
841
842 assert isinstance(key, rsa.RSAPrivateKey)
843 assert pkey.bits() == key.key_size
844
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400845 def test_type(self):
846 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500847 `PKey` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400848 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000849 assert is_consistent_type(PKey, 'PKey')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400850
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500851 def test_construction(self):
852 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000853 `PKey` takes no arguments and returns a new `PKey` instance.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500854 """
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500855 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000856 assert isinstance(key, PKey)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500857
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500858 def test_pregeneration(self):
859 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000860 `PKey.bits` and `PKey.type` return `0` before the key is generated.
861 `PKey.check` raises `TypeError` before the key is generated.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500862 """
863 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000864 assert key.type() == 0
865 assert key.bits() == 0
866 with pytest.raises(TypeError):
867 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500868
Alex Chan9e2a9932017-01-25 14:29:19 +0000869 def test_failed_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500870 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000871 `PKey.generate_key` takes two arguments, the first giving the key type
872 as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
873 bits to generate. If an invalid type is specified or generation fails,
874 `Error` is raised. If an invalid number of bits is specified,
875 `ValueError` or `Error` is raised.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500876 """
877 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000878 with pytest.raises(TypeError):
879 key.generate_key("foo", "bar")
880 with pytest.raises(Error):
881 key.generate_key(-1, 0)
Jean-Paul Calderoneab82db72008-03-06 00:09:31 -0500882
Alex Chan9e2a9932017-01-25 14:29:19 +0000883 with pytest.raises(ValueError):
884 key.generate_key(TYPE_RSA, -1)
885 with pytest.raises(ValueError):
886 key.generate_key(TYPE_RSA, 0)
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500887
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400888 with pytest.raises(TypeError):
889 key.generate_key(TYPE_RSA, object())
890
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500891 # XXX RSA generation for small values of bits is fairly buggy in a wide
892 # range of OpenSSL versions. I need to figure out what the safe lower
893 # bound for a reasonable number of OpenSSL versions is and explicitly
894 # check for that in the wrapper. The failure behavior is typically an
895 # infinite loop inside OpenSSL.
896
Alex Chan9e2a9932017-01-25 14:29:19 +0000897 # with pytest.raises(Error):
898 # key.generate_key(TYPE_RSA, 2)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500899
900 # XXX DSA generation seems happy with any number of bits. The DSS
901 # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
902 # generator doesn't seem to care about the upper limit at all. For
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500903 # the lower limit, it uses 512 if anything smaller is specified.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500904 # So, it doesn't seem possible to make generate_key fail for
905 # TYPE_DSA with a bits argument which is at least an int.
906
Alex Chan9e2a9932017-01-25 14:29:19 +0000907 # with pytest.raises(Error):
908 # key.generate_key(TYPE_DSA, -7)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500909
Alex Chan9e2a9932017-01-25 14:29:19 +0000910 def test_rsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500911 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000912 `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
913 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500914 """
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400915 bits = 512
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500916 key = PKey()
917 key.generate_key(TYPE_RSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000918 assert key.type() == TYPE_RSA
919 assert key.bits() == bits
920 assert key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500921
Alex Chan9e2a9932017-01-25 14:29:19 +0000922 def test_dsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500923 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000924 `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
925 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500926 """
927 # 512 is a magic number. The DSS (Digital Signature Standard)
928 # allows a minimum of 512 bits for DSA. DSA_generate_parameters
929 # will silently promote any value below 512 to 512.
930 bits = 512
931 key = PKey()
932 key.generate_key(TYPE_DSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000933 assert key.type() == TYPE_DSA
934 assert key.bits() == bits
935 with pytest.raises(TypeError):
936 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500937
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500938 def test_regeneration(self):
939 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000940 `PKey.generate_key` can be called multiple times on the same key to
941 generate new keys.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500942 """
943 key = PKey()
944 for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
Alex Gaynor7f636492015-09-04 13:26:52 -0400945 key.generate_key(type, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000946 assert key.type() == type
947 assert key.bits() == bits
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500948
Alex Chan9e2a9932017-01-25 14:29:19 +0000949 def test_inconsistent_key(self):
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400950 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000951 `PKey.check` returns `Error` if the key is not consistent.
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400952 """
953 key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
Alex Chan9e2a9932017-01-25 14:29:19 +0000954 with pytest.raises(Error):
955 key.check()
Jean-Paul Calderonee81020e2011-06-12 21:48:57 -0400956
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400957 def test_check_public_key(self):
958 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000959 `PKey.check` raises `TypeError` if only the public part of the key
960 is available.
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400961 """
962 # A trick to get a public-only key
963 key = PKey()
964 key.generate_key(TYPE_RSA, 512)
965 cert = X509()
966 cert.set_pubkey(key)
967 pub = cert.get_pubkey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000968 with pytest.raises(TypeError):
969 pub.check()
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400970
971
Alex Chan9e2a9932017-01-25 14:29:19 +0000972def x509_name(**attrs):
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500973 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000974 Return a new X509Name with the given attributes.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500975 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000976 # XXX There's no other way to get a new X509Name yet.
977 name = X509().get_subject()
978 attrs = list(attrs.items())
Alex Gaynoraceb3e22015-09-05 12:00:22 -0400979
Alex Chan9e2a9932017-01-25 14:29:19 +0000980 # Make the order stable - order matters!
981 def key(attr):
982 return attr[1]
983 attrs.sort(key=key)
984 for k, v in attrs:
985 setattr(name, k, v)
986 return name
Alex Gaynor85b49702015-09-05 16:30:59 -0400987
Alex Chan9e2a9932017-01-25 14:29:19 +0000988
989class TestX509Name(object):
990 """
991 Unit tests for `OpenSSL.crypto.X509Name`.
992 """
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -0500993
Rick Deane15b1472009-07-09 15:53:42 -0500994 def test_type(self):
995 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500996 The type of X509Name objects is `X509Name`.
Rick Deane15b1472009-07-09 15:53:42 -0500997 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000998 name = x509_name()
Alex Gaynor01f90a12019-02-07 09:14:48 -0500999 assert isinstance(name, X509Name)
Rick Deane15b1472009-07-09 15:53:42 -05001000
Alex Chan9e2a9932017-01-25 14:29:19 +00001001 def test_only_string_attributes(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001002 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001003 Attempting to set a non-`str` attribute name on an `X509Name` instance
1004 causes `TypeError` to be raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001005 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001006 name = x509_name()
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001007 # Beyond these cases, you may also think that unicode should be
Alex Gaynor31287502015-09-05 16:11:27 -04001008 # rejected. Sorry, you're wrong. unicode is automatically converted
1009 # to str outside of the control of X509Name, so there's no way to
1010 # reject it.
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -08001011
Alex Gaynor31287502015-09-05 16:11:27 -04001012 # Also, this used to test str subclasses, but that test is less
1013 # relevant now that the implementation is in Python instead of C. Also
1014 # PyPy automatically converts str subclasses to str when they are
1015 # passed to setattr, so we can't test it on PyPy. Apparently CPython
1016 # does this sometimes as well.
Alex Chan9e2a9932017-01-25 14:29:19 +00001017 with pytest.raises(TypeError):
1018 setattr(name, None, "hello")
1019 with pytest.raises(TypeError):
1020 setattr(name, 30, "hello")
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001021
Alex Chan9e2a9932017-01-25 14:29:19 +00001022 def test_set_invalid_attribute(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001023 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001024 Attempting to set any attribute name on an `X509Name` instance for
1025 which no corresponding NID is defined causes `AttributeError` to be
1026 raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001027 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001028 name = x509_name()
1029 with pytest.raises(AttributeError):
1030 setattr(name, "no such thing", None)
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001031
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001032 def test_attributes(self):
1033 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001034 `X509Name` instances have attributes for each standard (?)
1035 X509Name field.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001036 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001037 name = x509_name()
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001038 name.commonName = "foo"
Alex Gaynor37726112016-07-04 09:51:32 -04001039 assert name.commonName == "foo"
1040 assert name.CN == "foo"
1041
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001042 name.CN = "baz"
Alex Gaynor37726112016-07-04 09:51:32 -04001043 assert name.commonName == "baz"
1044 assert name.CN == "baz"
1045
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001046 name.commonName = "bar"
Alex Gaynor37726112016-07-04 09:51:32 -04001047 assert name.commonName == "bar"
1048 assert name.CN == "bar"
1049
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001050 name.CN = "quux"
Alex Gaynor37726112016-07-04 09:51:32 -04001051 assert name.commonName == "quux"
1052 assert name.CN == "quux"
1053
1054 assert name.OU is None
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001055
Alex Gaynor7778e792016-07-03 23:38:48 -04001056 with pytest.raises(AttributeError):
1057 name.foobar
1058
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001059 def test_copy(self):
1060 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001061 `X509Name` creates a new `X509Name` instance with all the same
1062 attributes as an existing `X509Name` instance when called with one.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001063 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001064 name = x509_name(commonName="foo", emailAddress="bar@example.com")
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001065
1066 copy = X509Name(name)
Alex Chan9e2a9932017-01-25 14:29:19 +00001067 assert copy.commonName == "foo"
1068 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001069
1070 # Mutate the copy and ensure the original is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001071 copy.commonName = "baz"
Alex Chan9e2a9932017-01-25 14:29:19 +00001072 assert name.commonName == "foo"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001073
1074 # Mutate the original and ensure the copy is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001075 name.emailAddress = "quux@example.com"
Alex Chan9e2a9932017-01-25 14:29:19 +00001076 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001077
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001078 def test_repr(self):
1079 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001080 `repr` passed an `X509Name` instance should return a string containing
1081 a description of the type and the NIDs which have been set on it.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001082 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001083 name = x509_name(commonName="foo", emailAddress="bar")
1084 assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001085
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001086 def test_comparison(self):
1087 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001088 `X509Name` instances should compare based on their NIDs.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001089 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001090 def _equality(a, b, assert_true, assert_false):
1091 assert_true(a == b)
1092 assert_false(a != b)
1093 assert_true(b == a)
1094 assert_false(b != a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001095
Alex Chan9e2a9932017-01-25 14:29:19 +00001096 def assert_true(x):
1097 assert x
1098
1099 def assert_false(x):
1100 assert not x
1101
1102 def assert_equal(a, b):
1103 _equality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001104
1105 # Instances compare equal to themselves.
Alex Chan9e2a9932017-01-25 14:29:19 +00001106 name = x509_name()
1107 assert_equal(name, name)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001108
1109 # Empty instances should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001110 assert_equal(x509_name(), x509_name())
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001111
1112 # Instances with equal NIDs should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001113 assert_equal(x509_name(commonName="foo"),
1114 x509_name(commonName="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001115
1116 # Instance with equal NIDs set using different aliases should compare
1117 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001118 assert_equal(x509_name(commonName="foo"),
1119 x509_name(CN="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001120
1121 # Instances with more than one NID with the same values should compare
1122 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001123 assert_equal(x509_name(CN="foo", organizationalUnitName="bar"),
1124 x509_name(commonName="foo", OU="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001125
Alex Chan9e2a9932017-01-25 14:29:19 +00001126 def assert_not_equal(a, b):
1127 _equality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001128
1129 # Instances with different values for the same NID should not compare
1130 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001131 assert_not_equal(x509_name(CN="foo"),
1132 x509_name(CN="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001133
1134 # Instances with different NIDs should not compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001135 assert_not_equal(x509_name(CN="foo"),
1136 x509_name(OU="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001137
Alex Chan9e2a9932017-01-25 14:29:19 +00001138 assert_not_equal(x509_name(), object())
Alex Gaynor7778e792016-07-03 23:38:48 -04001139
Alex Chan9e2a9932017-01-25 14:29:19 +00001140 def _inequality(a, b, assert_true, assert_false):
1141 assert_true(a < b)
1142 assert_true(a <= b)
1143 assert_true(b > a)
1144 assert_true(b >= a)
1145 assert_false(a > b)
1146 assert_false(a >= b)
1147 assert_false(b < a)
1148 assert_false(b <= a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001149
Alex Chan9e2a9932017-01-25 14:29:19 +00001150 def assert_less_than(a, b):
1151 _inequality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001152
1153 # An X509Name with a NID with a value which sorts less than the value
1154 # of the same NID on another X509Name compares less than the other
1155 # X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001156 assert_less_than(x509_name(CN="abc"),
1157 x509_name(CN="def"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001158
Alex Chan9e2a9932017-01-25 14:29:19 +00001159 def assert_greater_than(a, b):
1160 _inequality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001161
1162 # An X509Name with a NID with a value which sorts greater than the
1163 # value of the same NID on another X509Name compares greater than the
1164 # other X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001165 assert_greater_than(x509_name(CN="def"),
1166 x509_name(CN="abc"))
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001167
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001168 def test_hash(self):
1169 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001170 `X509Name.hash` returns an integer hash based on the value of the name.
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001171 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001172 a = x509_name(CN="foo")
1173 b = x509_name(CN="foo")
1174 assert a.hash() == b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001175 a.CN = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001176 assert a.hash() != b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001177
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001178 def test_der(self):
1179 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001180 `X509Name.der` returns the DER encoded form of the name.
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001181 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001182 a = x509_name(CN="foo", C="US")
1183 assert (a.der() ==
1184 b'0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
1185 b'1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo')
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001186
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001187 def test_get_components(self):
1188 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001189 `X509Name.get_components` returns a `list` of two-tuples of `str`
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001190 giving the NIDs and associated values which make up the name.
1191 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001192 a = x509_name()
1193 assert a.get_components() == []
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001194 a.CN = "foo"
Alex Chan9e2a9932017-01-25 14:29:19 +00001195 assert a.get_components() == [(b"CN", b"foo")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001196 a.organizationalUnitName = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001197 assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001198
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001199 def test_load_nul_byte_attribute(self):
1200 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001201 An `X509Name` from an `X509` instance loaded from a file can have a
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001202 NUL byte in the value of one of its attributes.
1203 """
1204 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1205 subject = cert.get_subject()
Alex Chan9e2a9932017-01-25 14:29:19 +00001206 assert "null.python.org\x00example.org" == subject.commonName
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001207
Romuald Brunet4183beb2019-01-21 19:38:33 +01001208 def test_load_nul_byte_components(self):
1209 """
1210 An `X509Name` from an `X509` instance loaded from a file can have a
1211 NUL byte in the value of its components
1212 """
1213 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1214 subject = cert.get_subject()
1215 components = subject.get_components()
1216 ccn = [value for name, value in components if name == b'CN']
1217 assert ccn[0] == b'null.python.org\x00example.org'
1218
Alex Chan9e2a9932017-01-25 14:29:19 +00001219 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001220 """
1221 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001222 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001223 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001224 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001225 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001226 with pytest.raises(Error):
1227 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001228
1229
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001230class _PKeyInteractionTestsMixin:
1231 """
1232 Tests which involve another thing and a PKey.
1233 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001234
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001235 def signable(self):
1236 """
Alex Chanfb078d82017-04-20 11:16:15 +01001237 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001238 """
1239 raise NotImplementedError()
1240
Alex Chanb00ede22017-01-30 07:24:40 +00001241 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001242 """
Alex Chanb00ede22017-01-30 07:24:40 +00001243 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001244 """
1245 request = self.signable()
1246 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001247 with pytest.raises(ValueError):
1248 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001249
Alex Chanb00ede22017-01-30 07:24:40 +00001250 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001251 """
Alex Chanb00ede22017-01-30 07:24:40 +00001252 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1253 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001254 """
1255 request = self.signable()
1256 key = PKey()
1257 key.generate_key(TYPE_RSA, 512)
1258 request.set_pubkey(key)
1259 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001260 with pytest.raises(ValueError):
1261 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001262
Alex Chanb00ede22017-01-30 07:24:40 +00001263 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001264 """
Alex Chanb00ede22017-01-30 07:24:40 +00001265 `X509Req.sign` raises `ValueError` when passed a digest name which is
1266 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001267 """
1268 request = self.signable()
1269 key = PKey()
1270 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001271 with pytest.raises(ValueError):
1272 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001273
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001274 def test_sign(self):
1275 """
Alex Chanb00ede22017-01-30 07:24:40 +00001276 `X509Req.sign` succeeds when passed a private key object and a
1277 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001278 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001279 """
1280 request = self.signable()
1281 key = PKey()
1282 key.generate_key(TYPE_RSA, 512)
1283 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001284 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001285 # If the type has a verify method, cover that too.
1286 if getattr(request, 'verify', None) is not None:
1287 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001288 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001289 # Make another key that won't verify.
1290 key = PKey()
1291 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001292 with pytest.raises(Error):
1293 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001294
1295
Alex Chanb00ede22017-01-30 07:24:40 +00001296class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001297 """
Alex Chanb00ede22017-01-30 07:24:40 +00001298 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001299 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001300
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001301 def signable(self):
1302 """
Alex Chanb00ede22017-01-30 07:24:40 +00001303 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001304 """
1305 return X509Req()
1306
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001307 def test_type(self):
1308 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001309 `X509Req` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001310 """
Alex Chanb00ede22017-01-30 07:24:40 +00001311 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 Gaynor01f90a12019-02-07 09:14:48 -05001315 `X509Req` takes no arguments and returns an `X509Req` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001316 """
1317 request = X509Req()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001318 assert isinstance(request, X509Req)
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 Gaynor01f90a12019-02-07 09:14:48 -05001350 assert isinstance(subject, X509Name)
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 Gaynor01f90a12019-02-07 09:14:48 -05001499 `X509` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001500 """
Alex Chanb00ede22017-01-30 07:24:40 +00001501 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001502
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001503 def test_construction(self):
1504 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001505 `X509` takes no arguments and returns an instance of `X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001506 """
1507 certificate = X509()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001508 assert isinstance(certificate, X509)
Alex Chanb00ede22017-01-30 07:24:40 +00001509 assert type(certificate).__name__ == 'X509'
Alex Chanb00ede22017-01-30 07:24:40 +00001510 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001511
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001512 def test_set_version_wrong_args(self):
1513 """
Alex Chanb00ede22017-01-30 07:24:40 +00001514 `X509.set_version` raises `TypeError` if invoked with an argument
1515 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001516 """
1517 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001518 with pytest.raises(TypeError):
1519 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001520
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001521 def test_version(self):
1522 """
Alex Chanb00ede22017-01-30 07:24:40 +00001523 `X509.set_version` sets the certificate version number.
1524 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001525 """
1526 cert = X509()
1527 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001528 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001529
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001530 def test_serial_number(self):
1531 """
Alex Chanb00ede22017-01-30 07:24:40 +00001532 The serial number of an `X509` can be retrieved and
1533 modified with `X509.get_serial_number` and
1534 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001535 """
1536 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001537 with pytest.raises(TypeError):
1538 certificate.set_serial_number("1")
1539 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001540 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001541 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001542 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001543 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001544 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001545 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001546 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001547 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001548
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001549 def _setBoundTest(self, which):
1550 """
Alex Chanb00ede22017-01-30 07:24:40 +00001551 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001552 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1553 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001554 """
1555 certificate = X509()
1556 set = getattr(certificate, 'set_not' + which)
1557 get = getattr(certificate, 'get_not' + which)
1558
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001559 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001560 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001561
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001562 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001563 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001564 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001565 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001566
1567 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001568 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001569 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001570 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001571
1572 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001573 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001574 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001575 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001576
1577 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001578 with pytest.raises(ValueError):
1579 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001580
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001581 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001582 with pytest.raises(TypeError):
1583 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001584 with pytest.raises(TypeError):
1585 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001586 with pytest.raises(TypeError):
1587 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001588
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001589 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001590
1591 def test_set_notBefore(self):
1592 """
Alex Chanb00ede22017-01-30 07:24:40 +00001593 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001594 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1595 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001596 """
1597 self._setBoundTest("Before")
1598
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001599 def test_set_notAfter(self):
1600 """
Alex Chanb00ede22017-01-30 07:24:40 +00001601 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001602 GENERALIZEDTIME and sets the end of the certificate's validity period
1603 to it.
1604 """
1605 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001606
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001607 def test_get_notBefore(self):
1608 """
Alex Chanb00ede22017-01-30 07:24:40 +00001609 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001610 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001611 internally.
1612 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001613 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001614 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001615
Rick Dean38a05c82009-07-18 01:41:30 -05001616 def test_get_notAfter(self):
1617 """
Alex Chanb00ede22017-01-30 07:24:40 +00001618 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001619 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001620 internally.
1621 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001622 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001623 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001624
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001625 def test_gmtime_adj_notBefore_wrong_args(self):
1626 """
Alex Chanb00ede22017-01-30 07:24:40 +00001627 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1628 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001629 """
1630 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001631 with pytest.raises(TypeError):
1632 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001633
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001634 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001635 def test_gmtime_adj_notBefore(self):
1636 """
Alex Chanb00ede22017-01-30 07:24:40 +00001637 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1638 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001639 """
1640 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001641 not_before_min = (
1642 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1643 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001644 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001645 not_before = datetime.strptime(
1646 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1647 )
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001648 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001649 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001650
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001651 def test_gmtime_adj_notAfter_wrong_args(self):
1652 """
Alex Chanb00ede22017-01-30 07:24:40 +00001653 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1654 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001655 """
1656 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001657 with pytest.raises(TypeError):
1658 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001659
Alex Gaynor642de6f2017-07-24 00:57:38 -04001660 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001661 def test_gmtime_adj_notAfter(self):
1662 """
Alex Chanb00ede22017-01-30 07:24:40 +00001663 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001664 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001665 """
1666 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001667 not_after_min = (
1668 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1669 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001670 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001671 not_after = datetime.strptime(
1672 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1673 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001674 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001675 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001676
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001677 def test_has_expired(self):
1678 """
Alex Chanb00ede22017-01-30 07:24:40 +00001679 `X509.has_expired` returns `True` if the certificate's not-after time
1680 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001681 """
1682 cert = X509()
1683 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001684 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001685
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001686 def test_has_not_expired(self):
1687 """
Alex Chanb00ede22017-01-30 07:24:40 +00001688 `X509.has_expired` returns `False` if the certificate's not-after time
1689 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001690 """
1691 cert = X509()
1692 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001693 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001694
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001695 def test_root_has_not_expired(self):
1696 """
Alex Chanb00ede22017-01-30 07:24:40 +00001697 `X509.has_expired` returns `False` if the certificate's not-after time
1698 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001699 """
1700 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001701 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001702
Rick Dean38a05c82009-07-18 01:41:30 -05001703 def test_digest(self):
1704 """
Alex Chanb00ede22017-01-30 07:24:40 +00001705 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001706 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001707 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001708 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001709 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001710 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1711 # actually matters to the assertion (ie, another arbitrary, good
1712 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001713 # Digest verified with the command:
1714 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001715 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001716 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001717
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001718 def _extcert(self, pkey, extensions):
1719 cert = X509()
1720 cert.set_pubkey(pkey)
1721 cert.get_subject().commonName = "Unit Tests"
1722 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001723 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001724 cert.set_notBefore(when)
1725 cert.set_notAfter(when)
1726
1727 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001728 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001729 return load_certificate(
1730 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1731
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001732 def test_extension_count(self):
1733 """
Alex Chanb00ede22017-01-30 07:24:40 +00001734 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001735 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001736 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001737 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001738 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1739 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001740 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001741 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001742
1743 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001744 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001745 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001746
1747 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001748 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001749 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001750
1751 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001752 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001753 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001754
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001755 def test_get_extension(self):
1756 """
Alex Chanb00ede22017-01-30 07:24:40 +00001757 `X509.get_extension` takes an integer and returns an
1758 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001759 """
1760 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001761 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1762 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001763 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001764 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001765
1766 cert = self._extcert(pkey, [ca, key, subjectAltName])
1767
1768 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001769 assert isinstance(ext, X509Extension)
1770 assert ext.get_critical()
1771 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001772
1773 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001774 assert isinstance(ext, X509Extension)
1775 assert ext.get_critical()
1776 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001777
1778 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001779 assert isinstance(ext, X509Extension)
1780 assert not ext.get_critical()
1781 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001782
Alex Chanb00ede22017-01-30 07:24:40 +00001783 with pytest.raises(IndexError):
1784 cert.get_extension(-1)
1785 with pytest.raises(IndexError):
1786 cert.get_extension(4)
1787 with pytest.raises(TypeError):
1788 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001789
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001790 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001791 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001792 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001793 bytes and this value is reflected in the string representation of the
1794 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001795 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001796 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001797
1798 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001799 assert ext.get_short_name() == b'subjectAltName'
1800 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001801 b"DNS:altnull.python.org\x00example.com, "
1802 b"email:null@python.org\x00user@example.org, "
1803 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001804 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 -04001805 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001806
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001807 def test_invalid_digest_algorithm(self):
1808 """
Alex Chanb00ede22017-01-30 07:24:40 +00001809 `X509.digest` raises `ValueError` if called with an unrecognized hash
1810 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001811 """
1812 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001813 with pytest.raises(ValueError):
1814 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001815
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001816 def test_get_subject(self):
1817 """
Alex Chanb00ede22017-01-30 07:24:40 +00001818 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001819 """
1820 cert = load_certificate(FILETYPE_PEM, self.pemData)
1821 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001822 assert isinstance(subj, X509Name)
1823 assert (
1824 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001825 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1826 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001827
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001828 def test_set_subject_wrong_args(self):
1829 """
Alex Chanb00ede22017-01-30 07:24:40 +00001830 `X509.set_subject` raises a `TypeError` if called with an argument not
1831 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001832 """
1833 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001834 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001835 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001836
1837 def test_set_subject(self):
1838 """
Alex Chanb00ede22017-01-30 07:24:40 +00001839 `X509.set_subject` changes the subject of the certificate to the one
1840 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001841 """
1842 cert = X509()
1843 name = cert.get_subject()
1844 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001845 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001846 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001847 assert (
1848 cert.get_subject().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001849 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001850
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001851 def test_get_issuer(self):
1852 """
Alex Chanb00ede22017-01-30 07:24:40 +00001853 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001854 """
1855 cert = load_certificate(FILETYPE_PEM, self.pemData)
1856 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001857 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001858 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001859 assert (
1860 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001861 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1862 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001863
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001864 def test_set_issuer_wrong_args(self):
1865 """
Alex Chanb00ede22017-01-30 07:24:40 +00001866 `X509.set_issuer` raises a `TypeError` if called with an argument not
1867 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001868 """
1869 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001870 with pytest.raises(TypeError):
1871 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001872
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001873 def test_set_issuer(self):
1874 """
Alex Chanb00ede22017-01-30 07:24:40 +00001875 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001876 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001877 """
1878 cert = X509()
1879 name = cert.get_issuer()
1880 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001881 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001882 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001883 assert (
1884 cert.get_issuer().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001885 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001886
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001887 def test_get_pubkey_uninitialized(self):
1888 """
Alex Chanb00ede22017-01-30 07:24:40 +00001889 When called on a certificate with no public key, `X509.get_pubkey`
1890 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001891 """
1892 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001893 with pytest.raises(Error):
1894 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001895
Alex Gaynor7778e792016-07-03 23:38:48 -04001896 def test_set_pubkey_wrong_type(self):
1897 """
Alex Chanb00ede22017-01-30 07:24:40 +00001898 `X509.set_pubkey` raises `TypeError` when given an object of the
1899 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001900 """
1901 cert = X509()
1902 with pytest.raises(TypeError):
1903 cert.set_pubkey(object())
1904
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001905 def test_subject_name_hash(self):
1906 """
Alex Chanb00ede22017-01-30 07:24:40 +00001907 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001908 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001909 """
1910 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor4cb05202019-02-02 11:06:41 -05001911 # SHA1
1912 assert cert.subject_name_hash() == 3278919224
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001913
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001914 def test_get_signature_algorithm(self):
1915 """
Alex Chanb00ede22017-01-30 07:24:40 +00001916 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001917 the algorithm used to sign the certificate.
1918 """
1919 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001920 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001921
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001922 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001923 """
Alex Chanb00ede22017-01-30 07:24:40 +00001924 `X509.get_signature_algorithm` raises `ValueError` if the signature
1925 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001926 """
1927 # This certificate has been modified to indicate a bogus OID in the
1928 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001929 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001930-----BEGIN CERTIFICATE-----
1931MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1932EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1933cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1934MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1935EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1936CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1937AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1938+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1939hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1940BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1941FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1942dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1943aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1944MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1945jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1946PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1947tgI5
1948-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001949"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001950 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001951 with pytest.raises(ValueError):
1952 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001953
Alex Gaynor37726112016-07-04 09:51:32 -04001954 def test_sign_bad_pubkey_type(self):
1955 """
Alex Chanb00ede22017-01-30 07:24:40 +00001956 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001957 """
1958 cert = X509()
1959 with pytest.raises(TypeError):
1960 cert.sign(object(), b"sha256")
1961
Alex Gaynor9939ba12017-06-25 16:28:24 -04001962 def test_convert_from_cryptography(self):
1963 crypto_cert = x509.load_pem_x509_certificate(
1964 intermediate_cert_pem, backend
1965 )
1966 cert = X509.from_cryptography(crypto_cert)
1967
1968 assert isinstance(cert, X509)
1969 assert cert.get_version() == crypto_cert.version.value
1970
1971 def test_convert_from_cryptography_unsupported_type(self):
1972 with pytest.raises(TypeError):
1973 X509.from_cryptography(object())
1974
1975 def test_convert_to_cryptography_key(self):
1976 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1977 crypto_cert = cert.to_cryptography()
1978
1979 assert isinstance(crypto_cert, x509.Certificate)
1980 assert crypto_cert.version.value == cert.get_version()
1981
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001982
Alex Chan9e2a9932017-01-25 14:29:19 +00001983class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001984 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001985 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001986 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001987
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001988 def test_type(self):
1989 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001990 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001991 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001992 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001993
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001994 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001995 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001996 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001997 """
1998 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001999 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002000 store.add_cert(cert)
2001
Alex Chanfb078d82017-04-20 11:16:15 +01002002 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2003 def test_add_cert_wrong_args(self, cert):
2004 """
2005 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2006 as its first argument.
2007 """
2008 store = X509Store()
2009 with pytest.raises(TypeError):
2010 store.add_cert(cert)
2011
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002012 def test_add_cert_accepts_duplicate(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002013 """
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002014 `X509Store.add_cert` doesn't raise `OpenSSL.crypto.Error` if an attempt
2015 is made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002016 """
2017 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2018 store = X509Store()
2019 store.add_cert(cert)
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002020 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002021
2022
Alex Chanb00ede22017-01-30 07:24:40 +00002023class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002024 """
Alex Chanb00ede22017-01-30 07:24:40 +00002025 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002026 """
2027 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2028
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002029 def test_type(self):
2030 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002031 `PKCS12` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002032 """
Alex Chanb00ede22017-01-30 07:24:40 +00002033 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002034
Rick Deanf94096c2009-07-18 14:23:06 -05002035 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002036 """
Alex Chanb00ede22017-01-30 07:24:40 +00002037 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2038 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002039 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002040 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002041 assert None is p12.get_certificate()
2042 assert None is p12.get_privatekey()
2043 assert None is p12.get_ca_certificates()
2044 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002045
2046 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002047 """
Alex Chanb00ede22017-01-30 07:24:40 +00002048 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2049 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2050 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002051 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002052 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002053 for bad_arg in [3, PKey(), X509]:
2054 with pytest.raises(TypeError):
2055 p12.set_certificate(bad_arg)
2056 for bad_arg in [3, 'legbone', X509()]:
2057 with pytest.raises(TypeError):
2058 p12.set_privatekey(bad_arg)
2059 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2060 with pytest.raises(TypeError):
2061 p12.set_ca_certificates(bad_arg)
2062 for bad_arg in [6, ('foo', 'bar')]:
2063 with pytest.raises(TypeError):
2064 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002065
2066 def test_key_only(self):
2067 """
Alex Chanb00ede22017-01-30 07:24:40 +00002068 A `PKCS12` with only a private key can be exported using
2069 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002070 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002071 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002072 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002073 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002074 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002075 assert None is p12.get_certificate()
2076 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002077 try:
2078 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2079 except Error:
2080 # Some versions of OpenSSL will throw an exception
2081 # for this nearly useless PKCS12 we tried to generate:
2082 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2083 return
Rick Dean623ee362009-07-17 12:22:16 -05002084 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002085 assert None is p12.get_ca_certificates()
2086 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002087
2088 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2089 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002090 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002091
2092 def test_cert_only(self):
2093 """
Alex Chanb00ede22017-01-30 07:24:40 +00002094 A `PKCS12` with only a certificate can be exported using
2095 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002096 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002097 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002098 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002099 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002100 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002101 assert cert == p12.get_certificate()
2102 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002103 try:
2104 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2105 except Error:
2106 # Some versions of OpenSSL will throw an exception
2107 # for this nearly useless PKCS12 we tried to generate:
2108 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2109 return
Rick Dean623ee362009-07-17 12:22:16 -05002110 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002111 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002112
2113 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002114 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002115
2116 # Oh ho. It puts the certificate into the ca certificates list, in
2117 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2118 # that to check to see if it reconstructed the certificate we expected
2119 # it to. At some point, hopefully this will change so that
2120 # p12.get_certificate() is actually what returns the loaded
2121 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002122 assert (
2123 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002124 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002125
Alex Gaynor31287502015-09-05 16:11:27 -04002126 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2127 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002128 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002129 Generate a PKCS12 object with components from PEM. Verify that the set
2130 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002131 """
Rick Deanf94096c2009-07-18 14:23:06 -05002132 p12 = PKCS12()
2133 if cert_pem:
2134 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002135 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002136 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002137 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002138 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002139 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002140 ret = p12.set_ca_certificates(
2141 (load_certificate(FILETYPE_PEM, ca_pem),)
2142 )
Alex Chanb00ede22017-01-30 07:24:40 +00002143 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002144 if friendly_name:
2145 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002146 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002147 return p12
2148
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002149 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002150 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002151 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002152 Use openssl program to confirm three components are recoverable from a
2153 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002154 """
2155 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002156 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002157 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2158 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002159 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002160 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002161 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002162 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2163 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002164 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002165 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002166 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002167 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2168 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002169 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002170
Stephen Holsapple38482622014-04-05 20:29:34 -07002171 def verify_pkcs12_container(self, p12):
2172 """
2173 Verify that the PKCS#12 container contains the correct client
2174 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002175
2176 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002177 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002178 """
2179 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2180 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002181 assert (
2182 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002183 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002184
Rick Deanf94096c2009-07-18 14:23:06 -05002185 def test_load_pkcs12(self):
2186 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002187 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002188 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002189 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002190 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002191 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002192 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002193 pem,
2194 b"pkcs12",
2195 b"-export",
2196 b"-clcerts",
2197 b"-passout",
2198 b"pass:" + passwd
2199 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002200 p12 = load_pkcs12(p12_str, passphrase=passwd)
2201 self.verify_pkcs12_container(p12)
2202
Abraham Martinc5484ba2015-03-25 15:33:05 +00002203 def test_load_pkcs12_text_passphrase(self):
2204 """
2205 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002206 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002207 Using text as passphrase instead of bytes. DeprecationWarning expected.
2208 """
2209 pem = client_key_pem + client_cert_pem
2210 passwd = b"whatever"
2211 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2212 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002213 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002214 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002215 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002216 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002217 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002218 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002219 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002220
Abraham Martinc5484ba2015-03-25 15:33:05 +00002221 self.verify_pkcs12_container(p12)
2222
Stephen Holsapple38482622014-04-05 20:29:34 -07002223 def test_load_pkcs12_no_passphrase(self):
2224 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002225 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002226 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002227 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002228 """
2229 pem = client_key_pem + client_cert_pem
2230 p12_str = _runopenssl(
2231 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2232 p12 = load_pkcs12(p12_str)
2233 self.verify_pkcs12_container(p12)
2234
Stephen Holsapple38482622014-04-05 20:29:34 -07002235 def _dump_and_load(self, dump_passphrase, load_passphrase):
2236 """
2237 A helper method to dump and load a PKCS12 object.
2238 """
2239 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2240 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2241 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2242
Stephen Holsapple38482622014-04-05 20:29:34 -07002243 def test_load_pkcs12_null_passphrase_load_empty(self):
2244 """
2245 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002246 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002247 extracted and examined.
2248 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002249 self.verify_pkcs12_container(
2250 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002251
Stephen Holsapple38482622014-04-05 20:29:34 -07002252 def test_load_pkcs12_null_passphrase_load_null(self):
2253 """
2254 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002255 null 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=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002260
Stephen Holsapple38482622014-04-05 20:29:34 -07002261 def test_load_pkcs12_empty_passphrase_load_empty(self):
2262 """
2263 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002264 empty 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=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002269
Stephen Holsapple38482622014-04-05 20:29:34 -07002270 def test_load_pkcs12_empty_passphrase_load_null(self):
2271 """
2272 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002273 null 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=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002278
Rick Deanee568302009-07-24 09:56:29 -05002279 def test_load_pkcs12_garbage(self):
2280 """
Alex Chanb00ede22017-01-30 07:24:40 +00002281 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002282 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002283 """
2284 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002285 with pytest.raises(Error) as err:
2286 load_pkcs12(b'fruit loops', passwd)
2287 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2288 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002289
Rick Deanf94096c2009-07-18 14:23:06 -05002290 def test_replace(self):
2291 """
Alex Chanb00ede22017-01-30 07:24:40 +00002292 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2293 cluster. `PKCS12.set_privatekey` replaces the private key.
2294 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002295 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002296 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2297 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2298 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002299 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002300 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002301 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002302 assert 1 == len(p12.get_ca_certificates())
2303 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002304 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002305 assert 2 == len(p12.get_ca_certificates())
2306 assert client_cert == p12.get_ca_certificates()[0]
2307 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002308
Rick Deanf94096c2009-07-18 14:23:06 -05002309 def test_friendly_name(self):
2310 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002311 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002312 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2313 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002314 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002315 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002316 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002317 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002318 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002319 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002320 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002321 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002322 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002323 # We would use the openssl program to confirm the friendly
2324 # name, but it is not possible. The pkcs12 command
2325 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002326 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002327 self.check_recovery(
2328 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2329 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002330
Rick Deanf94096c2009-07-18 14:23:06 -05002331 def test_various_empty_passphrases(self):
2332 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002333 Test that missing, None, and '' passphrases are identical for PKCS12
2334 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002335 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002336 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002337 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002338 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2339 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2340 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2341 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2342 self.check_recovery(
2343 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2344 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002345
Rick Deanf94096c2009-07-18 14:23:06 -05002346 def test_removing_ca_cert(self):
2347 """
Alex Chanb00ede22017-01-30 07:24:40 +00002348 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2349 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002350 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002351 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2352 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002353 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002354
Rick Deanf94096c2009-07-18 14:23:06 -05002355 def test_export_without_mac(self):
2356 """
Alex Chanb00ede22017-01-30 07:24:40 +00002357 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002358 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002359 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002360 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002361 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002362 self.check_recovery(
2363 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002364 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002365
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002366 def test_load_without_mac(self):
2367 """
2368 Loading a PKCS12 without a MAC does something other than crash.
2369 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002370 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002371 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2372 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002373 try:
2374 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2375 # The person who generated this PCKS12 should be flogged,
2376 # or better yet we should have a means to determine
2377 # whether a PCKS12 had a MAC that was verified.
2378 # Anyway, libopenssl chooses to allow it, so the
2379 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002380 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002381 except Error:
2382 # Failing here with an exception is preferred as some openssl
2383 # versions do.
2384 pass
Rick Dean623ee362009-07-17 12:22:16 -05002385
Rick Dean25bcc1f2009-07-20 11:53:13 -05002386 def test_zero_len_list_for_ca(self):
2387 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002388 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002389 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002390 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002391 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002392 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002393 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002394 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2395 self.check_recovery(
2396 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2397 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002398
Rick Deanf94096c2009-07-18 14:23:06 -05002399 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002400 """
Alex Chanb00ede22017-01-30 07:24:40 +00002401 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002402 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002403 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002404 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002405 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002406 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002407
Abraham Martinc5484ba2015-03-25 15:33:05 +00002408 def test_export_without_bytes(self):
2409 """
Alex Chanb00ede22017-01-30 07:24:40 +00002410 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002411 """
2412 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2413
Alex Chanb00ede22017-01-30 07:24:40 +00002414 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002415 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002416 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002417 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002418 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002419 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002420 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002421 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002422 dumped_p12,
2423 key=server_key_pem,
2424 cert=server_cert_pem,
2425 passwd=b"randomtext"
2426 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002427
Rick Deanf94096c2009-07-18 14:23:06 -05002428 def test_key_cert_mismatch(self):
2429 """
Alex Chanb00ede22017-01-30 07:24:40 +00002430 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002431 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002432 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002433 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002434 with pytest.raises(Error):
2435 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002436
2437
Rick Dean4c9ad612009-07-17 15:05:22 -05002438def _runopenssl(pem, *args):
2439 """
2440 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002441 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002442 """
Alex Gaynor6cbc69a2017-07-25 09:07:04 -04002443 proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002444 proc.stdin.write(pem)
2445 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002446 output = proc.stdout.read()
2447 proc.stdout.close()
2448 proc.wait()
2449 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002450
2451
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002452class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002453 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002454 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002455 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002456 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002457 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002458 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002459 """
2460 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002461
2462 assert True is key._only_public
2463 assert 2048 == key.bits()
2464 assert TYPE_RSA == key.type()
2465
2466 def test_invalid_type(self):
2467 """
2468 load_publickey doesn't support FILETYPE_TEXT.
2469 """
2470 with pytest.raises(ValueError):
2471 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2472
2473 def test_invalid_key_format(self):
2474 """
2475 load_publickey explodes on incorrect keys.
2476 """
2477 with pytest.raises(Error):
2478 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2479
2480 def test_tolerates_unicode_strings(self):
2481 """
2482 load_publickey works with text strings, not just bytes.
2483 """
2484 serialized = cleartextPublicKeyPEM.decode('ascii')
2485 key = load_publickey(FILETYPE_PEM, serialized)
2486 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2487
2488 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002489
2490
Alex Chanb00ede22017-01-30 07:24:40 +00002491class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002492 """
Alex Chanb00ede22017-01-30 07:24:40 +00002493 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002494 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002495
2496 def test_load_privatekey_invalid_format(self):
2497 """
Alex Chanb00ede22017-01-30 07:24:40 +00002498 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002499 """
Alex Chanb00ede22017-01-30 07:24:40 +00002500 with pytest.raises(ValueError):
2501 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002502
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002503 def test_load_privatekey_invalid_passphrase_type(self):
2504 """
Alex Chanb00ede22017-01-30 07:24:40 +00002505 `load_privatekey` raises `TypeError` if passed a passphrase that is
2506 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002507 """
Alex Chanb00ede22017-01-30 07:24:40 +00002508 with pytest.raises(TypeError):
2509 load_privatekey(
2510 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002511
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002512 def test_load_privatekey_wrongPassphrase(self):
2513 """
Alex Chanb00ede22017-01-30 07:24:40 +00002514 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2515 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002516 """
Alex Chanb00ede22017-01-30 07:24:40 +00002517 with pytest.raises(Error) as err:
2518 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2519 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002520
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002521 def test_load_privatekey_passphraseWrongType(self):
2522 """
Alex Chanb00ede22017-01-30 07:24:40 +00002523 `load_privatekey` raises `ValueError` when it is passeda passphrase
2524 with a private key encoded in a format, that doesn't support
2525 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002526 """
2527 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2528 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002529 with pytest.raises(ValueError):
2530 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002531
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002532 def test_load_privatekey_passphrase(self):
2533 """
Alex Chanb00ede22017-01-30 07:24:40 +00002534 `load_privatekey` can create a `PKey` object from an encrypted PEM
2535 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002536 """
2537 key = load_privatekey(
2538 FILETYPE_PEM, encryptedPrivateKeyPEM,
2539 encryptedPrivateKeyPEMPassphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002540 assert isinstance(key, PKey)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002541
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002542 def test_load_privatekey_passphrase_exception(self):
2543 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002544 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002545 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002546 """
2547 def cb(ignored):
2548 raise ArithmeticError
2549
Alex Gaynor791212d2015-09-05 15:46:08 -04002550 with pytest.raises(ArithmeticError):
2551 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002552
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002553 def test_load_privatekey_wrongPassphraseCallback(self):
2554 """
Alex Chanb00ede22017-01-30 07:24:40 +00002555 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002556 is passed an encrypted PEM and a passphrase callback which returns an
2557 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002558 """
2559 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002560
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002561 def cb(*a):
2562 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002563 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002564 with pytest.raises(Error) as err:
2565 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2566 assert called
2567 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002568
2569 def test_load_privatekey_passphraseCallback(self):
2570 """
Alex Chanb00ede22017-01-30 07:24:40 +00002571 `load_privatekey` can create a `PKey` object from an encrypted PEM
2572 string if given a passphrase callback which returns the correct
2573 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002574 """
2575 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002576
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002577 def cb(writing):
2578 called.append(writing)
2579 return encryptedPrivateKeyPEMPassphrase
2580 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002581 assert isinstance(key, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002582 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002583
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002584 def test_load_privatekey_passphrase_wrong_return_type(self):
2585 """
Alex Chanb00ede22017-01-30 07:24:40 +00002586 `load_privatekey` raises `ValueError` if the passphrase callback
2587 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002588 """
Alex Chanb00ede22017-01-30 07:24:40 +00002589 with pytest.raises(ValueError):
2590 load_privatekey(
2591 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002592
Alex Chanfb078d82017-04-20 11:16:15 +01002593 def test_dump_privatekey_wrong_args(self):
2594 """
2595 `dump_privatekey` raises `TypeError` if called with a `cipher`
2596 argument but no `passphrase` argument.
2597 """
2598 key = PKey()
2599 key.generate_key(TYPE_RSA, 512)
2600 with pytest.raises(TypeError):
2601 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2602
Paul Kehrercded9932017-06-29 18:43:42 -05002603 def test_dump_privatekey_not_rsa_key(self):
2604 """
2605 `dump_privatekey` raises `TypeError` if called with a key that is
2606 not RSA.
2607 """
2608 key = PKey()
2609 key.generate_key(TYPE_DSA, 512)
2610 with pytest.raises(TypeError):
2611 dump_privatekey(FILETYPE_TEXT, key)
2612
2613 def test_dump_privatekey_invalid_pkey(self):
2614 with pytest.raises(TypeError):
2615 dump_privatekey(FILETYPE_TEXT, object())
2616
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002617 def test_dump_privatekey_unknown_cipher(self):
2618 """
Alex Chanb00ede22017-01-30 07:24:40 +00002619 `dump_privatekey` raises `ValueError` if called with an unrecognized
2620 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002621 """
2622 key = PKey()
2623 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002624 with pytest.raises(ValueError):
2625 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002626
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002627 def test_dump_privatekey_invalid_passphrase_type(self):
2628 """
Alex Chanb00ede22017-01-30 07:24:40 +00002629 `dump_privatekey` raises `TypeError` if called with a passphrase which
2630 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002631 """
2632 key = PKey()
2633 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002634 with pytest.raises(TypeError):
2635 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002636
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002637 def test_dump_privatekey_invalid_filetype(self):
2638 """
Alex Chanb00ede22017-01-30 07:24:40 +00002639 `dump_privatekey` raises `ValueError` if called with an unrecognized
2640 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002641 """
2642 key = PKey()
2643 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002644 with pytest.raises(ValueError):
2645 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002646
Alex Chanb00ede22017-01-30 07:24:40 +00002647 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002648 """
Alex Chanb00ede22017-01-30 07:24:40 +00002649 `crypto.load_privatekey` should raise an error when the passphrase
2650 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002651 """
2652 def cb(ignored):
2653 return "a" * 1025
2654
Alex Gaynor791212d2015-09-05 15:46:08 -04002655 with pytest.raises(ValueError):
2656 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002657
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002658 def test_dump_privatekey_passphrase(self):
2659 """
Alex Chanb00ede22017-01-30 07:24:40 +00002660 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002661 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002662 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002663 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002664 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002665 assert isinstance(pem, binary_type)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002666 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002667 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002668 assert loadedKey.type() == key.type()
2669 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002670
Alex Chanb00ede22017-01-30 07:24:40 +00002671 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002672 """
Alex Chanb00ede22017-01-30 07:24:40 +00002673 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2674 with a private key encoded in a format, that doesn't support
2675 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002676 """
2677 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002678 with pytest.raises(ValueError):
2679 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002680
Rick Dean5b7b6372009-04-01 11:34:06 -05002681 def test_dump_certificate(self):
2682 """
Alex Chanb00ede22017-01-30 07:24:40 +00002683 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002684 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002685 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002686 cert = load_certificate(FILETYPE_PEM, pemData)
2687 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002688 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002689 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002690 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002691 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002692 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2693 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002694 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002695 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002696 good_text = _runopenssl(
2697 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002698 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002699
Alex Gaynor37726112016-07-04 09:51:32 -04002700 def test_dump_certificate_bad_type(self):
2701 """
Alex Chanb00ede22017-01-30 07:24:40 +00002702 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002703 a bad type.
2704 """
2705 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2706 with pytest.raises(ValueError):
2707 dump_certificate(object(), cert)
2708
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002709 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002710 """
Alex Chanb00ede22017-01-30 07:24:40 +00002711 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002712 """
2713 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002714 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002715 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002716 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002717
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002718 def test_dump_privatekey_asn1(self):
2719 """
Alex Chanb00ede22017-01-30 07:24:40 +00002720 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002721 """
2722 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2723 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2724
Rick Dean5b7b6372009-04-01 11:34:06 -05002725 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002726 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002727 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002728 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002729 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2730 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002731 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002732
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002733 def test_dump_privatekey_text(self):
2734 """
Alex Chanb00ede22017-01-30 07:24:40 +00002735 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002736 """
2737 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2738 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2739
Rick Dean5b7b6372009-04-01 11:34:06 -05002740 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002741 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002742 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002743
Cory Benfield6492f7c2015-10-27 16:57:58 +09002744 def test_dump_publickey_pem(self):
2745 """
Cory Benfield11c10192015-10-27 17:23:03 +09002746 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002747 """
2748 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2749 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002750 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002751
2752 def test_dump_publickey_asn1(self):
2753 """
Cory Benfield11c10192015-10-27 17:23:03 +09002754 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002755 """
2756 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2757 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2758 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2759 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002760 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002761
Cory Benfielde02c7d82015-10-27 17:34:49 +09002762 def test_dump_publickey_invalid_type(self):
2763 """
2764 dump_publickey doesn't support FILETYPE_TEXT.
2765 """
2766 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2767
2768 with pytest.raises(ValueError):
2769 dump_publickey(FILETYPE_TEXT, key)
2770
Rick Dean5b7b6372009-04-01 11:34:06 -05002771 def test_dump_certificate_request(self):
2772 """
Alex Chanb00ede22017-01-30 07:24:40 +00002773 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002774 """
Alex Gaynor31287502015-09-05 16:11:27 -04002775 req = load_certificate_request(
2776 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002777 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002778 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002779 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002780 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002781 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002782 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2783 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002784 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002785 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002786 good_text = _runopenssl(
2787 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002788 assert dumped_text == good_text
2789 with pytest.raises(ValueError):
2790 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002791
Alex Chanb00ede22017-01-30 07:24:40 +00002792 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002793 """
Alex Chanb00ede22017-01-30 07:24:40 +00002794 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002795 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002796 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002797 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002798 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002799
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002800 def cb(writing):
2801 called.append(writing)
2802 return passphrase
2803 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002804 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002805 assert isinstance(pem, binary_type)
2806 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002807 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002808 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002809 assert loadedKey.type() == key.type()
2810 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002811
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002812 def test_dump_privatekey_passphrase_exception(self):
2813 """
Alex Chanb00ede22017-01-30 07:24:40 +00002814 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002815 by the passphrase callback.
2816 """
2817 def cb(ignored):
2818 raise ArithmeticError
2819
2820 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002821 with pytest.raises(ArithmeticError):
2822 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002823
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002824 def test_dump_privatekey_passphraseCallbackLength(self):
2825 """
Alex Chanb00ede22017-01-30 07:24:40 +00002826 `crypto.dump_privatekey` should raise an error when the passphrase
2827 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002828 """
2829 def cb(ignored):
2830 return "a" * 1025
2831
2832 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002833 with pytest.raises(ValueError):
2834 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002835
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002836 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002837 """
Alex Chanb00ede22017-01-30 07:24:40 +00002838 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2839 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002840 """
2841 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002842 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002843
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002844 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002845 """
Alex Chanb00ede22017-01-30 07:24:40 +00002846 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2847 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002848 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002849 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002850 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002851
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002852 def test_load_pkcs7_data_invalid(self):
2853 """
Alex Chanb00ede22017-01-30 07:24:40 +00002854 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002855 """
Alex Chanb00ede22017-01-30 07:24:40 +00002856 with pytest.raises(Error):
2857 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002858
Alex Gaynor09a386e2016-07-03 09:32:44 -04002859 def test_load_pkcs7_type_invalid(self):
2860 """
Alex Chanb00ede22017-01-30 07:24:40 +00002861 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002862 """
2863 with pytest.raises(ValueError):
2864 load_pkcs7_data(object(), b"foo")
2865
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002866
Alex Chan9e2a9932017-01-25 14:29:19 +00002867class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002868 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002869 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002870 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002871
Alex Chan9e2a9932017-01-25 14:29:19 +00002872 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002873 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002874 If the file type passed to `load_certificate_request` is neither
2875 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002876 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002877 with pytest.raises(ValueError):
2878 load_certificate_request(object(), b"")
2879 with pytest.raises(ValueError):
2880 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002881
Alex Gaynor37726112016-07-04 09:51:32 -04002882 def test_bad_certificate(self):
2883 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002884 If the bytes passed to `load_certificate` are not a valid certificate,
2885 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002886 """
2887 with pytest.raises(Error):
2888 load_certificate(FILETYPE_ASN1, b"lol")
2889
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002890
Alex Chanb00ede22017-01-30 07:24:40 +00002891class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002892 """
Alex Chanb00ede22017-01-30 07:24:40 +00002893 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002894 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002895
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002896 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002897 """
Alex Chanb00ede22017-01-30 07:24:40 +00002898 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2899 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002900 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002901 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002902 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002903
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002904 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002905 """
Alex Chanb00ede22017-01-30 07:24:40 +00002906 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2907 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002908 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002909 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002910 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002911
Alex Chanb00ede22017-01-30 07:24:40 +00002912 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002913 """
Alex Chanb00ede22017-01-30 07:24:40 +00002914 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002915 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002916 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002917 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002918 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002919
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002920 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002921 """
Alex Chanb00ede22017-01-30 07:24:40 +00002922 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2923 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002924 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002925 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002926 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002927
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002928 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002929 """
Alex Chanb00ede22017-01-30 07:24:40 +00002930 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002931 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002932 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002933 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002934 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002935
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002936 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002937 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002938 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002939 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002940 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002941 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002942 with pytest.raises(AttributeError):
2943 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002944
2945
Alex Chanb00ede22017-01-30 07:24:40 +00002946class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002947 """
Alex Chanb00ede22017-01-30 07:24:40 +00002948 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002949 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002950
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002951 def signable(self):
2952 """
Alex Chanb00ede22017-01-30 07:24:40 +00002953 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002954 """
2955 return NetscapeSPKI()
2956
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002957 def test_type(self):
2958 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002959 `NetscapeSPKI` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002960 """
Alex Chanb00ede22017-01-30 07:24:40 +00002961 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002962
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002963 def test_construction(self):
2964 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002965 `NetscapeSPKI` returns an instance of `NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002966 """
2967 nspki = NetscapeSPKI()
Alex Gaynor01f90a12019-02-07 09:14:48 -05002968 assert isinstance(nspki, NetscapeSPKI)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002969
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002970 def test_invalid_attribute(self):
2971 """
Alex Chanb00ede22017-01-30 07:24:40 +00002972 Accessing a non-existent attribute of a `NetscapeSPKI` instance
2973 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002974 """
2975 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002976 with pytest.raises(AttributeError):
2977 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002978
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002979 def test_b64_encode(self):
2980 """
Alex Chanb00ede22017-01-30 07:24:40 +00002981 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002982 """
2983 nspki = NetscapeSPKI()
2984 blob = nspki.b64_encode()
Alex Chanb00ede22017-01-30 07:24:40 +00002985 assert isinstance(blob, binary_type)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002986
2987
Paul Kehrer2c605ba2016-03-11 11:17:26 -04002988class TestRevoked(object):
2989 """
Alex Chandeec9342016-12-19 22:00:38 +00002990 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04002991 """
2992 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
2993 """
2994 The get_reason method on the Revoked class checks to see if the
2995 extension is NID_crl_reason and should skip it otherwise. This test
2996 loads a CRL with extensions it should ignore.
2997 """
2998 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
2999 revoked = crl.get_revoked()
3000 reason = revoked[1].get_reason()
3001 assert reason == b'Unspecified'
3002
3003 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3004 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3005 revoked = crl.get_revoked()
3006 revoked[1].set_reason(None)
3007 reason = revoked[1].get_reason()
3008 assert reason is None
3009
Rick Dean536ba022009-07-24 23:57:27 -05003010 def test_construction(self):
3011 """
Alex Chandeec9342016-12-19 22:00:38 +00003012 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3013 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003014 """
3015 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003016 assert isinstance(revoked, Revoked)
3017 assert type(revoked) == Revoked
3018 assert revoked.get_serial() == b'00'
3019 assert revoked.get_rev_date() is None
3020 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003021
Rick Dean536ba022009-07-24 23:57:27 -05003022 def test_serial(self):
3023 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003024 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003025 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003026 """
3027 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003028 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003029 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003030 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003031 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003032
Alex Gaynore7f51982016-09-11 11:48:14 -04003033 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003034 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003035 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003036
Alex Chandeec9342016-12-19 22:00:38 +00003037 with pytest.raises(ValueError):
3038 revoked.set_serial(b'pqrst')
3039 with pytest.raises(TypeError):
3040 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003041
Rick Dean536ba022009-07-24 23:57:27 -05003042 def test_date(self):
3043 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003044 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003045 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003046 """
3047 revoked = Revoked()
3048 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003049 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003050
Alex Gaynore7f51982016-09-11 11:48:14 -04003051 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003052 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003053 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003054 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003055 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003056
Rick Dean6385faf2009-07-26 00:07:47 -05003057 def test_reason(self):
3058 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003059 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003060 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3061 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003062 """
3063 revoked = Revoked()
3064 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003065 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003066 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003067 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003068 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003069 assert (
3070 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003071 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003072 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003073
3074 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003075 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003076
Alex Chanfb078d82017-04-20 11:16:15 +01003077 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3078 def test_set_reason_wrong_args(self, reason):
3079 """
3080 `Revoked.set_reason` raises `TypeError` if called with an argument
3081 which is neither `None` nor a byte string.
3082 """
3083 revoked = Revoked()
3084 with pytest.raises(TypeError):
3085 revoked.set_reason(reason)
3086
Alex Chandeec9342016-12-19 22:00:38 +00003087 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003088 """
Alex Chandeec9342016-12-19 22:00:38 +00003089 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3090 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003091 """
3092 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003093 with pytest.raises(ValueError):
3094 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003095
3096
Alex Chan7be83a52017-01-24 15:19:29 +00003097class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003098 """
Alex Chan7be83a52017-01-24 15:19:29 +00003099 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003100 """
3101 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3102 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3103
Dan Sully44e767a2016-06-04 18:05:27 -07003104 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3105 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3106 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3107 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3108 intermediate_server_cert = load_certificate(
3109 FILETYPE_PEM, intermediate_server_cert_pem)
3110 intermediate_server_key = load_privatekey(
3111 FILETYPE_PEM, intermediate_server_key_pem)
3112
Rick Dean536ba022009-07-24 23:57:27 -05003113 def test_construction(self):
3114 """
Alex Chan7be83a52017-01-24 15:19:29 +00003115 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003116 that it is empty
3117 """
3118 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003119 assert isinstance(crl, CRL)
3120 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003121
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003122 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003123 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003124 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003125 """
3126 crl = CRL()
3127 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003128 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003129 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003130 revoked.set_serial(b'3ab')
3131 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003132 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003133 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003134
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003135 def test_export_pem(self):
3136 """
3137 If not passed a format, ``CRL.export`` returns a "PEM" format string
3138 representing a serial number, a revoked reason, and certificate issuer
3139 information.
3140 """
Rick Dean536ba022009-07-24 23:57:27 -05003141 # PEM format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003142 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003143 self.cert, self.pkey, days=20, digest=b"sha256"
3144 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003145 crl = x509.load_pem_x509_crl(dumped_crl, backend)
3146 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3147 assert revoked is not None
3148 assert crl.issuer == x509.Name([
3149 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3150 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3151 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3152 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3153 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3154 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003155
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003156 def test_export_der(self):
3157 """
3158 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3159 "DER" format string representing a serial number, a revoked reason, and
3160 certificate issuer information.
3161 """
3162 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003163
3164 # DER format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003165 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003166 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3167 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003168 crl = x509.load_der_x509_crl(dumped_crl, backend)
3169 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3170 assert revoked is not None
3171 assert crl.issuer == x509.Name([
3172 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3173 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3174 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3175 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3176 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3177 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003178
Alex Gaynore466bc92017-07-06 23:43:47 -04003179 # Flaky because we compare the output of running commands which sometimes
3180 # varies by 1 second
3181 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003182 def test_export_text(self):
3183 """
3184 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3185 text format string like the one produced by the openssl command line
3186 tool.
3187 """
3188 crl = self._get_crl()
3189
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003190 dumped_crl = crl.export(
3191 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3192 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003193 text = _runopenssl(
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003194 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER",
3195 b"-nameopt", b""
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003196 )
Rick Dean536ba022009-07-24 23:57:27 -05003197
3198 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003199 dumped_text = crl.export(
3200 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3201 )
Alex Chan7be83a52017-01-24 15:19:29 +00003202 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003203
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003204 def test_export_custom_digest(self):
3205 """
3206 If passed the name of a digest function, ``CRL.export`` uses a
3207 signature algorithm based on that digest function.
3208 """
3209 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003210 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003211 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003212 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003213
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003214 def test_export_md5_digest(self):
3215 """
3216 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3217 not emit a deprecation warning.
3218 """
3219 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003220 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003221 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003222 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003223 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3224 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003225 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003226
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003227 def test_export_default_digest(self):
3228 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003229 If not passed the name of a digest function, ``CRL.export`` raises a
3230 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003231 """
3232 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003233 with pytest.raises(TypeError):
3234 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003235
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003236 def test_export_invalid(self):
3237 """
Alex Chan7be83a52017-01-24 15:19:29 +00003238 If `CRL.export` is used with an uninitialized `X509` instance,
3239 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003240 """
3241 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003242 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003243 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003244
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003245 def test_add_revoked_keyword(self):
3246 """
Alex Chan7be83a52017-01-24 15:19:29 +00003247 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003248 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003249 """
3250 crl = CRL()
3251 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003252 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003253 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003254 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003255 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003256
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003257 def test_export_wrong_args(self):
3258 """
Alex Chan7be83a52017-01-24 15:19:29 +00003259 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003260 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003261 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003262 """
3263 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003264 with pytest.raises(TypeError):
3265 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3266 with pytest.raises(TypeError):
3267 crl.export(self.cert, None, FILETYPE_PEM, 10)
3268 with pytest.raises(TypeError):
3269 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003270 with pytest.raises(TypeError):
3271 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003272
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003273 def test_export_unknown_filetype(self):
3274 """
Alex Chan7be83a52017-01-24 15:19:29 +00003275 Calling `OpenSSL.CRL.export` with a file type other than
3276 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3277 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003278 """
3279 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003280 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003281 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003282
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003283 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003284 """
Alex Chan7be83a52017-01-24 15:19:29 +00003285 Calling `OpenSSL.CRL.export` with an unsupported digest results
3286 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003287 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003288 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003289 with pytest.raises(ValueError):
3290 crl.export(
3291 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003292
Rick Dean536ba022009-07-24 23:57:27 -05003293 def test_get_revoked(self):
3294 """
Alex Chan7be83a52017-01-24 15:19:29 +00003295 Use python to create a simple CRL with two revocations. Get back the
3296 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003297 """
3298 crl = CRL()
3299
3300 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003301 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003302 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003303 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003304 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003305 revoked.set_serial(b'100')
3306 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003307 crl.add_revoked(revoked)
3308
3309 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003310 assert len(revs) == 2
3311 assert type(revs[0]) == Revoked
3312 assert type(revs[1]) == Revoked
3313 assert revs[0].get_serial() == b'03AB'
3314 assert revs[1].get_serial() == b'0100'
3315 assert revs[0].get_rev_date() == now
3316 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003317
Rick Dean536ba022009-07-24 23:57:27 -05003318 def test_load_crl(self):
3319 """
Alex Chan7be83a52017-01-24 15:19:29 +00003320 Load a known CRL and inspect its revocations. Both EM and DER formats
3321 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003322 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003323 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003324 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003325 assert len(revs) == 2
3326 assert revs[0].get_serial() == b'03AB'
3327 assert revs[0].get_reason() is None
3328 assert revs[1].get_serial() == b'0100'
3329 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003330
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003331 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003332 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003333 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003334 assert len(revs) == 2
3335 assert revs[0].get_serial() == b'03AB'
3336 assert revs[0].get_reason() is None
3337 assert revs[1].get_serial() == b'0100'
3338 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003339
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003340 def test_load_crl_bad_filetype(self):
3341 """
Alex Chan7be83a52017-01-24 15:19:29 +00003342 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3343 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003344 """
Alex Chan7be83a52017-01-24 15:19:29 +00003345 with pytest.raises(ValueError):
3346 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003347
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003348 def test_load_crl_bad_data(self):
3349 """
Alex Chan7be83a52017-01-24 15:19:29 +00003350 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3351 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003352 """
Alex Chan7be83a52017-01-24 15:19:29 +00003353 with pytest.raises(Error):
3354 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003355
Dan Sully44e767a2016-06-04 18:05:27 -07003356 def test_get_issuer(self):
3357 """
Alex Chan7be83a52017-01-24 15:19:29 +00003358 Load a known CRL and assert its issuer's common name is what we expect
3359 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003360 """
3361 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003362 assert isinstance(crl.get_issuer(), X509Name)
3363 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003364
Dominic Chenf05b2122015-10-13 16:32:35 +00003365 def test_dump_crl(self):
3366 """
3367 The dumped CRL matches the original input.
3368 """
3369 crl = load_crl(FILETYPE_PEM, crlData)
3370 buf = dump_crl(FILETYPE_PEM, crl)
3371 assert buf == crlData
3372
Dan Sully44e767a2016-06-04 18:05:27 -07003373 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3374 """
3375 Create a CRL.
3376
3377 :param list[X509] certs: A list of certificates to revoke.
3378 :rtype: CRL
3379 """
3380 crl = CRL()
3381 for cert in certs:
3382 revoked = Revoked()
3383 # FIXME: This string splicing is an unfortunate implementation
3384 # detail that has been reported in
3385 # https://github.com/pyca/pyopenssl/issues/258
3386 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3387 revoked.set_serial(serial)
3388 revoked.set_reason(b'unspecified')
3389 revoked.set_rev_date(b'20140601000000Z')
3390 crl.add_revoked(revoked)
3391 crl.set_version(1)
3392 crl.set_lastUpdate(b'20140601000000Z')
3393 crl.set_nextUpdate(b'20180601000000Z')
3394 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3395 return crl
3396
3397 def test_verify_with_revoked(self):
3398 """
Alex Chan7be83a52017-01-24 15:19:29 +00003399 `verify_certificate` raises error when an intermediate certificate is
3400 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003401 """
3402 store = X509Store()
3403 store.add_cert(self.root_cert)
3404 store.add_cert(self.intermediate_cert)
3405 root_crl = self._make_test_crl(
3406 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3407 intermediate_crl = self._make_test_crl(
3408 self.intermediate_cert, self.intermediate_key, certs=[])
3409 store.add_crl(root_crl)
3410 store.add_crl(intermediate_crl)
3411 store.set_flags(
3412 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3413 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003414 with pytest.raises(X509StoreContextError) as err:
3415 store_ctx.verify_certificate()
3416 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003417
3418 def test_verify_with_missing_crl(self):
3419 """
Alex Chan7be83a52017-01-24 15:19:29 +00003420 `verify_certificate` raises error when an intermediate certificate's
3421 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003422 """
3423 store = X509Store()
3424 store.add_cert(self.root_cert)
3425 store.add_cert(self.intermediate_cert)
3426 root_crl = self._make_test_crl(
3427 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3428 store.add_crl(root_crl)
3429 store.set_flags(
3430 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3431 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003432 with pytest.raises(X509StoreContextError) as err:
3433 store_ctx.verify_certificate()
3434 assert err.value.args[0][2] == 'unable to get certificate CRL'
3435 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003436
Paul Kehrer41c10242017-06-29 18:24:17 -05003437 def test_convert_from_cryptography(self):
3438 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3439 crl = CRL.from_cryptography(crypto_crl)
3440 assert isinstance(crl, CRL)
3441
3442 def test_convert_from_cryptography_unsupported_type(self):
3443 with pytest.raises(TypeError):
3444 CRL.from_cryptography(object())
3445
3446 def test_convert_to_cryptography_key(self):
3447 crl = load_crl(FILETYPE_PEM, crlData)
3448 crypto_crl = crl.to_cryptography()
3449 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3450
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003451
Alex Chan7be83a52017-01-24 15:19:29 +00003452class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003453 """
Alex Chan7be83a52017-01-24 15:19:29 +00003454 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003455 """
3456 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3457 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003458 intermediate_server_cert = load_certificate(
3459 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003460
3461 def test_valid(self):
3462 """
Alex Chan7be83a52017-01-24 15:19:29 +00003463 `verify_certificate` returns ``None`` when called with a certificate
3464 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003465 """
3466 store = X509Store()
3467 store.add_cert(self.root_cert)
3468 store.add_cert(self.intermediate_cert)
3469 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003470 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003471
3472 def test_reuse(self):
3473 """
Alex Chan7be83a52017-01-24 15:19:29 +00003474 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003475 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003476 """
3477 store = X509Store()
3478 store.add_cert(self.root_cert)
3479 store.add_cert(self.intermediate_cert)
3480 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003481 assert store_ctx.verify_certificate() is None
3482 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003483
3484 def test_trusted_self_signed(self):
3485 """
Alex Chan7be83a52017-01-24 15:19:29 +00003486 `verify_certificate` returns ``None`` when called with a self-signed
3487 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003488 """
3489 store = X509Store()
3490 store.add_cert(self.root_cert)
3491 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003492 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003493
3494 def test_untrusted_self_signed(self):
3495 """
Alex Chan7be83a52017-01-24 15:19:29 +00003496 `verify_certificate` raises error when a self-signed certificate is
3497 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003498 """
3499 store = X509Store()
3500 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003501 with pytest.raises(X509StoreContextError) as exc:
3502 store_ctx.verify_certificate()
3503
3504 assert exc.value.args[0][2] == 'self signed certificate'
3505 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003506
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003507 def test_invalid_chain_no_root(self):
3508 """
Alex Chan7be83a52017-01-24 15:19:29 +00003509 `verify_certificate` raises error when a root certificate is missing
3510 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003511 """
3512 store = X509Store()
3513 store.add_cert(self.intermediate_cert)
3514 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003515
3516 with pytest.raises(X509StoreContextError) as exc:
3517 store_ctx.verify_certificate()
3518
3519 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3520 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003521
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003522 def test_invalid_chain_no_intermediate(self):
3523 """
Alex Chan7be83a52017-01-24 15:19:29 +00003524 `verify_certificate` raises error when an intermediate certificate is
3525 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003526 """
3527 store = X509Store()
3528 store.add_cert(self.root_cert)
3529 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003530
Alex Gaynor85b49702015-09-05 16:30:59 -04003531 with pytest.raises(X509StoreContextError) as exc:
3532 store_ctx.verify_certificate()
3533
3534 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3535 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003536
Stephen Holsapple46a09252015-02-12 14:45:43 -08003537 def test_modification_pre_verify(self):
3538 """
Alex Chan7be83a52017-01-24 15:19:29 +00003539 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003540 instantiation.
3541 """
3542 store_bad = X509Store()
3543 store_bad.add_cert(self.intermediate_cert)
3544 store_good = X509Store()
3545 store_good.add_cert(self.root_cert)
3546 store_good.add_cert(self.intermediate_cert)
3547 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003548
3549 with pytest.raises(X509StoreContextError) as exc:
3550 store_ctx.verify_certificate()
3551
3552 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3553 assert exc.value.certificate.get_subject().CN == 'intermediate'
3554
Stephen Holsapple46a09252015-02-12 14:45:43 -08003555 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003556 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003557
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003558 def test_verify_with_time(self):
3559 """
3560 `verify_certificate` raises error when the verification time is
3561 set at notAfter.
3562 """
3563 store = X509Store()
3564 store.add_cert(self.root_cert)
3565 store.add_cert(self.intermediate_cert)
3566
3567 expire_time = self.intermediate_server_cert.get_notAfter()
3568 expire_datetime = datetime.strptime(
3569 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3570 )
3571 store.set_time(expire_datetime)
3572
3573 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3574 with pytest.raises(X509StoreContextError) as exc:
3575 store_ctx.verify_certificate()
3576
3577 assert exc.value.args[0][2] == 'certificate has expired'
3578
Stephen Holsapple46a09252015-02-12 14:45:43 -08003579
Alex Chan7be83a52017-01-24 15:19:29 +00003580class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003581 """
Alex Chan7be83a52017-01-24 15:19:29 +00003582 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003583 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003584
James Yonan7c2e5d32010-02-27 05:45:50 -07003585 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003586 """
Alex Chan7be83a52017-01-24 15:19:29 +00003587 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003588 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003589 content = (
3590 b"It was a bright cold day in April, and the clocks were striking "
3591 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3592 b"effort to escape the vile wind, slipped quickly through the "
3593 b"glass doors of Victory Mansions, though not quickly enough to "
3594 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003595
3596 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003597 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003598 # verify the content with this cert
3599 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3600 # certificate unrelated to priv_key, used to trigger an error
3601 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003602
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003603 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003604 sig = sign(priv_key, content, digest)
3605
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003606 # Verify the signature of content, will throw an exception if
3607 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003608 verify(good_cert, sig, content, digest)
3609
3610 # This should fail because the certificate doesn't match the
3611 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003612 with pytest.raises(Error):
3613 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003614
3615 # This should fail because we've "tainted" the content after
3616 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003617 with pytest.raises(Error):
3618 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003619
3620 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003621 with pytest.raises(ValueError):
3622 sign(priv_key, content, "strange-digest")
3623 with pytest.raises(ValueError):
3624 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003625
Abraham Martinc5484ba2015-03-25 15:33:05 +00003626 def test_sign_verify_with_text(self):
3627 """
Alex Chan7be83a52017-01-24 15:19:29 +00003628 `sign` generates a cryptographic signature which
3629 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003630 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003631 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003632 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003633 b"It was a bright cold day in April, and the clocks were striking "
3634 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3635 b"effort to escape the vile wind, slipped quickly through the "
3636 b"glass doors of Victory Mansions, though not quickly enough to "
3637 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003638 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003639
3640 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3641 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3642 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003643 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003644 simplefilter("always")
3645 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003646 assert (
3647 "{0} for data is no longer accepted, use bytes".format(
3648 WARNING_TYPE_EXPECTED
3649 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003650
Alex Chan7be83a52017-01-24 15:19:29 +00003651 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003652 simplefilter("always")
3653 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003654 assert (
3655 "{0} for data is no longer accepted, use bytes".format(
3656 WARNING_TYPE_EXPECTED
3657 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003658
Paul Kehrer59d26252017-07-20 10:45:54 +02003659 def test_sign_verify_ecdsa(self):
3660 """
3661 `sign` generates a cryptographic signature which `verify` can check.
3662 ECDSA Signatures in the X9.62 format may have variable length,
3663 different from the length of the private key.
3664 """
3665 content = (
3666 b"It was a bright cold day in April, and the clocks were striking "
3667 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3668 b"effort to escape the vile wind, slipped quickly through the "
3669 b"glass doors of Victory Mansions, though not quickly enough to "
3670 b"prevent a swirl of gritty dust from entering along with him."
3671 ).decode("ascii")
3672 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3673 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3674 sig = sign(priv_key, content, "sha1")
3675 verify(cert, sig, content, "sha1")
3676
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003677 def test_sign_nulls(self):
3678 """
Alex Chan7be83a52017-01-24 15:19:29 +00003679 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003680 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003681 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003682 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3683 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3684 sig = sign(priv_key, content, "sha1")
3685 verify(good_cert, sig, content, "sha1")
3686
Colleen Murphye09399b2016-03-01 17:40:49 -08003687 def test_sign_with_large_key(self):
3688 """
Alex Chan7be83a52017-01-24 15:19:29 +00003689 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003690 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003691 content = (
3692 b"It was a bright cold day in April, and the clocks were striking "
3693 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3694 b"effort to escape the vile wind, slipped quickly through the "
3695 b"glass doors of Victory Mansions, though not quickly enough to "
3696 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003697
3698 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3699 sign(priv_key, content, "sha1")
3700
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003701
Alex Chan63ef9bc2016-12-19 12:02:06 +00003702class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003703 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003704 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3705 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003706 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003707
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003708 def test_set(self):
3709 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003710 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003711 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003712 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003713
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003714 def test_a_curve(self):
3715 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003716 `get_elliptic_curve` can be used to retrieve a particular supported
3717 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003718 """
3719 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003720 curve = next(iter(curves))
3721 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003722
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003723 def test_not_a_curve(self):
3724 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003725 `get_elliptic_curve` raises `ValueError` if called with a name which
3726 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003727 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003728 with pytest.raises(ValueError):
3729 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003730
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003731 def test_repr(self):
3732 """
3733 The string representation of a curve object includes simply states the
3734 object is a curve and what its name is.
3735 """
3736 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003737 curve = next(iter(curves))
3738 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003739
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003740 def test_to_EC_KEY(self):
3741 """
3742 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003743 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003744 """
3745 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003746 curve = next(iter(curves))
3747 # It's not easy to assert anything about this object. However, see
3748 # leakcheck/crypto.py for a test that demonstrates it at least does
3749 # not leak memory.
3750 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003751
3752
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003753class EllipticCurveFactory(object):
3754 """
3755 A helper to get the names of two curves.
3756 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003757
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003758 def __init__(self):
3759 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003760 self.curve_name = next(curves).name
3761 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003762
3763
Alex Chan63ef9bc2016-12-19 12:02:06 +00003764class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003765 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003766 Tests `_EllipticCurve`'s implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003767 """
3768 curve_factory = EllipticCurveFactory()
3769
3770 if curve_factory.curve_name is None:
3771 skip = "There are no curves available there can be no curve objects."
3772
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003773 def anInstance(self):
3774 """
3775 Get the curve object for an arbitrary curve supported by the system.
3776 """
3777 return get_elliptic_curve(self.curve_factory.curve_name)
3778
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003779 def anotherInstance(self):
3780 """
3781 Get the curve object for an arbitrary curve supported by the system -
3782 but not the one returned by C{anInstance}.
3783 """
3784 return get_elliptic_curve(self.curve_factory.another_curve_name)
3785
3786
Alex Chan63ef9bc2016-12-19 12:02:06 +00003787class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003788 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003789 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3790 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003791 """
3792 curve_factory = EllipticCurveFactory()
3793
3794 if curve_factory.curve_name is None:
3795 skip = "There are no curves available there can be no curve objects."
3796
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003797 def test_contains(self):
3798 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003799 The ``in`` operator reports that a `set` containing a curve does
3800 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003801 """
3802 curve = get_elliptic_curve(self.curve_factory.curve_name)
3803 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003804 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003805
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003806 def test_does_not_contain(self):
3807 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003808 The ``in`` operator reports that a `set` not containing a curve
3809 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003810 """
3811 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003812 curves = set([
3813 get_elliptic_curve(self.curve_factory.another_curve_name)
3814 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003815 assert curve not in curves