blob: b0e8e8ba5ab1e1695da5029c24f9d54d492b48ca [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 Gaynor9939ba12017-06-25 16:28:24 -040016from cryptography import x509
Paul Kehrer72d968b2016-07-29 15:31:04 +080017from cryptography.hazmat.backends.openssl.backend import backend
18from cryptography.hazmat.primitives import serialization
19from cryptography.hazmat.primitives.asymmetric import rsa
20
Alex Gaynore466bc92017-07-06 23:43:47 -040021import flaky
22
Alex Gaynor01f90a12019-02-07 09:14:48 -050023from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey
24from OpenSSL.crypto import X509, X509Name
Alex Gaynor31287502015-09-05 16:11:27 -040025from OpenSSL.crypto import (
Dan Sully44e767a2016-06-04 18:05:27 -070026 X509Store,
27 X509StoreFlags,
Dan Sully44e767a2016-06-04 18:05:27 -070028 X509StoreContext,
29 X509StoreContextError
Alex Gaynor31287502015-09-05 16:11:27 -040030)
Alex Gaynor01f90a12019-02-07 09:14:48 -050031from OpenSSL.crypto import X509Req
32from OpenSSL.crypto import X509Extension
Rick Dean5b7b6372009-04-01 11:34:06 -050033from OpenSSL.crypto import load_certificate, load_privatekey
Cory Benfield6492f7c2015-10-27 16:57:58 +090034from OpenSSL.crypto import load_publickey, dump_publickey
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -040035from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
Jean-Paul Calderone71919862009-04-01 13:01:19 -040036from OpenSSL.crypto import dump_certificate, load_certificate_request
37from OpenSSL.crypto import dump_certificate_request, dump_privatekey
Alex Gaynor01f90a12019-02-07 09:14:48 -050038from OpenSSL.crypto import PKCS7, load_pkcs7_data
39from OpenSSL.crypto import PKCS12, load_pkcs12
Dominic Chenf05b2122015-10-13 16:32:35 +000040from OpenSSL.crypto import CRL, Revoked, dump_crl, load_crl
Alex Gaynor01f90a12019-02-07 09:14:48 -050041from OpenSSL.crypto import NetscapeSPKI
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040042from OpenSSL.crypto import (
43 sign, verify, get_elliptic_curve, get_elliptic_curves)
Hynek Schlawackf0e66852015-10-16 20:18:38 +020044
Alex Chanb00ede22017-01-30 07:24:40 +000045from .util import EqualityTestsMixin, is_consistent_type, WARNING_TYPE_EXPECTED
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040046
Alex Gaynoraceb3e22015-09-05 12:00:22 -040047
Jean-Paul Calderone9da338d2011-05-04 11:40:54 -040048def normalize_privatekey_pem(pem):
49 return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
50
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040051
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050052GOOD_CIPHER = "blowfish"
53BAD_CIPHER = "zippers"
54
Anthony Alba2ce737f2015-12-04 11:04:56 +080055GOOD_DIGEST = "SHA1"
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050056BAD_DIGEST = "monkeys"
57
Paul Kehrera40898b2017-06-11 16:30:58 -100058old_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
Rick Dean94e46fd2009-07-18 14:51:24 -050059MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
60BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
61ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
62NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
63MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
64ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
65urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
662xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
671dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
68FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
69VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
70BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
71b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
72AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
73hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
74w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
75-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -040076"""
Rick Dean94e46fd2009-07-18 14:51:24 -050077
Paul Kehrera40898b2017-06-11 16:30:58 -100078root_cert_pem = b"""-----BEGIN CERTIFICATE-----
79MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
80BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
81ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
82WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
83BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
84bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
85bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
86LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
87onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
88LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
89yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
90aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
91Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
92R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
93gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
94lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
95-----END CERTIFICATE-----
96"""
97
Alex Gaynore7f51982016-09-11 11:48:14 -040098root_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -050099MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
100jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
1013claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
102AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
103yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
1046JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
105BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
106u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
107PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
108I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
109ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
1106AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
111cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
112-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400113"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500114
Alex Gaynore7f51982016-09-11 11:48:14 -0400115intermediate_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700116MIICVzCCAcCgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQENBQAw
117WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
118DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTQw
119ODI4MDIwNDA4WhcNMjQwODI1MDIwNDA4WjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
120dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
121MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIGfMA0GCSqGSIb3DQEB
122AQUAA4GNADCBiQKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmK
123FGIbljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT
12421H2qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwID
125AQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDQUAA4GBAPIWSkLX
126QRMApOjjyC+tMxumT5e2pMqChHmxobQK4NMdrf2VCx+cRT6EmY8sK3/Xl/X8UBQ+
1279n5zXb1ZwhW/sTWgUvmOceJ4/XVs9FkdWOOn1J0XBch9ZIiFe/s5ASIgG7fUdcUF
1289mAWS6FK2ca3xIh5kIupCXOFa0dPvlw/YUFT
129-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400130"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700131
Alex Gaynore7f51982016-09-11 11:48:14 -0400132intermediate_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700133MIICWwIBAAKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmKFGIb
134ljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT21H2
135qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwIDAQAB
136AoGAfSZVV80pSeOKHTYfbGdNY/jHdU9eFUa/33YWriXU+77EhpIItJjkRRgivIfo
137rhFJpBSGmDLblaqepm8emsXMeH4+2QzOYIf0QGGP6E6scjTt1PLqdqKfVJ1a2REN
138147cujNcmFJb/5VQHHMpaPTgttEjlzuww4+BCDPsVRABWrkCQQD3loH36nLoQTtf
139+kQq0T6Bs9/UWkTAGo0ND81ALj0F8Ie1oeZg6RNT96RxZ3aVuFTESTv6/TbjWywO
140wdzlmV1vAkEA38rTJ6PTwaJlw5OttdDzAXGPB9tDmzh9oSi7cHwQQXizYd8MBYx4
141sjHUKD3dCQnb1dxJFhd3BT5HsnkRMbVZXQJAbXduH17ZTzcIOXc9jHDXYiFVZV5D
14252vV0WCbLzVCZc3jMrtSUKa8lPN5EWrdU3UchWybyG0MR5mX8S5lrF4SoQJAIyUD
143DBKaSqpqONCUUx1BTFS9FYrFjzbL4+c1qHCTTPTblt8kUCrDOZjBrKAqeiTmNSum
144/qUot9YUBF8m6BuGsQJATHHmdFy/fG1VLkyBp49CAa8tN3Z5r/CgTznI4DfMTf4C
145NbRHn2UmYlwQBa+L5lg9phewNe8aEwpPyPLoV85U8Q==
146-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400147"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700148
Alex Gaynore7f51982016-09-11 11:48:14 -0400149server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000150MIICJDCCAY2gAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
151BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
152VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMTA1
153N1oXDTM3MDYwNzAwMTA1N1owGDEWMBQGA1UEAwwNbG92ZWx5IHNlcnZlcjCBnzAN
154BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvqb4brndXS2kEL84qXbZXE6LYK+UrhNi
15570sdIM/24NVN7tXkPlOXqrMWhFHHml+aeSpPkH5b1vKnY1TcULmEubnNICtvjmZ5
156SGMQn+J+RmBs1SMd0EgY/0wBBQdlrlYp2QYgm8YC+zxTNSqWvhMFZAgHbj6Un5SS
157T8JGBqytjB0CAwEAAaM2MDQwHQYDVR0OBBYEFINVdy1eIfFJDAkk51QJEo3IfgSu
158MBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4GBAGki1K6WgHHJ
159qC6aY2EowjaWOXLO6jUZIhGk7BA7vMRfNug429AOZ4m5F6OQhzmJmlw67Jyu2FeI
160h0VtBuQoHPtjqZXF59oX6hMMmGLMs9pV0UA3fJs5MYA4/V5ZcQy0Ie0QoJNejLzE
1616V1Qz1rRTYLUyEcpI7ZCmBg2KQQI8YZI
Rick Dean94e46fd2009-07-18 14:51:24 -0500162-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400163"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500164
Alex Gaynore7f51982016-09-11 11:48:14 -0400165server_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500166MIICWwIBAAKBgQC+pvhuud1dLaQQvzipdtlcTotgr5SuE2LvSx0gz/bg1U3u1eQ+
167U5eqsxaEUceaX5p5Kk+QflvW8qdjVNxQuYS5uc0gK2+OZnlIYxCf4n5GYGzVIx3Q
168SBj/TAEFB2WuVinZBiCbxgL7PFM1Kpa+EwVkCAduPpSflJJPwkYGrK2MHQIDAQAB
169AoGAbwuZ0AR6JveahBaczjfnSpiFHf+mve2UxoQdpyr6ROJ4zg/PLW5K/KXrC48G
170j6f3tXMrfKHcpEoZrQWUfYBRCUsGD5DCazEhD8zlxEHahIsqpwA0WWssJA2VOLEN
171j6DuV2pCFbw67rfTBkTSo32ahfXxEKev5KswZk0JIzH3ooECQQDgzS9AI89h0gs8
172Dt+1m11Rzqo3vZML7ZIyGApUzVan+a7hbc33nbGRkAXjHaUBJO31it/H6dTO+uwX
173msWwNG5ZAkEA2RyFKs5xR5USTFaKLWCgpH/ydV96KPOpBND7TKQx62snDenFNNbn
174FwwOhpahld+vqhYk+pfuWWUpQciE+Bu7ZQJASjfT4sQv4qbbKK/scePicnDdx9th
1754e1EeB9xwb+tXXXUo/6Bor/AcUNwfiQ6Zt9PZOK9sR3lMZSsP7rMi7kzuQJABie6
1761sXXjFH7nNJvRG4S39cIxq8YRYTy68II/dlB2QzGpKxV/POCxbJ/zu0CU79tuYK7
177NaeNCFfH3aeTrX0LyQJAMBWjWmeKM2G2sCExheeQK0ROnaBC8itCECD4Jsve4nqf
178r50+LF74iLXFwqysVCebPKMOpDWp/qQ1BbJQIPs7/A==
179-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400180""")
Rick Dean94e46fd2009-07-18 14:51:24 -0500181
Alex Gaynore7f51982016-09-11 11:48:14 -0400182intermediate_server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700183MIICWDCCAcGgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQENBQAw
184ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
185CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
186biBEaWVnbzAeFw0xNDA4MjgwMjEwNDhaFw0yNDA4MjUwMjEwNDhaMG4xHTAbBgNV
187BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
188CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
189biBEaWVnbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqpJZygd+w1faLOr1
190iOAmbBhx5SZWcTCZ/ZjHQTJM7GuPT624QkqsixFghRKdDROwpwnAP7gMRukLqiy4
191+kRuGT5OfyGggL95i2xqA+zehjj08lSTlvGHpePJgCyTavIy5+Ljsj4DKnKyuhxm
192biXTRrH83NDgixVkObTEmh/OVK0CAwEAATANBgkqhkiG9w0BAQ0FAAOBgQBa0Npw
193UkzjaYEo1OUE1sTI6Mm4riTIHMak4/nswKh9hYup//WVOlr/RBSBtZ7Q/BwbjobN
1943bfAtV7eSAqBsfxYXyof7G1ALANQERkq3+oyLP1iVt08W1WOUlIMPhdCF/QuCwy6
195x9MJLhUCGLJPM+O2rAPWVD9wCmvq10ALsiH3yA==
196-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400197"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700198
Alex Gaynore7f51982016-09-11 11:48:14 -0400199intermediate_server_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700200MIICXAIBAAKBgQCqklnKB37DV9os6vWI4CZsGHHlJlZxMJn9mMdBMkzsa49PrbhC
201SqyLEWCFEp0NE7CnCcA/uAxG6QuqLLj6RG4ZPk5/IaCAv3mLbGoD7N6GOPTyVJOW
2028Yel48mALJNq8jLn4uOyPgMqcrK6HGZuJdNGsfzc0OCLFWQ5tMSaH85UrQIDAQAB
203AoGAIQ594j5zna3/9WaPsTgnmhlesVctt4AAx/n827DA4ayyuHFlXUuVhtoWR5Pk
2045ezj9mtYW8DyeCegABnsu2vZni/CdvU6uiS1Hv6qM1GyYDm9KWgovIP9rQCDSGaz
205d57IWVGxx7ODFkm3gN5nxnSBOFVHytuW1J7FBRnEsehRroECQQDXHFOv82JuXDcz
206z3+4c74IEURdOHcbycxlppmK9kFqm5lsUdydnnGW+mvwDk0APOB7Wg7vyFyr393e
207dpmBDCzNAkEAyv6tVbTKUYhSjW+QhabJo896/EqQEYUmtMXxk4cQnKeR/Ao84Rkf
208EqD5IykMUfUI0jJU4DGX+gWZ10a7kNbHYQJAVFCuHNFxS4Cpwo0aqtnzKoZaHY/8
209X9ABZfafSHCtw3Op92M+7ikkrOELXdS9KdKyyqbKJAKNEHF3LbOfB44WIQJAA2N4
2109UNNVUsXRbElEnYUS529CdUczo4QdVgQjkvk5RiPAUwSdBd9Q0xYnFOlFwEmIowg
211ipWJWe0aAlP18ZcEQQJBAL+5lekZ/GUdQoZ4HAsN5a9syrzavJ9VvU1KOOPorPZK
212nMRZbbQgP+aSB7yl6K0gaLaZ8XaK0pjxNBh6ASqg9f4=
213-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400214"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700215
Alex Gaynore7f51982016-09-11 11:48:14 -0400216client_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000217MIICIjCCAYugAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
218BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
219VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMDQx
220M1oXDTM3MDYwNzAwMDQxM1owFjEUMBIGA1UEAwwLdWdseSBjbGllbnQwgZ8wDQYJ
221KoZIhvcNAQEBBQADgY0AMIGJAoGBAMBmH9JG02bme0xPipvpjMSlOugyWrauf4at
222EdGJn7GQLD8IY2Fu0+Kvv9DFpSPboFKZCsfDVsYoRs+xaJbtt1dJ6ymX7EqKS7gb
2238q+eeZZ14keqyJd5Rm2q6swQtw9ADD3E8cS6GqpQm+8SgxOycISoYz7sO1ugJFqN
224jId+W4BFAgMBAAGjNjA0MB0GA1UdDgQWBBSDVXctXiHxSQwJJOdUCRKNyH4ErjAT
225BgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQAMqcHyweaCOZNN
226dWQQOsBKQlL5wqVVZwucHPWqobjxpULKy9gS2ha2zbgkXcB/BnBOSwe0Fm+MJV0T
227NbnTghcGJNpEH7VKn4xSLvIGZmnZZWgxeIB16z4GhpkK2fShBJ+6GKZjsgjT0lSH
228JRgjHbWutZfZvbSHXr9n7PIphG1Ojg==
Rick Dean94e46fd2009-07-18 14:51:24 -0500229-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400230"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500231
Alex Gaynore7f51982016-09-11 11:48:14 -0400232client_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500233MIICXgIBAAKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2rn+GrRHRiZ+xkCw/CGNh
234btPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xKiku4G/KvnnmWdeJHqsiX
235eUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7DtboCRajYyHfluARQIDAQAB
236AoGATkZ+NceY5Glqyl4mD06SdcKfV65814vg2EL7V9t8+/mi9rYL8KztSXGlQWPX
237zuHgtRoMl78yQ4ZJYOBVo+nsx8KZNRCEBlE19bamSbQLCeQMenWnpeYyQUZ908gF
238h6L9qsFVJepgA9RDgAjyDoS5CaWCdCCPCH2lDkdcqC54SVUCQQDseuduc4wi8h4t
239V8AahUn9fn9gYfhoNuM0gdguTA0nPLVWz4hy1yJiWYQe0H7NLNNTmCKiLQaJpAbb
240TC6vE8C7AkEA0Ee8CMJUc20BnGEmxwgWcVuqFWaKCo8jTH1X38FlATUsyR3krjW2
241dL3yDD9NwHxsYP7nTKp/U8MV7U9IBn4y/wJBAJl7H0/BcLeRmuJk7IqJ7b635iYB
242D/9beFUw3MUXmQXZUfyYz39xf6CDZsu1GEdEC5haykeln3Of4M9d/4Kj+FcCQQCY
243si6xwT7GzMDkk/ko684AV3KPc/h6G0yGtFIrMg7J3uExpR/VdH2KgwMkZXisSMvw
244JJEQjOMCVsEJlRk54WWjAkEAzoZNH6UhDdBK5F38rVt/y4SEHgbSfJHIAmPS32Kq
245f6GGcfNpip0Uk7q7udTKuX7Q/buZi/C4YW7u3VKAquv9NA==
246-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400247""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400248
Alex Gaynore7f51982016-09-11 11:48:14 -0400249cleartextCertificatePEM = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000250MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400251BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
Paul Kehrera40898b2017-06-11 16:30:58 -1000252ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
253WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
254BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
255bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
256bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
257LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
258onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
259LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
260yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
261aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
262Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
263R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
264gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
265lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400266-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400267"""
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400268
Alex Gaynore7f51982016-09-11 11:48:14 -0400269cleartextPrivateKeyPEM = normalize_privatekey_pem(b"""\
Jean-Paul Calderoned50d2042011-05-04 17:00:49 -0400270-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400271MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
272jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
2733claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
274AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
275yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
2766JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
277BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
278u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
279PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
280I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
281ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
2826AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
283cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
284-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400285""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400286
Alex Gaynore7f51982016-09-11 11:48:14 -0400287cleartextCertificateRequestPEM = b"""-----BEGIN CERTIFICATE REQUEST-----
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -0400288MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
289EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
290ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
291BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
292E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
293xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
294gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
295Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
296oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
297-----END CERTIFICATE REQUEST-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400298"""
Rick Dean5b7b6372009-04-01 11:34:06 -0500299
Alex Gaynore7f51982016-09-11 11:48:14 -0400300encryptedPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400301Proc-Type: 4,ENCRYPTED
302DEK-Info: DES-EDE3-CBC,9573604A18579E9E
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400303
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400304SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
305a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
3068+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
307mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
308+00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
309fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
310tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
311rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
312gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
313o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
3147SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
315MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
31611n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
317-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400318"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400319
Alex Gaynore7f51982016-09-11 11:48:14 -0400320encryptedPrivateKeyPEMPassphrase = b"foobar"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400321
Cory Benfield6492f7c2015-10-27 16:57:58 +0900322
Alex Gaynore7f51982016-09-11 11:48:14 -0400323cleartextPublicKeyPEM = b"""-----BEGIN PUBLIC KEY-----
Cory Benfield6492f7c2015-10-27 16:57:58 +0900324MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxszlc+b71LvlLS0ypt/l
325gT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZOtPclNY823Q4pErMTSWC
32690qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLjBuUIkQzEKEFV+8taiRV+
327ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPrUQqYQUEiTmVhh4FBUKZ5
328XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV215k4TeHMFYE5RG0KYAS
3298Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6HXRpQCyASzEG7bgtROLhL
330ywIDAQAB
331-----END PUBLIC KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400332"""
Cory Benfield6492f7c2015-10-27 16:57:58 +0900333
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400334# Some PKCS#7 stuff. Generated with the openssl command line:
335#
336# openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
337#
338# with a certificate and key (but the key should be irrelevant) in s.pem
Alex Gaynore7f51982016-09-11 11:48:14 -0400339pkcs7Data = b"""\
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400340-----BEGIN PKCS7-----
341MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
342BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
343A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
344MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
345cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
346A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
347HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
348SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
349zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
350LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
351A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
35265w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
353Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
354Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
355bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
356VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
357/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
358Ho4EzbYCOaEAMQA=
359-----END PKCS7-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400360"""
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400361
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700362pkcs7DataASN1 = base64.b64decode(b"""
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700363MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
364BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
365A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
366MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
367cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
368A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
369HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
370SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
371zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
372LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
373A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
37465w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
375Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
376Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
377bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
378VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
379/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
380Ho4EzbYCOaEAMQA=
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700381""")
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700382
Alex Gaynore7f51982016-09-11 11:48:14 -0400383crlData = b"""\
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -0500384-----BEGIN X509 CRL-----
385MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
386SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
387D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
388MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
389MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
3904dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
3910yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
392vrzEeLDRiiPl92dyyWmu
393-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400394"""
Jean-Paul Calderonee890db32010-08-22 16:55:15 -0400395
Alex Gaynore7f51982016-09-11 11:48:14 -0400396crlDataUnsupportedExtension = b"""\
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400397-----BEGIN X509 CRL-----
398MIIGRzCCBS8CAQIwDQYJKoZIhvcNAQELBQAwJzELMAkGA1UEBhMCVVMxGDAWBgNV
399BAMMD2NyeXB0b2dyYXBoeS5pbxgPMjAxNTAxMDEwMDAwMDBaGA8yMDE2MDEwMTAw
400MDAwMFowggTOMBQCAQAYDzIwMTUwMTAxMDAwMDAwWjByAgEBGA8yMDE1MDEwMTAw
401MDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAn
402MQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQD
403CgEAMHICAQIYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAw
404MDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlw
405dG9ncmFwaHkuaW8wCgYDVR0VBAMKAQEwcgIBAxgPMjAxNTAxMDEwMDAwMDBaMFww
406GAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTArpCkwJzELMAkGA1UE
407BhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNVHRUEAwoBAjByAgEE
408GA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQG
409A1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5
410LmlvMAoGA1UdFQQDCgEDMHICAQUYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQR
411GA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgw
412FgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQQwcgIBBhgPMjAxNTAx
413MDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTAr
414pCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNV
415HRUEAwoBBTByAgEHGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAx
416MDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwP
417Y3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEGMHICAQgYDzIwMTUwMTAxMDAwMDAw
418WjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJ
419BgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQgw
420cgIBCRgPMjAxNTAxMDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAw
421WjA0BgNVHR0ELTArpCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dy
422YXBoeS5pbzAKBgNVHRUEAwoBCTByAgEKGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNV
423HRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJV
424UzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEKMC4CAQsYDzIw
425MTUwMTAxMDAwMDAwWjAYMAoGA1UdFQQDCgEBMAoGAyoDBAQDCgEAMA0GCSqGSIb3
426DQEBCwUAA4IBAQBTaloHlPaCZzYee8LxkWej5meiqxQVNWFoVdjesroa+f1FRrH+
427drRU60Nq97KCKf7f9GNN/J3ZIlQmYhmuDqh12f+XLpotoj1ZRfBz2hjFCkJlv+2c
428oWWGNHgA70ndFoVtcmX088SYpX8E3ARATivS4q2h9WlwV6rO93mhg3HGIe3JpcK4
4297BcW6Poi/ut/zsDOkVbI00SqaujRpdmdCTht82MH3ztjyDkI9KYaD/YEweKSrWOz
430SdEILd164bfBeLuplVI+xpmTEMVNpXBlSXl7+xIw9Vk7p7Q1Pa3k/SvhOldYCm6y
431C1xAg/AAq6w78yzYt18j5Mj0s6eeHi1YpHKw
432-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400433"""
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400434
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400435
436# A broken RSA private key which can be used to test the error path through
437# PKey.check.
Alex Gaynore7f51982016-09-11 11:48:14 -0400438inconsistentPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400439MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
4405kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
441OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
442zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
443nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
444HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
445oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
446-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400447"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400448
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400449# certificate with NULL bytes in subjectAltName and common name
450
Alex Gaynore7f51982016-09-11 11:48:14 -0400451nulbyteSubjectAltNamePEM = b"""-----BEGIN CERTIFICATE-----
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400452MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
453DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
454eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
455RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
456ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
457NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
458DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
459ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
460ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
461hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
462BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
463pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
464vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
465KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
466oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
46708LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
468HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
469BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
470Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
471bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
472AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
473i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
474HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
475kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
476VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
477RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
Alex Gaynore7f51982016-09-11 11:48:14 -0400478-----END CERTIFICATE-----"""
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400479
Alex Gaynore7f51982016-09-11 11:48:14 -0400480large_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Colleen Murphye09399b2016-03-01 17:40:49 -0800481MIIJYgIBAAKCAg4AtRua8eIeevRfsj+fkcHr1vmse7Kgb+oX1ssJAvCb1R7JQMnH
482hNDjDP6b3vEkZuPUzlDHymP+cNkXvvi4wJ4miVbO3+SeU4Sh+jmsHeHzGIXat9xW
4839PFtuPM5FQq8zvkY8aDeRYmYwN9JKu4/neMBCBqostYlTEWg+bSytO/qWnyHTHKh
484g0GfaDdqUQPsGQw+J0MgaYIjQOCVASHAPlzbDQLCtuOb587rwTLkZA2GwoHB/LyJ
485BwT0HHgBaiObE12Vs6wi2en0Uu11CiwEuK1KIBcZ2XbE6eApaZa6VH9ysEmUxPt7
486TqyZ4E2oMIYaLPNRxuvozdwTlj1svI1k1FrkaXGc5MTjbgigPMKjIb0T7b/4GNzt
487DhP1LvAeUMnrEi3hJJrcJPXHPqS8/RiytR9xQQW6Sdh4LaA3f9MQm3WSevWage3G
488P8YcCLssOVKsArDjuA52NF5LmYuAeUzXprm4ITDi2oO+0iFBpFW6VPEK4A9vO0Yk
489M/6Wt6tG8zyWhaSH1zFUTwfQ9Yvjyt5w1lrUaAJuoTpwbMVZaDJaEhjOaXU0dyPQ
490jOsePDOQcU6dkeTWsQ3LsHPEEug/X6819TLG5mb3V7bvV9nPFBfTJSCEG794kr90
491XgZfIN71FrdByxLerlbuJI21pPs/nZi9SXi9jAWeiS45/azUxMsyYgJArui+gjq7
492sV1pWiBm6/orAgMBAAECggINQp5L6Yu+oIXBqcSjgq8tfF9M5hd30pLuf/EheHZf
493LA7uAqn2fVGFI2OInIJhXIOT5OxsAXO0xXfltzawZxIFpOFMqajj4F7aYjvSpw9V
494J4EdSiJ/zgv8y1qUdbwEZbHVThRZjoSlrtSzilonBoHZAE0mHtqMz7iRFSk1zz6t
495GunRrvo/lROPentf3TsvHquVNUYI5yaapyO1S7xJhecMIIYSb8nbsHI54FBDGNas
4966mFmpPwI/47/6HTwOEWupnn3NicsjrHzUInOUpaMig4cRR+aP5bjqg/ty8xI8AoN
497evEmCytiWTc+Rvbp1ieN+1jpjN18PjUk80/W7qioHUDt4ieLic8uxWH2VD9SCEnX
498Mpi9tA/FqoZ+2A/3m1OfrY6jiZVE2g+asi9lCK7QVWL39eK82H4rPvtp0/dyo1/i
499ZZz68TXg+m8IgEZcp88hngbkuoTTzpGE73QuPKhGA1uMIimDdqPPB5WP76q+03Oi
500IRR5DfZnqPERed49by0enJ7tKa/gFPZizOV8ALKr0Dp+vfAkxGDLPLBLd2A3//tw
501xg0Q/wltihHSBujv4nYlDXdc5oYyMYZ+Lhc/VuOghHfBq3tgEQ1ECM/ofqXEIdy7
502nVcpZn3Eeq8Jl5CrqxE1ee3NxlzsJHn99yGQpr7mOhW/psJF3XNz80Meg3L4m1T8
503sMBK0GbaassuJhdzb5whAoIBBw48sx1b1WR4XxQc5O/HjHva+l16i2pjUnOUTcDF
504RWmSbIhBm2QQ2rVhO8+fak0tkl6ZnMWW4i0U/X5LOEBbC7+IS8bO3j3Revi+Vw5x
505j96LMlIe9XEub5i/saEWgiz7maCvfzLFU08e1OpT4qPDpP293V400ubA6R7WQTCv
506pBkskGwHeu0l/TuKkVqBFFUTu7KEbps8Gjg7MkJaFriAOv1zis/umK8pVS3ZAM6e
5078w5jfpRccn8Xzta2fRwTB5kCmfxdDsY0oYGxPLRAbW72bORoLGuyyPp/ojeGwoik
508JX9RttErc6FjyZtks370Pa8UL5QskyhMbDhrZW2jFD+RXYM1BrvmZRjbAoIBBwy4
509iFJpuDfytJfz1MWtaL5DqEL/kmiZYAXl6hifNhGu5GAipVIIGsDqEYW4i+VC15aa
5107kOCwz/I5zsB3vSDW96IRs4wXtqEZSibc2W/bqfVi+xcvPPl1ZhQ2EAwa4D/x035
511kyf20ffWOU+1yf2cnijzqs3IzlveUm+meLw5s3Rc+iG7DPWWeCoe1hVwANI1euNc
512pqKwKY905yFyjOje2OgiEU2kS4YME4zGeBys8yo7E42hNnN2EPK6xkkUqzdudLLQ
5138OUlKRTc8AbIf3XG1rpA4VUpTv3hhxGGwCRy6If8zgZQsNYchgNztRGk72Gcb8Dm
514vFSEN3ZtwxU64G3YZzntdcr2WPzxAoIBBw30g6Fgdb/gmVnOpL0//T0ePNDKIMPs
515jVJLaRduhoZgB1Bb9qPUPX0SzRzLZtg1tkZSDjBDoHmOHJfhxUaXt+FLCPPbrE4t
516+nq9n/nBaMM779w9ClqhqLOyGrwKoxjSmhi+TVEHyIxCbXMvPHVHfX9WzxjbcGrN
517ZvRaEVZWo+QlIX8yqdSwqxLk1WtAIRzvlcj7NKum8xBxPed6BNFep/PtgIAmoLT5
518L8wb7EWb2iUdc2KbZ4OaY51lDScqpATgXu3WjXfM+Q52G0mX6Wyd0cjlL711Zrjb
519yLbiueZT94lgIHHRRKtKc8CEqcjkQV5OzABS3P/gQSfgZXBdLKjOpTnKDUq7IBeH
520AoIBBweAOEIAPLQg1QRUrr3xRrYKRwlakgZDii9wJt1l5AgBTICzbTA1vzDJ1JM5
521AqSpCV6w9JWyYVcXK+HLdKBRZLaPPNEQDJ5lOxD6uMziWGl2rg8tj+1xNMWfxiPz
522aTCjoe4EoBUMoTq2gwzRcM2usEQNikXVhnj9Wzaivsaeb4bJ3GRPW5DkrO6JSEtT
523w+gvyMqQM2Hy5k7E7BT46sXVwaj/jZxuqGnebRixXtnp0WixdRIqYWUr1UqLf6hQ
524G7WP2BgoxCMaCmNW8+HMD/xuxucEotoIhZ+GgJKBFoNnjl3BX+qxYdSe9RbL/5Tr
5254It6Jxtj8uETJXEbv9Cg6v1agWPS9YY8RLTBAoIBBwrU2AsAUts6h1LgGLKK3UWZ
526oLH5E+4o+7HqSGRcRodVeN9NBXIYdHHOLeEG6YNGJiJ3bFP5ZQEu9iDsyoFVKJ9O
527Mw/y6dKZuxOCZ+X8FopSROg3yWfdOpAm6cnQZp3WqLNX4n/Q6WvKojfyEiPphjwT
5280ymrUJELXLWJmjUyPoAk6HgC0Gs28ZnEXbyhx7CSbZNFyCU/PNUDZwto3GisIPD3
529le7YjqHugezmjMGlA0sDw5aCXjfbl74vowRFYMO6e3ItApfSRgNV86CDoX74WI/5
530AYU/QVM4wGt8XGT2KwDFJaxYGKsGDMWmXY04dS+WPuetCbouWUusyFwRb9SzFave
531vYeU7Ab/
Alex Gaynore7f51982016-09-11 11:48:14 -0400532-----END RSA PRIVATE KEY-----"""
Colleen Murphye09399b2016-03-01 17:40:49 -0800533
Paul Kehrer72d968b2016-07-29 15:31:04 +0800534ec_private_key_pem = b"""-----BEGIN PRIVATE KEY-----
535MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgYirTZSx+5O8Y6tlG
536cka6W6btJiocdrdolfcukSoTEk+hRANCAAQkvPNu7Pa1GcsWU4v7ptNfqCJVq8Cx
537zo0MUVPQgwJ3aJtNM1QMOQUayCrRwfklg+D/rFSUwEUqtZh7fJDiFqz3
538-----END PRIVATE KEY-----
539"""
540
Paul Kehrer59d26252017-07-20 10:45:54 +0200541ec_root_key_pem = b"""-----BEGIN EC PRIVATE KEY-----
542MIGlAgEBBDEAz/HOBFPYLB0jLWeTpJn4Yc4m/C4mdWymVHBjOmnwiPHKT326iYN/
543ZhmSs+RM94RsoAcGBSuBBAAioWQDYgAEwE5vDdla/nLpWAPAQ0yFGqwLuw4BcN2r
544U+sKab5EAEHzLeceRa8ffncYdCXNoVsBcdob1y66CFZMEWLetPTmGapyWkBAs6/L
5458kUlkU9OsE+7IVo4QQJkgV5gM+Dim1XE
546-----END EC PRIVATE KEY-----
547"""
548
549ec_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
550MIICLTCCAbKgAwIBAgIMWW/hwTl6ufz6/WkCMAoGCCqGSM49BAMDMFgxGDAWBgNV
551BAMTD1Rlc3RpbmcgUm9vdCBDQTEQMA4GA1UEChMHVGVzdGluZzEQMA4GA1UEBxMH
552Q2hpY2FnbzELMAkGA1UECBMCSUwxCzAJBgNVBAYTAlVTMCAXDTE3MDcxOTIyNDgz
553M1oYDzk5OTkxMjMxMjM1OTU5WjBYMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0Ex
554EDAOBgNVBAoTB1Rlc3RpbmcxEDAOBgNVBAcTB0NoaWNhZ28xCzAJBgNVBAgTAklM
555MQswCQYDVQQGEwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABMBObw3ZWv5y6VgD
556wENMhRqsC7sOAXDdq1PrCmm+RABB8y3nHkWvH353GHQlzaFbAXHaG9cuughWTBFi
5573rT05hmqclpAQLOvy/JFJZFPTrBPuyFaOEECZIFeYDPg4ptVxKNDMEEwDwYDVR0T
558AQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwQAMB0GA1UdDgQWBBSoTrF0H2m8RDzB
559MnY2KReEPfz7ZjAKBggqhkjOPQQDAwNpADBmAjEA3+G1oVCxGjYX4iUN93QYcNHe
560e3fJQJwX9+KsHRut6qNZDUbvRbtO1YIAwB4UJZjwAjEAtXCPURS5A4McZHnSwgTi
561Td8GMrwKz0557OxxtKN6uVVy4ACFMqEw0zN/KJI1vxc9
562-----END CERTIFICATE-----"""
563
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400564
Alex Chanc6077062016-11-18 13:53:39 +0000565@pytest.fixture
566def x509_data():
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400567 """
Alex Chanc6077062016-11-18 13:53:39 +0000568 Create a new private key and start a certificate request (for a test
569 to finish in one way or another).
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400570 """
Alex Chanc6077062016-11-18 13:53:39 +0000571 # Basic setup stuff to generate a certificate
572 pkey = PKey()
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400573 pkey.generate_key(TYPE_RSA, 512)
Alex Chanc6077062016-11-18 13:53:39 +0000574 req = X509Req()
575 req.set_pubkey(pkey)
576 # Authority good you have.
577 req.get_subject().commonName = "Yoda root CA"
578 x509 = X509()
579 subject = x509.get_subject()
580 subject.commonName = req.get_subject().commonName
581 x509.set_issuer(subject)
582 x509.set_pubkey(pkey)
583 now = datetime.now()
584 expire = datetime.now() + timedelta(days=100)
585 x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
586 x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
587 yield pkey, x509
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400588
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400589
Alex Chanc6077062016-11-18 13:53:39 +0000590class TestX509Ext(object):
591 """
592 Tests for `OpenSSL.crypto.X509Extension`.
593 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -0800594
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400595 def test_str(self):
596 """
Alex Chanc6077062016-11-18 13:53:39 +0000597 The string representation of `X509Extension` instances as
598 returned by `str` includes stuff.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400599 """
600 # This isn't necessarily the best string representation. Perhaps it
601 # will be changed/improved in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000602 assert (
603 str(X509Extension(b'basicConstraints', True, b'CA:false')) ==
604 'CA:FALSE'
605 )
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400606
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400607 def test_type(self):
608 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500609 `X509Extension` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400610 """
Alex Chanc6077062016-11-18 13:53:39 +0000611 assert is_consistent_type(
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400612 X509Extension,
Alex Gaynore7f51982016-09-11 11:48:14 -0400613 'X509Extension', b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400614
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500615 def test_construction(self):
616 """
Alex Chanc6077062016-11-18 13:53:39 +0000617 `X509Extension` accepts an extension type name, a critical flag,
Alex Gaynor01f90a12019-02-07 09:14:48 -0500618 and an extension value and returns an `X509Extension` instance.
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500619 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400620 basic = X509Extension(b'basicConstraints', True, b'CA:true')
Alex Gaynor01f90a12019-02-07 09:14:48 -0500621 assert isinstance(basic, X509Extension)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500622
Alex Chanc6077062016-11-18 13:53:39 +0000623 comment = X509Extension(b'nsComment', False, b'pyOpenSSL unit test')
Alex Gaynor01f90a12019-02-07 09:14:48 -0500624 assert isinstance(comment, X509Extension)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500625
Alex Chanc6077062016-11-18 13:53:39 +0000626 @pytest.mark.parametrize('type_name, critical, value', [
627 (b'thisIsMadeUp', False, b'hi'),
628 (b'basicConstraints', False, b'blah blah'),
Jean-Paul Calderone391585f2008-12-31 14:36:31 -0500629
Jean-Paul Calderone2ee1e7c2008-12-31 14:58:38 -0500630 # Exercise a weird one (an extension which uses the r2i method). This
631 # exercises the codepath that requires a non-NULL ctx to be passed to
632 # X509V3_EXT_nconf. It can't work now because we provide no
633 # configuration database. It might be made to work in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000634 (b'proxyCertInfo', True,
635 b'language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')
636 ])
637 def test_invalid_extension(self, type_name, critical, value):
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500638 """
Alex Chanc6077062016-11-18 13:53:39 +0000639 `X509Extension` raises something if it is passed a bad
640 extension name or value.
641 """
642 with pytest.raises(Error):
643 X509Extension(type_name, critical, value)
644
645 @pytest.mark.parametrize('critical_flag', [True, False])
646 def test_get_critical(self, critical_flag):
647 """
648 `X509ExtensionType.get_critical` returns the value of the
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500649 extension's critical flag.
650 """
Alex Chanc6077062016-11-18 13:53:39 +0000651 ext = X509Extension(b'basicConstraints', critical_flag, b'CA:true')
652 assert ext.get_critical() == critical_flag
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500653
Alex Chanc6077062016-11-18 13:53:39 +0000654 @pytest.mark.parametrize('short_name, value', [
655 (b'basicConstraints', b'CA:true'),
656 (b'nsComment', b'foo bar'),
657 ])
658 def test_get_short_name(self, short_name, value):
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500659 """
Alex Chanc6077062016-11-18 13:53:39 +0000660 `X509ExtensionType.get_short_name` returns a string giving the
Alex Gaynor31287502015-09-05 16:11:27 -0400661 short type name of the extension.
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500662 """
Alex Chanc6077062016-11-18 13:53:39 +0000663 ext = X509Extension(short_name, True, value)
664 assert ext.get_short_name() == short_name
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500665
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400666 def test_get_data(self):
667 """
Alex Chanc6077062016-11-18 13:53:39 +0000668 `X509Extension.get_data` returns a string giving the data of
Alex Gaynor31287502015-09-05 16:11:27 -0400669 the extension.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400670 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400671 ext = X509Extension(b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400672 # Expect to get back the DER encoded form of CA:true.
Alex Chanc6077062016-11-18 13:53:39 +0000673 assert ext.get_data() == b'0\x03\x01\x01\xff'
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400674
Alex Chanc6077062016-11-18 13:53:39 +0000675 def test_unused_subject(self, x509_data):
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400676 """
Alex Chanc6077062016-11-18 13:53:39 +0000677 The `subject` parameter to `X509Extension` may be provided for an
678 extension which does not use it and is ignored in this case.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400679 """
Alex Chanc6077062016-11-18 13:53:39 +0000680 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400681 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000682 b'basicConstraints', False, b'CA:TRUE', subject=x509)
683 x509.add_extensions([ext1])
684 x509.sign(pkey, 'sha1')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400685 # This is a little lame. Can we think of a better way?
Alex Chanc6077062016-11-18 13:53:39 +0000686 text = dump_certificate(FILETYPE_TEXT, x509)
687 assert b'X509v3 Basic Constraints:' in text
688 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400689
Alex Chanc6077062016-11-18 13:53:39 +0000690 def test_subject(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400691 """
Alex Chanc6077062016-11-18 13:53:39 +0000692 If an extension requires a subject, the `subject` parameter to
693 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400694 """
Alex Chanc6077062016-11-18 13:53:39 +0000695 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400696 ext3 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000697 b'subjectKeyIdentifier', False, b'hash', subject=x509)
698 x509.add_extensions([ext3])
699 x509.sign(pkey, 'sha1')
700 text = dump_certificate(FILETYPE_TEXT, x509)
701 assert b'X509v3 Subject Key Identifier:' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400702
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400703 def test_missing_subject(self):
704 """
Alex Chanc6077062016-11-18 13:53:39 +0000705 If an extension requires a subject and the `subject` parameter
Alex Gaynor31287502015-09-05 16:11:27 -0400706 is given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400707 """
Alex Chanc6077062016-11-18 13:53:39 +0000708 with pytest.raises(Error):
709 X509Extension(b'subjectKeyIdentifier', False, b'hash')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400710
Alex Chanc6077062016-11-18 13:53:39 +0000711 @pytest.mark.parametrize('bad_obj', [
712 True,
713 object(),
714 "hello",
715 [],
716 ])
717 def test_invalid_subject(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400718 """
Alex Chanc6077062016-11-18 13:53:39 +0000719 If the `subject` parameter is given a value which is not an
720 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400721 """
Alex Chanc6077062016-11-18 13:53:39 +0000722 with pytest.raises(TypeError):
723 X509Extension(
724 'basicConstraints', False, 'CA:TRUE', subject=bad_obj)
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400725
Alex Chanc6077062016-11-18 13:53:39 +0000726 def test_unused_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400727 """
Alex Chanc6077062016-11-18 13:53:39 +0000728 The `issuer` parameter to `X509Extension` may be provided for an
729 extension which does not use it and is ignored in this case.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400730 """
Alex Chanc6077062016-11-18 13:53:39 +0000731 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400732 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000733 b'basicConstraints', False, b'CA:TRUE', issuer=x509)
734 x509.add_extensions([ext1])
735 x509.sign(pkey, 'sha1')
736 text = dump_certificate(FILETYPE_TEXT, x509)
737 assert b'X509v3 Basic Constraints:' in text
738 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400739
Alex Chanc6077062016-11-18 13:53:39 +0000740 def test_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400741 """
Alex Chanc6077062016-11-18 13:53:39 +0000742 If an extension requires an issuer, the `issuer` parameter to
743 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400744 """
Alex Chanc6077062016-11-18 13:53:39 +0000745 pkey, x509 = x509_data
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400746 ext2 = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -0400747 b'authorityKeyIdentifier', False, b'issuer:always',
Alex Chanc6077062016-11-18 13:53:39 +0000748 issuer=x509)
749 x509.add_extensions([ext2])
750 x509.sign(pkey, 'sha1')
751 text = dump_certificate(FILETYPE_TEXT, x509)
752 assert b'X509v3 Authority Key Identifier:' in text
753 assert b'DirName:/CN=Yoda root CA' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400754
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400755 def test_missing_issuer(self):
756 """
Alex Chanc6077062016-11-18 13:53:39 +0000757 If an extension requires an issue and the `issuer` parameter is
758 given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400759 """
Alex Chanc6077062016-11-18 13:53:39 +0000760 with pytest.raises(Error):
761 X509Extension(
762 b'authorityKeyIdentifier',
763 False, b'keyid:always,issuer:always')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400764
Alex Chanc6077062016-11-18 13:53:39 +0000765 @pytest.mark.parametrize('bad_obj', [
766 True,
767 object(),
768 "hello",
769 [],
770 ])
771 def test_invalid_issuer(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400772 """
Alex Chanc6077062016-11-18 13:53:39 +0000773 If the `issuer` parameter is given a value which is not an
774 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400775 """
Alex Chanc6077062016-11-18 13:53:39 +0000776 with pytest.raises(TypeError):
777 X509Extension(
778 'basicConstraints', False, 'keyid:always,issuer:always',
779 issuer=bad_obj)
Rick Dean47262da2009-07-08 16:17:17 -0500780
781
Paul Kehrer72d968b2016-07-29 15:31:04 +0800782class TestPKey(object):
783 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +0100784 Tests for `OpenSSL.crypto.PKey`.
Paul Kehrer72d968b2016-07-29 15:31:04 +0800785 """
786
787 def test_convert_from_cryptography_private_key(self):
788 """
789 PKey.from_cryptography_key creates a proper private PKey.
790 """
791 key = serialization.load_pem_private_key(
792 intermediate_key_pem, None, backend
793 )
794 pkey = PKey.from_cryptography_key(key)
795
796 assert isinstance(pkey, PKey)
797 assert pkey.bits() == key.key_size
798 assert pkey._only_public is False
799 assert pkey._initialized is True
800
801 def test_convert_from_cryptography_public_key(self):
802 """
803 PKey.from_cryptography_key creates a proper public PKey.
804 """
805 key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
806 pkey = PKey.from_cryptography_key(key)
807
808 assert isinstance(pkey, PKey)
809 assert pkey.bits() == key.key_size
810 assert pkey._only_public is True
811 assert pkey._initialized is True
812
813 def test_convert_from_cryptography_unsupported_type(self):
814 """
815 PKey.from_cryptography_key raises TypeError with an unsupported type.
816 """
817 key = serialization.load_pem_private_key(
818 ec_private_key_pem, None, backend
819 )
820 with pytest.raises(TypeError):
821 PKey.from_cryptography_key(key)
822
823 def test_convert_public_pkey_to_cryptography_key(self):
824 """
825 PKey.to_cryptography_key creates a proper cryptography public key.
826 """
827 pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
828 key = pkey.to_cryptography_key()
829
830 assert isinstance(key, rsa.RSAPublicKey)
831 assert pkey.bits() == key.key_size
832
833 def test_convert_private_pkey_to_cryptography_key(self):
834 """
835 PKey.to_cryptography_key creates a proper cryptography private key.
836 """
837 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
838 key = pkey.to_cryptography_key()
839
840 assert isinstance(key, rsa.RSAPrivateKey)
841 assert pkey.bits() == key.key_size
842
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400843 def test_type(self):
844 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500845 `PKey` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400846 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000847 assert is_consistent_type(PKey, 'PKey')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400848
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500849 def test_construction(self):
850 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000851 `PKey` takes no arguments and returns a new `PKey` instance.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500852 """
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500853 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000854 assert isinstance(key, PKey)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500855
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500856 def test_pregeneration(self):
857 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000858 `PKey.bits` and `PKey.type` return `0` before the key is generated.
859 `PKey.check` raises `TypeError` before the key is generated.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500860 """
861 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000862 assert key.type() == 0
863 assert key.bits() == 0
864 with pytest.raises(TypeError):
865 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500866
Alex Chan9e2a9932017-01-25 14:29:19 +0000867 def test_failed_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500868 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000869 `PKey.generate_key` takes two arguments, the first giving the key type
870 as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
871 bits to generate. If an invalid type is specified or generation fails,
872 `Error` is raised. If an invalid number of bits is specified,
873 `ValueError` or `Error` is raised.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500874 """
875 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000876 with pytest.raises(TypeError):
877 key.generate_key("foo", "bar")
878 with pytest.raises(Error):
879 key.generate_key(-1, 0)
Jean-Paul Calderoneab82db72008-03-06 00:09:31 -0500880
Alex Chan9e2a9932017-01-25 14:29:19 +0000881 with pytest.raises(ValueError):
882 key.generate_key(TYPE_RSA, -1)
883 with pytest.raises(ValueError):
884 key.generate_key(TYPE_RSA, 0)
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500885
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400886 with pytest.raises(TypeError):
887 key.generate_key(TYPE_RSA, object())
888
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500889 # XXX RSA generation for small values of bits is fairly buggy in a wide
890 # range of OpenSSL versions. I need to figure out what the safe lower
891 # bound for a reasonable number of OpenSSL versions is and explicitly
892 # check for that in the wrapper. The failure behavior is typically an
893 # infinite loop inside OpenSSL.
894
Alex Chan9e2a9932017-01-25 14:29:19 +0000895 # with pytest.raises(Error):
896 # key.generate_key(TYPE_RSA, 2)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500897
898 # XXX DSA generation seems happy with any number of bits. The DSS
899 # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
900 # generator doesn't seem to care about the upper limit at all. For
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500901 # the lower limit, it uses 512 if anything smaller is specified.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500902 # So, it doesn't seem possible to make generate_key fail for
903 # TYPE_DSA with a bits argument which is at least an int.
904
Alex Chan9e2a9932017-01-25 14:29:19 +0000905 # with pytest.raises(Error):
906 # key.generate_key(TYPE_DSA, -7)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500907
Alex Chan9e2a9932017-01-25 14:29:19 +0000908 def test_rsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500909 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000910 `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
911 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500912 """
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400913 bits = 512
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500914 key = PKey()
915 key.generate_key(TYPE_RSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000916 assert key.type() == TYPE_RSA
917 assert key.bits() == bits
918 assert key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500919
Alex Chan9e2a9932017-01-25 14:29:19 +0000920 def test_dsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500921 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000922 `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
923 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500924 """
925 # 512 is a magic number. The DSS (Digital Signature Standard)
926 # allows a minimum of 512 bits for DSA. DSA_generate_parameters
927 # will silently promote any value below 512 to 512.
928 bits = 512
929 key = PKey()
930 key.generate_key(TYPE_DSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000931 assert key.type() == TYPE_DSA
932 assert key.bits() == bits
933 with pytest.raises(TypeError):
934 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500935
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500936 def test_regeneration(self):
937 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000938 `PKey.generate_key` can be called multiple times on the same key to
939 generate new keys.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500940 """
941 key = PKey()
942 for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
Alex Gaynor7f636492015-09-04 13:26:52 -0400943 key.generate_key(type, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000944 assert key.type() == type
945 assert key.bits() == bits
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500946
Alex Chan9e2a9932017-01-25 14:29:19 +0000947 def test_inconsistent_key(self):
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400948 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000949 `PKey.check` returns `Error` if the key is not consistent.
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400950 """
951 key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
Alex Chan9e2a9932017-01-25 14:29:19 +0000952 with pytest.raises(Error):
953 key.check()
Jean-Paul Calderonee81020e2011-06-12 21:48:57 -0400954
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400955 def test_check_public_key(self):
956 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000957 `PKey.check` raises `TypeError` if only the public part of the key
958 is available.
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400959 """
960 # A trick to get a public-only key
961 key = PKey()
962 key.generate_key(TYPE_RSA, 512)
963 cert = X509()
964 cert.set_pubkey(key)
965 pub = cert.get_pubkey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000966 with pytest.raises(TypeError):
967 pub.check()
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400968
969
Alex Chan9e2a9932017-01-25 14:29:19 +0000970def x509_name(**attrs):
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500971 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000972 Return a new X509Name with the given attributes.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500973 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000974 # XXX There's no other way to get a new X509Name yet.
975 name = X509().get_subject()
976 attrs = list(attrs.items())
Alex Gaynoraceb3e22015-09-05 12:00:22 -0400977
Alex Chan9e2a9932017-01-25 14:29:19 +0000978 # Make the order stable - order matters!
979 def key(attr):
980 return attr[1]
981 attrs.sort(key=key)
982 for k, v in attrs:
983 setattr(name, k, v)
984 return name
Alex Gaynor85b49702015-09-05 16:30:59 -0400985
Alex Chan9e2a9932017-01-25 14:29:19 +0000986
987class TestX509Name(object):
988 """
989 Unit tests for `OpenSSL.crypto.X509Name`.
990 """
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -0500991
Rick Deane15b1472009-07-09 15:53:42 -0500992 def test_type(self):
993 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500994 The type of X509Name objects is `X509Name`.
Rick Deane15b1472009-07-09 15:53:42 -0500995 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000996 name = x509_name()
Alex Gaynor01f90a12019-02-07 09:14:48 -0500997 assert isinstance(name, X509Name)
Rick Deane15b1472009-07-09 15:53:42 -0500998
Alex Chan9e2a9932017-01-25 14:29:19 +0000999 def test_only_string_attributes(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001000 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001001 Attempting to set a non-`str` attribute name on an `X509Name` instance
1002 causes `TypeError` to be raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001003 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001004 name = x509_name()
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001005 # Beyond these cases, you may also think that unicode should be
Alex Gaynor31287502015-09-05 16:11:27 -04001006 # rejected. Sorry, you're wrong. unicode is automatically converted
1007 # to str outside of the control of X509Name, so there's no way to
1008 # reject it.
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -08001009
Alex Gaynor31287502015-09-05 16:11:27 -04001010 # Also, this used to test str subclasses, but that test is less
1011 # relevant now that the implementation is in Python instead of C. Also
1012 # PyPy automatically converts str subclasses to str when they are
1013 # passed to setattr, so we can't test it on PyPy. Apparently CPython
1014 # does this sometimes as well.
Alex Chan9e2a9932017-01-25 14:29:19 +00001015 with pytest.raises(TypeError):
1016 setattr(name, None, "hello")
1017 with pytest.raises(TypeError):
1018 setattr(name, 30, "hello")
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001019
Alex Chan9e2a9932017-01-25 14:29:19 +00001020 def test_set_invalid_attribute(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001021 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001022 Attempting to set any attribute name on an `X509Name` instance for
1023 which no corresponding NID is defined causes `AttributeError` to be
1024 raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001025 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001026 name = x509_name()
1027 with pytest.raises(AttributeError):
1028 setattr(name, "no such thing", None)
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001029
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001030 def test_attributes(self):
1031 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001032 `X509Name` instances have attributes for each standard (?)
1033 X509Name field.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001034 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001035 name = x509_name()
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001036 name.commonName = "foo"
Alex Gaynor37726112016-07-04 09:51:32 -04001037 assert name.commonName == "foo"
1038 assert name.CN == "foo"
1039
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001040 name.CN = "baz"
Alex Gaynor37726112016-07-04 09:51:32 -04001041 assert name.commonName == "baz"
1042 assert name.CN == "baz"
1043
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001044 name.commonName = "bar"
Alex Gaynor37726112016-07-04 09:51:32 -04001045 assert name.commonName == "bar"
1046 assert name.CN == "bar"
1047
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001048 name.CN = "quux"
Alex Gaynor37726112016-07-04 09:51:32 -04001049 assert name.commonName == "quux"
1050 assert name.CN == "quux"
1051
1052 assert name.OU is None
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001053
Alex Gaynor7778e792016-07-03 23:38:48 -04001054 with pytest.raises(AttributeError):
1055 name.foobar
1056
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001057 def test_copy(self):
1058 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001059 `X509Name` creates a new `X509Name` instance with all the same
1060 attributes as an existing `X509Name` instance when called with one.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001061 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001062 name = x509_name(commonName="foo", emailAddress="bar@example.com")
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001063
1064 copy = X509Name(name)
Alex Chan9e2a9932017-01-25 14:29:19 +00001065 assert copy.commonName == "foo"
1066 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001067
1068 # Mutate the copy and ensure the original is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001069 copy.commonName = "baz"
Alex Chan9e2a9932017-01-25 14:29:19 +00001070 assert name.commonName == "foo"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001071
1072 # Mutate the original and ensure the copy is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001073 name.emailAddress = "quux@example.com"
Alex Chan9e2a9932017-01-25 14:29:19 +00001074 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001075
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001076 def test_repr(self):
1077 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001078 `repr` passed an `X509Name` instance should return a string containing
1079 a description of the type and the NIDs which have been set on it.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001080 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001081 name = x509_name(commonName="foo", emailAddress="bar")
1082 assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001083
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001084 def test_comparison(self):
1085 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001086 `X509Name` instances should compare based on their NIDs.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001087 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001088 def _equality(a, b, assert_true, assert_false):
1089 assert_true(a == b)
1090 assert_false(a != b)
1091 assert_true(b == a)
1092 assert_false(b != a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001093
Alex Chan9e2a9932017-01-25 14:29:19 +00001094 def assert_true(x):
1095 assert x
1096
1097 def assert_false(x):
1098 assert not x
1099
1100 def assert_equal(a, b):
1101 _equality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001102
1103 # Instances compare equal to themselves.
Alex Chan9e2a9932017-01-25 14:29:19 +00001104 name = x509_name()
1105 assert_equal(name, name)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001106
1107 # Empty instances should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001108 assert_equal(x509_name(), x509_name())
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001109
1110 # Instances with equal NIDs should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001111 assert_equal(x509_name(commonName="foo"),
1112 x509_name(commonName="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001113
1114 # Instance with equal NIDs set using different aliases should compare
1115 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001116 assert_equal(x509_name(commonName="foo"),
1117 x509_name(CN="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001118
1119 # Instances with more than one NID with the same values should compare
1120 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001121 assert_equal(x509_name(CN="foo", organizationalUnitName="bar"),
1122 x509_name(commonName="foo", OU="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001123
Alex Chan9e2a9932017-01-25 14:29:19 +00001124 def assert_not_equal(a, b):
1125 _equality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001126
1127 # Instances with different values for the same NID should not compare
1128 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001129 assert_not_equal(x509_name(CN="foo"),
1130 x509_name(CN="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001131
1132 # Instances with different NIDs should not compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001133 assert_not_equal(x509_name(CN="foo"),
1134 x509_name(OU="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001135
Alex Chan9e2a9932017-01-25 14:29:19 +00001136 assert_not_equal(x509_name(), object())
Alex Gaynor7778e792016-07-03 23:38:48 -04001137
Alex Chan9e2a9932017-01-25 14:29:19 +00001138 def _inequality(a, b, assert_true, assert_false):
1139 assert_true(a < b)
1140 assert_true(a <= b)
1141 assert_true(b > a)
1142 assert_true(b >= a)
1143 assert_false(a > b)
1144 assert_false(a >= b)
1145 assert_false(b < a)
1146 assert_false(b <= a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001147
Alex Chan9e2a9932017-01-25 14:29:19 +00001148 def assert_less_than(a, b):
1149 _inequality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001150
1151 # An X509Name with a NID with a value which sorts less than the value
1152 # of the same NID on another X509Name compares less than the other
1153 # X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001154 assert_less_than(x509_name(CN="abc"),
1155 x509_name(CN="def"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001156
Alex Chan9e2a9932017-01-25 14:29:19 +00001157 def assert_greater_than(a, b):
1158 _inequality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001159
1160 # An X509Name with a NID with a value which sorts greater than the
1161 # value of the same NID on another X509Name compares greater than the
1162 # other X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001163 assert_greater_than(x509_name(CN="def"),
1164 x509_name(CN="abc"))
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001165
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001166 def test_hash(self):
1167 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001168 `X509Name.hash` returns an integer hash based on the value of the name.
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001169 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001170 a = x509_name(CN="foo")
1171 b = x509_name(CN="foo")
1172 assert a.hash() == b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001173 a.CN = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001174 assert a.hash() != b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001175
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001176 def test_der(self):
1177 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001178 `X509Name.der` returns the DER encoded form of the name.
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001179 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001180 a = x509_name(CN="foo", C="US")
1181 assert (a.der() ==
1182 b'0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
1183 b'1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo')
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001184
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001185 def test_get_components(self):
1186 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001187 `X509Name.get_components` returns a `list` of two-tuples of `str`
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001188 giving the NIDs and associated values which make up the name.
1189 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001190 a = x509_name()
1191 assert a.get_components() == []
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001192 a.CN = "foo"
Alex Chan9e2a9932017-01-25 14:29:19 +00001193 assert a.get_components() == [(b"CN", b"foo")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001194 a.organizationalUnitName = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001195 assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001196
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001197 def test_load_nul_byte_attribute(self):
1198 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001199 An `X509Name` from an `X509` instance loaded from a file can have a
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001200 NUL byte in the value of one of its attributes.
1201 """
1202 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1203 subject = cert.get_subject()
Alex Chan9e2a9932017-01-25 14:29:19 +00001204 assert "null.python.org\x00example.org" == subject.commonName
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001205
Romuald Brunet4183beb2019-01-21 19:38:33 +01001206 def test_load_nul_byte_components(self):
1207 """
1208 An `X509Name` from an `X509` instance loaded from a file can have a
1209 NUL byte in the value of its components
1210 """
1211 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1212 subject = cert.get_subject()
1213 components = subject.get_components()
1214 ccn = [value for name, value in components if name == b'CN']
1215 assert ccn[0] == b'null.python.org\x00example.org'
1216
Alex Chan9e2a9932017-01-25 14:29:19 +00001217 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001218 """
1219 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001220 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001221 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001222 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001223 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001224 with pytest.raises(Error):
1225 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001226
1227
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001228class _PKeyInteractionTestsMixin:
1229 """
1230 Tests which involve another thing and a PKey.
1231 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001232
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001233 def signable(self):
1234 """
Alex Chanfb078d82017-04-20 11:16:15 +01001235 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001236 """
1237 raise NotImplementedError()
1238
Alex Chanb00ede22017-01-30 07:24:40 +00001239 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001240 """
Alex Chanb00ede22017-01-30 07:24:40 +00001241 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001242 """
1243 request = self.signable()
1244 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001245 with pytest.raises(ValueError):
1246 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001247
Alex Chanb00ede22017-01-30 07:24:40 +00001248 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001249 """
Alex Chanb00ede22017-01-30 07:24:40 +00001250 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1251 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001252 """
1253 request = self.signable()
1254 key = PKey()
1255 key.generate_key(TYPE_RSA, 512)
1256 request.set_pubkey(key)
1257 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001258 with pytest.raises(ValueError):
1259 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001260
Alex Chanb00ede22017-01-30 07:24:40 +00001261 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001262 """
Alex Chanb00ede22017-01-30 07:24:40 +00001263 `X509Req.sign` raises `ValueError` when passed a digest name which is
1264 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001265 """
1266 request = self.signable()
1267 key = PKey()
1268 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001269 with pytest.raises(ValueError):
1270 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001271
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001272 def test_sign(self):
1273 """
Alex Chanb00ede22017-01-30 07:24:40 +00001274 `X509Req.sign` succeeds when passed a private key object and a
1275 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001276 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001277 """
1278 request = self.signable()
1279 key = PKey()
1280 key.generate_key(TYPE_RSA, 512)
1281 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001282 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001283 # If the type has a verify method, cover that too.
1284 if getattr(request, 'verify', None) is not None:
1285 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001286 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001287 # Make another key that won't verify.
1288 key = PKey()
1289 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001290 with pytest.raises(Error):
1291 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001292
1293
Alex Chanb00ede22017-01-30 07:24:40 +00001294class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001295 """
Alex Chanb00ede22017-01-30 07:24:40 +00001296 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001297 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001298
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001299 def signable(self):
1300 """
Alex Chanb00ede22017-01-30 07:24:40 +00001301 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001302 """
1303 return X509Req()
1304
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001305 def test_type(self):
1306 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001307 `X509Req` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001308 """
Alex Chanb00ede22017-01-30 07:24:40 +00001309 assert is_consistent_type(X509Req, 'X509Req')
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001310
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001311 def test_construction(self):
1312 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001313 `X509Req` takes no arguments and returns an `X509Req` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001314 """
1315 request = X509Req()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001316 assert isinstance(request, X509Req)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001317
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001318 def test_version(self):
1319 """
Alex Chanb00ede22017-01-30 07:24:40 +00001320 `X509Req.set_version` sets the X.509 version of the certificate
1321 request. `X509Req.get_version` returns the X.509 version of the
1322 certificate request. The initial value of the version is 0.
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001323 """
1324 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001325 assert request.get_version() == 0
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001326 request.set_version(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001327 assert request.get_version() == 1
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001328 request.set_version(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001329 assert request.get_version() == 3
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001330
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001331 def test_version_wrong_args(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001332 """
Alex Chanb00ede22017-01-30 07:24:40 +00001333 `X509Req.set_version` raises `TypeError` if called with a non-`int`
1334 argument.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001335 """
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001336 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001337 with pytest.raises(TypeError):
1338 request.set_version("foo")
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001339
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001340 def test_get_subject(self):
1341 """
Alex Chanb00ede22017-01-30 07:24:40 +00001342 `X509Req.get_subject` returns an `X509Name` for the subject of the
1343 request and which is valid even after the request object is
1344 otherwise dead.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001345 """
1346 request = X509Req()
1347 subject = request.get_subject()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001348 assert isinstance(subject, X509Name)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001349 subject.commonName = "foo"
Alex Chanb00ede22017-01-30 07:24:40 +00001350 assert request.get_subject().commonName == "foo"
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001351 del request
1352 subject.commonName = "bar"
Alex Chanb00ede22017-01-30 07:24:40 +00001353 assert subject.commonName == "bar"
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001354
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001355 def test_add_extensions(self):
1356 """
Alex Chanb00ede22017-01-30 07:24:40 +00001357 `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
1358 and adds them to the X509 request.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001359 """
1360 request = X509Req()
1361 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001362 X509Extension(b'basicConstraints', True, b'CA:false')])
Stephen Holsappleca545b72014-01-28 21:43:25 -08001363 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001364 assert len(exts) == 1
1365 assert exts[0].get_short_name() == b'basicConstraints'
1366 assert exts[0].get_critical() == 1
1367 assert exts[0].get_data() == b'0\x00'
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001368
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001369 def test_get_extensions(self):
1370 """
Alex Chanb00ede22017-01-30 07:24:40 +00001371 `X509Req.get_extensions` returns a `list` of extensions added to this
1372 X509 request.
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001373 """
1374 request = X509Req()
1375 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001376 assert exts == []
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001377 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001378 X509Extension(b'basicConstraints', True, b'CA:true'),
1379 X509Extension(b'keyUsage', False, b'digitalSignature')])
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001380 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001381 assert len(exts) == 2
1382 assert exts[0].get_short_name() == b'basicConstraints'
1383 assert exts[0].get_critical() == 1
1384 assert exts[0].get_data() == b'0\x03\x01\x01\xff'
1385 assert exts[1].get_short_name() == b'keyUsage'
1386 assert exts[1].get_critical() == 0
1387 assert exts[1].get_data() == b'\x03\x02\x07\x80'
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001388
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001389 def test_add_extensions_wrong_args(self):
1390 """
Alex Chanb00ede22017-01-30 07:24:40 +00001391 `X509Req.add_extensions` raises `TypeError` if called with a
1392 non-`list`. Or it raises `ValueError` if called with a `list`
1393 containing objects other than `X509Extension` instances.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001394 """
1395 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001396 with pytest.raises(TypeError):
1397 request.add_extensions(object())
1398 with pytest.raises(ValueError):
1399 request.add_extensions([object()])
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001400
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001401 def test_verify_wrong_args(self):
1402 """
Alex Chanb00ede22017-01-30 07:24:40 +00001403 `X509Req.verify` raises `TypeError` if passed anything other than a
1404 `PKey` instance as its single argument.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001405 """
1406 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001407 with pytest.raises(TypeError):
1408 request.verify(object())
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001409
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001410 def test_verify_uninitialized_key(self):
1411 """
Alex Chanb00ede22017-01-30 07:24:40 +00001412 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1413 `OpenSSL.crypto.PKey` which contains no key data.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001414 """
1415 request = X509Req()
1416 pkey = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001417 with pytest.raises(Error):
1418 request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001419
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001420 def test_verify_wrong_key(self):
1421 """
Alex Chanb00ede22017-01-30 07:24:40 +00001422 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1423 `OpenSSL.crypto.PKey` which does not represent the public part of the
Alex Gaynor31287502015-09-05 16:11:27 -04001424 key which signed the request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001425 """
1426 request = X509Req()
1427 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001428 request.sign(pkey, GOOD_DIGEST)
Alex Chanb00ede22017-01-30 07:24:40 +00001429 another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
1430 with pytest.raises(Error):
1431 request.verify(another_pkey)
1432
1433 def test_verify_success(self):
1434 """
1435 `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
1436 which represents the public part of the key which signed the request.
1437 """
1438 request = X509Req()
1439 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
1440 request.sign(pkey, GOOD_DIGEST)
1441 assert request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001442
Paul Kehrer41c10242017-06-29 18:24:17 -05001443 def test_convert_from_cryptography(self):
1444 crypto_req = x509.load_pem_x509_csr(
1445 cleartextCertificateRequestPEM, backend
1446 )
1447 req = X509Req.from_cryptography(crypto_req)
1448 assert isinstance(req, X509Req)
1449
1450 def test_convert_from_cryptography_unsupported_type(self):
1451 with pytest.raises(TypeError):
1452 X509Req.from_cryptography(object())
1453
1454 def test_convert_to_cryptography_key(self):
1455 req = load_certificate_request(
1456 FILETYPE_PEM, cleartextCertificateRequestPEM
1457 )
1458 crypto_req = req.to_cryptography()
1459 assert isinstance(crypto_req, x509.CertificateSigningRequest)
1460
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001461
Alex Chanb00ede22017-01-30 07:24:40 +00001462class TestX509(_PKeyInteractionTestsMixin):
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001463 """
Alex Chanb00ede22017-01-30 07:24:40 +00001464 Tests for `OpenSSL.crypto.X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001465 """
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001466 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Jean-Paul Calderone8114b452008-03-25 15:27:59 -04001467
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001468 extpem = """
1469-----BEGIN CERTIFICATE-----
1470MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
1471BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
1472eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
1473MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
1474aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
1475hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
1476Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
1477zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
1478hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
1479TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
148003HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
1481MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
1482b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
1483MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
1484uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
1485WpOdIpB8KksUTCzV591Nr1wd
1486-----END CERTIFICATE-----
1487 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001488
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001489 def signable(self):
1490 """
Alex Chanb00ede22017-01-30 07:24:40 +00001491 Create and return a new `X509`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001492 """
1493 return X509()
1494
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001495 def test_type(self):
1496 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001497 `X509` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001498 """
Alex Chanb00ede22017-01-30 07:24:40 +00001499 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001500
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001501 def test_construction(self):
1502 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001503 `X509` takes no arguments and returns an instance of `X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001504 """
1505 certificate = X509()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001506 assert isinstance(certificate, X509)
Alex Chanb00ede22017-01-30 07:24:40 +00001507 assert type(certificate).__name__ == 'X509'
Alex Chanb00ede22017-01-30 07:24:40 +00001508 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001510 def test_set_version_wrong_args(self):
1511 """
Alex Chanb00ede22017-01-30 07:24:40 +00001512 `X509.set_version` raises `TypeError` if invoked with an argument
1513 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001514 """
1515 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001516 with pytest.raises(TypeError):
1517 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001518
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001519 def test_version(self):
1520 """
Alex Chanb00ede22017-01-30 07:24:40 +00001521 `X509.set_version` sets the certificate version number.
1522 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001523 """
1524 cert = X509()
1525 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001526 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001527
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001528 def test_serial_number(self):
1529 """
Alex Chanb00ede22017-01-30 07:24:40 +00001530 The serial number of an `X509` can be retrieved and
1531 modified with `X509.get_serial_number` and
1532 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001533 """
1534 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001535 with pytest.raises(TypeError):
1536 certificate.set_serial_number("1")
1537 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001538 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001539 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001540 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001541 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001542 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001543 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001544 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001545 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001546
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001547 def _setBoundTest(self, which):
1548 """
Alex Chanb00ede22017-01-30 07:24:40 +00001549 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001550 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1551 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001552 """
1553 certificate = X509()
1554 set = getattr(certificate, 'set_not' + which)
1555 get = getattr(certificate, 'get_not' + which)
1556
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001557 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001558 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001559
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001560 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001561 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001562 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001563 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001564
1565 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001566 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001567 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001568 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001569
1570 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001571 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001572 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001573 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001574
1575 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001576 with pytest.raises(ValueError):
1577 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001578
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001579 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001580 with pytest.raises(TypeError):
1581 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001582 with pytest.raises(TypeError):
1583 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001584 with pytest.raises(TypeError):
1585 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001586
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001587 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001588
1589 def test_set_notBefore(self):
1590 """
Alex Chanb00ede22017-01-30 07:24:40 +00001591 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001592 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1593 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001594 """
1595 self._setBoundTest("Before")
1596
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001597 def test_set_notAfter(self):
1598 """
Alex Chanb00ede22017-01-30 07:24:40 +00001599 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001600 GENERALIZEDTIME and sets the end of the certificate's validity period
1601 to it.
1602 """
1603 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001604
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001605 def test_get_notBefore(self):
1606 """
Alex Chanb00ede22017-01-30 07:24:40 +00001607 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001608 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001609 internally.
1610 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001611 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001612 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001613
Rick Dean38a05c82009-07-18 01:41:30 -05001614 def test_get_notAfter(self):
1615 """
Alex Chanb00ede22017-01-30 07:24:40 +00001616 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001617 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001618 internally.
1619 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001620 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001621 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001622
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001623 def test_gmtime_adj_notBefore_wrong_args(self):
1624 """
Alex Chanb00ede22017-01-30 07:24:40 +00001625 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1626 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001627 """
1628 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001629 with pytest.raises(TypeError):
1630 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001631
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001632 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001633 def test_gmtime_adj_notBefore(self):
1634 """
Alex Chanb00ede22017-01-30 07:24:40 +00001635 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1636 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001637 """
1638 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001639 not_before_min = (
1640 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1641 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001642 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001643 not_before = datetime.strptime(
1644 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1645 )
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001646 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001647 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001648
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001649 def test_gmtime_adj_notAfter_wrong_args(self):
1650 """
Alex Chanb00ede22017-01-30 07:24:40 +00001651 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1652 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001653 """
1654 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001655 with pytest.raises(TypeError):
1656 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001657
Alex Gaynor642de6f2017-07-24 00:57:38 -04001658 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001659 def test_gmtime_adj_notAfter(self):
1660 """
Alex Chanb00ede22017-01-30 07:24:40 +00001661 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001662 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001663 """
1664 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001665 not_after_min = (
1666 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1667 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001668 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001669 not_after = datetime.strptime(
1670 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1671 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001672 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001673 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001674
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001675 def test_has_expired(self):
1676 """
Alex Chanb00ede22017-01-30 07:24:40 +00001677 `X509.has_expired` returns `True` if the certificate's not-after time
1678 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001679 """
1680 cert = X509()
1681 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001682 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001683
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001684 def test_has_not_expired(self):
1685 """
Alex Chanb00ede22017-01-30 07:24:40 +00001686 `X509.has_expired` returns `False` if the certificate's not-after time
1687 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001688 """
1689 cert = X509()
1690 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001691 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001692
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001693 def test_root_has_not_expired(self):
1694 """
Alex Chanb00ede22017-01-30 07:24:40 +00001695 `X509.has_expired` returns `False` if the certificate's not-after time
1696 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001697 """
1698 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001699 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001700
Rick Dean38a05c82009-07-18 01:41:30 -05001701 def test_digest(self):
1702 """
Alex Chanb00ede22017-01-30 07:24:40 +00001703 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001704 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001705 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001706 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001707 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001708 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1709 # actually matters to the assertion (ie, another arbitrary, good
1710 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001711 # Digest verified with the command:
1712 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001713 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001714 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001715
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001716 def _extcert(self, pkey, extensions):
1717 cert = X509()
1718 cert.set_pubkey(pkey)
1719 cert.get_subject().commonName = "Unit Tests"
1720 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001721 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001722 cert.set_notBefore(when)
1723 cert.set_notAfter(when)
1724
1725 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001726 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001727 return load_certificate(
1728 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1729
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001730 def test_extension_count(self):
1731 """
Alex Chanb00ede22017-01-30 07:24:40 +00001732 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001733 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001734 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001735 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001736 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1737 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001738 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001739 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001740
1741 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001742 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001743 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001744
1745 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001746 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001747 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001748
1749 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001750 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001751 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001752
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001753 def test_get_extension(self):
1754 """
Alex Chanb00ede22017-01-30 07:24:40 +00001755 `X509.get_extension` takes an integer and returns an
1756 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001757 """
1758 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001759 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1760 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001761 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001762 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001763
1764 cert = self._extcert(pkey, [ca, key, subjectAltName])
1765
1766 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001767 assert isinstance(ext, X509Extension)
1768 assert ext.get_critical()
1769 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001770
1771 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001772 assert isinstance(ext, X509Extension)
1773 assert ext.get_critical()
1774 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001775
1776 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001777 assert isinstance(ext, X509Extension)
1778 assert not ext.get_critical()
1779 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001780
Alex Chanb00ede22017-01-30 07:24:40 +00001781 with pytest.raises(IndexError):
1782 cert.get_extension(-1)
1783 with pytest.raises(IndexError):
1784 cert.get_extension(4)
1785 with pytest.raises(TypeError):
1786 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001787
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001788 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001789 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001790 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001791 bytes and this value is reflected in the string representation of the
1792 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001793 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001794 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001795
1796 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001797 assert ext.get_short_name() == b'subjectAltName'
1798 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001799 b"DNS:altnull.python.org\x00example.com, "
1800 b"email:null@python.org\x00user@example.org, "
1801 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001802 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 -04001803 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001804
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001805 def test_invalid_digest_algorithm(self):
1806 """
Alex Chanb00ede22017-01-30 07:24:40 +00001807 `X509.digest` raises `ValueError` if called with an unrecognized hash
1808 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001809 """
1810 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001811 with pytest.raises(ValueError):
1812 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001813
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001814 def test_get_subject(self):
1815 """
Alex Chanb00ede22017-01-30 07:24:40 +00001816 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001817 """
1818 cert = load_certificate(FILETYPE_PEM, self.pemData)
1819 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001820 assert isinstance(subj, X509Name)
1821 assert (
1822 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001823 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1824 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001825
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001826 def test_set_subject_wrong_args(self):
1827 """
Alex Chanb00ede22017-01-30 07:24:40 +00001828 `X509.set_subject` raises a `TypeError` if called with an argument not
1829 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001830 """
1831 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001832 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001833 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001834
1835 def test_set_subject(self):
1836 """
Alex Chanb00ede22017-01-30 07:24:40 +00001837 `X509.set_subject` changes the subject of the certificate to the one
1838 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001839 """
1840 cert = X509()
1841 name = cert.get_subject()
1842 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001843 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001844 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001845 assert (
1846 cert.get_subject().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001847 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001848
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001849 def test_get_issuer(self):
1850 """
Alex Chanb00ede22017-01-30 07:24:40 +00001851 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001852 """
1853 cert = load_certificate(FILETYPE_PEM, self.pemData)
1854 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001855 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001856 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001857 assert (
1858 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001859 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1860 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001861
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001862 def test_set_issuer_wrong_args(self):
1863 """
Alex Chanb00ede22017-01-30 07:24:40 +00001864 `X509.set_issuer` raises a `TypeError` if called with an argument not
1865 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001866 """
1867 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001868 with pytest.raises(TypeError):
1869 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001870
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001871 def test_set_issuer(self):
1872 """
Alex Chanb00ede22017-01-30 07:24:40 +00001873 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001874 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001875 """
1876 cert = X509()
1877 name = cert.get_issuer()
1878 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001879 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001880 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001881 assert (
1882 cert.get_issuer().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001883 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001884
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001885 def test_get_pubkey_uninitialized(self):
1886 """
Alex Chanb00ede22017-01-30 07:24:40 +00001887 When called on a certificate with no public key, `X509.get_pubkey`
1888 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001889 """
1890 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001891 with pytest.raises(Error):
1892 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001893
Alex Gaynor7778e792016-07-03 23:38:48 -04001894 def test_set_pubkey_wrong_type(self):
1895 """
Alex Chanb00ede22017-01-30 07:24:40 +00001896 `X509.set_pubkey` raises `TypeError` when given an object of the
1897 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001898 """
1899 cert = X509()
1900 with pytest.raises(TypeError):
1901 cert.set_pubkey(object())
1902
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001903 def test_subject_name_hash(self):
1904 """
Alex Chanb00ede22017-01-30 07:24:40 +00001905 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001906 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001907 """
1908 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor4cb05202019-02-02 11:06:41 -05001909 # SHA1
1910 assert cert.subject_name_hash() == 3278919224
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001911
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001912 def test_get_signature_algorithm(self):
1913 """
Alex Chanb00ede22017-01-30 07:24:40 +00001914 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001915 the algorithm used to sign the certificate.
1916 """
1917 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001918 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001919
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001920 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001921 """
Alex Chanb00ede22017-01-30 07:24:40 +00001922 `X509.get_signature_algorithm` raises `ValueError` if the signature
1923 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001924 """
1925 # This certificate has been modified to indicate a bogus OID in the
1926 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001927 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001928-----BEGIN CERTIFICATE-----
1929MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1930EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1931cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1932MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1933EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1934CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1935AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1936+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1937hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1938BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1939FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1940dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1941aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1942MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1943jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1944PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1945tgI5
1946-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001947"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001948 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001949 with pytest.raises(ValueError):
1950 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001951
Alex Gaynor37726112016-07-04 09:51:32 -04001952 def test_sign_bad_pubkey_type(self):
1953 """
Alex Chanb00ede22017-01-30 07:24:40 +00001954 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001955 """
1956 cert = X509()
1957 with pytest.raises(TypeError):
1958 cert.sign(object(), b"sha256")
1959
Alex Gaynor9939ba12017-06-25 16:28:24 -04001960 def test_convert_from_cryptography(self):
1961 crypto_cert = x509.load_pem_x509_certificate(
1962 intermediate_cert_pem, backend
1963 )
1964 cert = X509.from_cryptography(crypto_cert)
1965
1966 assert isinstance(cert, X509)
1967 assert cert.get_version() == crypto_cert.version.value
1968
1969 def test_convert_from_cryptography_unsupported_type(self):
1970 with pytest.raises(TypeError):
1971 X509.from_cryptography(object())
1972
1973 def test_convert_to_cryptography_key(self):
1974 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1975 crypto_cert = cert.to_cryptography()
1976
1977 assert isinstance(crypto_cert, x509.Certificate)
1978 assert crypto_cert.version.value == cert.get_version()
1979
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001980
Alex Chan9e2a9932017-01-25 14:29:19 +00001981class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001982 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001983 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001984 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001985
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001986 def test_type(self):
1987 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001988 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001989 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001990 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001991
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001992 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001993 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001994 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001995 """
1996 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001997 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001998 store.add_cert(cert)
1999
Alex Chanfb078d82017-04-20 11:16:15 +01002000 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2001 def test_add_cert_wrong_args(self, cert):
2002 """
2003 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2004 as its first argument.
2005 """
2006 store = X509Store()
2007 with pytest.raises(TypeError):
2008 store.add_cert(cert)
2009
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002010 def test_add_cert_accepts_duplicate(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002011 """
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002012 `X509Store.add_cert` doesn't raise `OpenSSL.crypto.Error` if an attempt
2013 is made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002014 """
2015 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2016 store = X509Store()
2017 store.add_cert(cert)
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002018 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002019
2020
Alex Chanb00ede22017-01-30 07:24:40 +00002021class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002022 """
Alex Chanb00ede22017-01-30 07:24:40 +00002023 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002024 """
2025 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2026
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002027 def test_type(self):
2028 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002029 `PKCS12` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002030 """
Alex Chanb00ede22017-01-30 07:24:40 +00002031 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002032
Rick Deanf94096c2009-07-18 14:23:06 -05002033 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002034 """
Alex Chanb00ede22017-01-30 07:24:40 +00002035 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2036 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002037 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002038 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002039 assert None is p12.get_certificate()
2040 assert None is p12.get_privatekey()
2041 assert None is p12.get_ca_certificates()
2042 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002043
2044 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002045 """
Alex Chanb00ede22017-01-30 07:24:40 +00002046 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2047 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2048 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002049 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002050 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002051 for bad_arg in [3, PKey(), X509]:
2052 with pytest.raises(TypeError):
2053 p12.set_certificate(bad_arg)
2054 for bad_arg in [3, 'legbone', X509()]:
2055 with pytest.raises(TypeError):
2056 p12.set_privatekey(bad_arg)
2057 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2058 with pytest.raises(TypeError):
2059 p12.set_ca_certificates(bad_arg)
2060 for bad_arg in [6, ('foo', 'bar')]:
2061 with pytest.raises(TypeError):
2062 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002063
2064 def test_key_only(self):
2065 """
Alex Chanb00ede22017-01-30 07:24:40 +00002066 A `PKCS12` with only a private key can be exported using
2067 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002068 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002069 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002070 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002071 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002072 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002073 assert None is p12.get_certificate()
2074 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002075 try:
2076 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2077 except Error:
2078 # Some versions of OpenSSL will throw an exception
2079 # for this nearly useless PKCS12 we tried to generate:
2080 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2081 return
Rick Dean623ee362009-07-17 12:22:16 -05002082 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002083 assert None is p12.get_ca_certificates()
2084 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002085
2086 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2087 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002088 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002089
2090 def test_cert_only(self):
2091 """
Alex Chanb00ede22017-01-30 07:24:40 +00002092 A `PKCS12` with only a certificate can be exported using
2093 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002094 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002095 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002096 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002097 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002098 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002099 assert cert == p12.get_certificate()
2100 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002101 try:
2102 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2103 except Error:
2104 # Some versions of OpenSSL will throw an exception
2105 # for this nearly useless PKCS12 we tried to generate:
2106 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2107 return
Rick Dean623ee362009-07-17 12:22:16 -05002108 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002109 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002110
2111 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002112 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002113
2114 # Oh ho. It puts the certificate into the ca certificates list, in
2115 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2116 # that to check to see if it reconstructed the certificate we expected
2117 # it to. At some point, hopefully this will change so that
2118 # p12.get_certificate() is actually what returns the loaded
2119 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002120 assert (
2121 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002122 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002123
Alex Gaynor31287502015-09-05 16:11:27 -04002124 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2125 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002126 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002127 Generate a PKCS12 object with components from PEM. Verify that the set
2128 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002129 """
Rick Deanf94096c2009-07-18 14:23:06 -05002130 p12 = PKCS12()
2131 if cert_pem:
2132 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002133 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002134 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002135 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002136 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002137 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002138 ret = p12.set_ca_certificates(
2139 (load_certificate(FILETYPE_PEM, ca_pem),)
2140 )
Alex Chanb00ede22017-01-30 07:24:40 +00002141 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002142 if friendly_name:
2143 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002144 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002145 return p12
2146
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002147 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002148 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002149 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002150 Use openssl program to confirm three components are recoverable from a
2151 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002152 """
2153 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002154 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002155 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2156 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002157 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002158 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002159 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002160 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2161 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002162 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002163 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002164 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002165 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2166 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002167 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002168
Stephen Holsapple38482622014-04-05 20:29:34 -07002169 def verify_pkcs12_container(self, p12):
2170 """
2171 Verify that the PKCS#12 container contains the correct client
2172 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002173
2174 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002175 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002176 """
2177 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2178 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002179 assert (
2180 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002181 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002182
Rick Deanf94096c2009-07-18 14:23:06 -05002183 def test_load_pkcs12(self):
2184 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002185 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002186 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002187 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002188 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002189 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002190 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002191 pem,
2192 b"pkcs12",
2193 b"-export",
2194 b"-clcerts",
2195 b"-passout",
2196 b"pass:" + passwd
2197 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002198 p12 = load_pkcs12(p12_str, passphrase=passwd)
2199 self.verify_pkcs12_container(p12)
2200
Abraham Martinc5484ba2015-03-25 15:33:05 +00002201 def test_load_pkcs12_text_passphrase(self):
2202 """
2203 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002204 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002205 Using text as passphrase instead of bytes. DeprecationWarning expected.
2206 """
2207 pem = client_key_pem + client_cert_pem
2208 passwd = b"whatever"
2209 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2210 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002211 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002212 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002213 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002214 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002215 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002216 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002217 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002218
Abraham Martinc5484ba2015-03-25 15:33:05 +00002219 self.verify_pkcs12_container(p12)
2220
Stephen Holsapple38482622014-04-05 20:29:34 -07002221 def test_load_pkcs12_no_passphrase(self):
2222 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002223 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002224 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002225 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002226 """
2227 pem = client_key_pem + client_cert_pem
2228 p12_str = _runopenssl(
2229 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2230 p12 = load_pkcs12(p12_str)
2231 self.verify_pkcs12_container(p12)
2232
Stephen Holsapple38482622014-04-05 20:29:34 -07002233 def _dump_and_load(self, dump_passphrase, load_passphrase):
2234 """
2235 A helper method to dump and load a PKCS12 object.
2236 """
2237 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2238 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2239 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2240
Stephen Holsapple38482622014-04-05 20:29:34 -07002241 def test_load_pkcs12_null_passphrase_load_empty(self):
2242 """
2243 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002244 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002245 extracted and examined.
2246 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002247 self.verify_pkcs12_container(
2248 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002249
Stephen Holsapple38482622014-04-05 20:29:34 -07002250 def test_load_pkcs12_null_passphrase_load_null(self):
2251 """
2252 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002253 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002254 extracted and examined.
2255 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002256 self.verify_pkcs12_container(
2257 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002258
Stephen Holsapple38482622014-04-05 20:29:34 -07002259 def test_load_pkcs12_empty_passphrase_load_empty(self):
2260 """
2261 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002262 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002263 extracted and examined.
2264 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002265 self.verify_pkcs12_container(
2266 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002267
Stephen Holsapple38482622014-04-05 20:29:34 -07002268 def test_load_pkcs12_empty_passphrase_load_null(self):
2269 """
2270 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002271 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002272 extracted and examined.
2273 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002274 self.verify_pkcs12_container(
2275 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002276
Rick Deanee568302009-07-24 09:56:29 -05002277 def test_load_pkcs12_garbage(self):
2278 """
Alex Chanb00ede22017-01-30 07:24:40 +00002279 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002280 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002281 """
2282 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002283 with pytest.raises(Error) as err:
2284 load_pkcs12(b'fruit loops', passwd)
2285 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2286 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002287
Rick Deanf94096c2009-07-18 14:23:06 -05002288 def test_replace(self):
2289 """
Alex Chanb00ede22017-01-30 07:24:40 +00002290 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2291 cluster. `PKCS12.set_privatekey` replaces the private key.
2292 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002293 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002294 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2295 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2296 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002297 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002298 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002299 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002300 assert 1 == len(p12.get_ca_certificates())
2301 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002302 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002303 assert 2 == len(p12.get_ca_certificates())
2304 assert client_cert == p12.get_ca_certificates()[0]
2305 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002306
Rick Deanf94096c2009-07-18 14:23:06 -05002307 def test_friendly_name(self):
2308 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002309 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002310 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2311 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002312 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002313 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002314 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002315 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002316 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002317 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002318 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002319 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002320 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002321 # We would use the openssl program to confirm the friendly
2322 # name, but it is not possible. The pkcs12 command
2323 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002324 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002325 self.check_recovery(
2326 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2327 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002328
Rick Deanf94096c2009-07-18 14:23:06 -05002329 def test_various_empty_passphrases(self):
2330 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002331 Test that missing, None, and '' passphrases are identical for PKCS12
2332 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002333 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002334 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002335 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002336 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2337 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2338 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2339 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2340 self.check_recovery(
2341 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2342 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002343
Rick Deanf94096c2009-07-18 14:23:06 -05002344 def test_removing_ca_cert(self):
2345 """
Alex Chanb00ede22017-01-30 07:24:40 +00002346 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2347 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002348 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002349 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2350 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002351 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002352
Rick Deanf94096c2009-07-18 14:23:06 -05002353 def test_export_without_mac(self):
2354 """
Alex Chanb00ede22017-01-30 07:24:40 +00002355 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002356 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002357 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002358 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002359 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002360 self.check_recovery(
2361 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002362 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002363
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002364 def test_load_without_mac(self):
2365 """
2366 Loading a PKCS12 without a MAC does something other than crash.
2367 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002368 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002369 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2370 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002371 try:
2372 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2373 # The person who generated this PCKS12 should be flogged,
2374 # or better yet we should have a means to determine
2375 # whether a PCKS12 had a MAC that was verified.
2376 # Anyway, libopenssl chooses to allow it, so the
2377 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002378 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002379 except Error:
2380 # Failing here with an exception is preferred as some openssl
2381 # versions do.
2382 pass
Rick Dean623ee362009-07-17 12:22:16 -05002383
Rick Dean25bcc1f2009-07-20 11:53:13 -05002384 def test_zero_len_list_for_ca(self):
2385 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002386 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002387 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002388 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002389 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002390 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002391 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002392 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2393 self.check_recovery(
2394 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2395 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002396
Rick Deanf94096c2009-07-18 14:23:06 -05002397 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002398 """
Alex Chanb00ede22017-01-30 07:24:40 +00002399 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002400 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002401 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002402 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002403 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002404 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002405
Abraham Martinc5484ba2015-03-25 15:33:05 +00002406 def test_export_without_bytes(self):
2407 """
Alex Chanb00ede22017-01-30 07:24:40 +00002408 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002409 """
2410 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2411
Alex Chanb00ede22017-01-30 07:24:40 +00002412 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002413 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002414 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002415 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002416 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002417 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002418 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002419 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002420 dumped_p12,
2421 key=server_key_pem,
2422 cert=server_cert_pem,
2423 passwd=b"randomtext"
2424 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002425
Rick Deanf94096c2009-07-18 14:23:06 -05002426 def test_key_cert_mismatch(self):
2427 """
Alex Chanb00ede22017-01-30 07:24:40 +00002428 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002429 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002430 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002431 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002432 with pytest.raises(Error):
2433 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002434
2435
Rick Dean4c9ad612009-07-17 15:05:22 -05002436def _runopenssl(pem, *args):
2437 """
2438 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002439 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002440 """
Alex Gaynor6cbc69a2017-07-25 09:07:04 -04002441 proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002442 proc.stdin.write(pem)
2443 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002444 output = proc.stdout.read()
2445 proc.stdout.close()
2446 proc.wait()
2447 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002448
2449
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002450class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002451 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002452 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002453 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002454 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002455 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002456 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002457 """
2458 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002459
2460 assert True is key._only_public
2461 assert 2048 == key.bits()
2462 assert TYPE_RSA == key.type()
2463
2464 def test_invalid_type(self):
2465 """
2466 load_publickey doesn't support FILETYPE_TEXT.
2467 """
2468 with pytest.raises(ValueError):
2469 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2470
2471 def test_invalid_key_format(self):
2472 """
2473 load_publickey explodes on incorrect keys.
2474 """
2475 with pytest.raises(Error):
2476 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2477
2478 def test_tolerates_unicode_strings(self):
2479 """
2480 load_publickey works with text strings, not just bytes.
2481 """
2482 serialized = cleartextPublicKeyPEM.decode('ascii')
2483 key = load_publickey(FILETYPE_PEM, serialized)
2484 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2485
2486 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002487
2488
Alex Chanb00ede22017-01-30 07:24:40 +00002489class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002490 """
Alex Chanb00ede22017-01-30 07:24:40 +00002491 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002492 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002493
2494 def test_load_privatekey_invalid_format(self):
2495 """
Alex Chanb00ede22017-01-30 07:24:40 +00002496 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002497 """
Alex Chanb00ede22017-01-30 07:24:40 +00002498 with pytest.raises(ValueError):
2499 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002500
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002501 def test_load_privatekey_invalid_passphrase_type(self):
2502 """
Alex Chanb00ede22017-01-30 07:24:40 +00002503 `load_privatekey` raises `TypeError` if passed a passphrase that is
2504 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002505 """
Alex Chanb00ede22017-01-30 07:24:40 +00002506 with pytest.raises(TypeError):
2507 load_privatekey(
2508 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002509
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002510 def test_load_privatekey_wrongPassphrase(self):
2511 """
Alex Chanb00ede22017-01-30 07:24:40 +00002512 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2513 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002514 """
Alex Chanb00ede22017-01-30 07:24:40 +00002515 with pytest.raises(Error) as err:
2516 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2517 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002518
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002519 def test_load_privatekey_passphraseWrongType(self):
2520 """
Alex Chanb00ede22017-01-30 07:24:40 +00002521 `load_privatekey` raises `ValueError` when it is passeda passphrase
2522 with a private key encoded in a format, that doesn't support
2523 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002524 """
2525 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2526 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002527 with pytest.raises(ValueError):
2528 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002529
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002530 def test_load_privatekey_passphrase(self):
2531 """
Alex Chanb00ede22017-01-30 07:24:40 +00002532 `load_privatekey` can create a `PKey` object from an encrypted PEM
2533 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002534 """
2535 key = load_privatekey(
2536 FILETYPE_PEM, encryptedPrivateKeyPEM,
2537 encryptedPrivateKeyPEMPassphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002538 assert isinstance(key, PKey)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002539
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002540 def test_load_privatekey_passphrase_exception(self):
2541 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002542 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002543 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002544 """
2545 def cb(ignored):
2546 raise ArithmeticError
2547
Alex Gaynor791212d2015-09-05 15:46:08 -04002548 with pytest.raises(ArithmeticError):
2549 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002550
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002551 def test_load_privatekey_wrongPassphraseCallback(self):
2552 """
Alex Chanb00ede22017-01-30 07:24:40 +00002553 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002554 is passed an encrypted PEM and a passphrase callback which returns an
2555 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002556 """
2557 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002558
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002559 def cb(*a):
2560 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002561 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002562 with pytest.raises(Error) as err:
2563 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2564 assert called
2565 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002566
2567 def test_load_privatekey_passphraseCallback(self):
2568 """
Alex Chanb00ede22017-01-30 07:24:40 +00002569 `load_privatekey` can create a `PKey` object from an encrypted PEM
2570 string if given a passphrase callback which returns the correct
2571 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002572 """
2573 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002574
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002575 def cb(writing):
2576 called.append(writing)
2577 return encryptedPrivateKeyPEMPassphrase
2578 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002579 assert isinstance(key, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002580 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002581
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002582 def test_load_privatekey_passphrase_wrong_return_type(self):
2583 """
Alex Chanb00ede22017-01-30 07:24:40 +00002584 `load_privatekey` raises `ValueError` if the passphrase callback
2585 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002586 """
Alex Chanb00ede22017-01-30 07:24:40 +00002587 with pytest.raises(ValueError):
2588 load_privatekey(
2589 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002590
Alex Chanfb078d82017-04-20 11:16:15 +01002591 def test_dump_privatekey_wrong_args(self):
2592 """
2593 `dump_privatekey` raises `TypeError` if called with a `cipher`
2594 argument but no `passphrase` argument.
2595 """
2596 key = PKey()
2597 key.generate_key(TYPE_RSA, 512)
2598 with pytest.raises(TypeError):
2599 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2600
Paul Kehrercded9932017-06-29 18:43:42 -05002601 def test_dump_privatekey_not_rsa_key(self):
2602 """
2603 `dump_privatekey` raises `TypeError` if called with a key that is
2604 not RSA.
2605 """
2606 key = PKey()
2607 key.generate_key(TYPE_DSA, 512)
2608 with pytest.raises(TypeError):
2609 dump_privatekey(FILETYPE_TEXT, key)
2610
2611 def test_dump_privatekey_invalid_pkey(self):
2612 with pytest.raises(TypeError):
2613 dump_privatekey(FILETYPE_TEXT, object())
2614
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002615 def test_dump_privatekey_unknown_cipher(self):
2616 """
Alex Chanb00ede22017-01-30 07:24:40 +00002617 `dump_privatekey` raises `ValueError` if called with an unrecognized
2618 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002619 """
2620 key = PKey()
2621 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002622 with pytest.raises(ValueError):
2623 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002624
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002625 def test_dump_privatekey_invalid_passphrase_type(self):
2626 """
Alex Chanb00ede22017-01-30 07:24:40 +00002627 `dump_privatekey` raises `TypeError` if called with a passphrase which
2628 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002629 """
2630 key = PKey()
2631 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002632 with pytest.raises(TypeError):
2633 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002634
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002635 def test_dump_privatekey_invalid_filetype(self):
2636 """
Alex Chanb00ede22017-01-30 07:24:40 +00002637 `dump_privatekey` raises `ValueError` if called with an unrecognized
2638 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002639 """
2640 key = PKey()
2641 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002642 with pytest.raises(ValueError):
2643 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002644
Alex Chanb00ede22017-01-30 07:24:40 +00002645 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002646 """
Alex Chanb00ede22017-01-30 07:24:40 +00002647 `crypto.load_privatekey` should raise an error when the passphrase
2648 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002649 """
2650 def cb(ignored):
2651 return "a" * 1025
2652
Alex Gaynor791212d2015-09-05 15:46:08 -04002653 with pytest.raises(ValueError):
2654 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002655
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002656 def test_dump_privatekey_passphrase(self):
2657 """
Alex Chanb00ede22017-01-30 07:24:40 +00002658 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002659 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002660 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002661 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002662 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Gaynor12576002019-11-18 00:18:50 -05002663 assert isinstance(pem, bytes)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002664 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002665 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002666 assert loadedKey.type() == key.type()
2667 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002668
Alex Chanb00ede22017-01-30 07:24:40 +00002669 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002670 """
Alex Chanb00ede22017-01-30 07:24:40 +00002671 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2672 with a private key encoded in a format, that doesn't support
2673 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002674 """
2675 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002676 with pytest.raises(ValueError):
2677 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002678
Rick Dean5b7b6372009-04-01 11:34:06 -05002679 def test_dump_certificate(self):
2680 """
Alex Chanb00ede22017-01-30 07:24:40 +00002681 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002682 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002683 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002684 cert = load_certificate(FILETYPE_PEM, pemData)
2685 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002686 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002687 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002688 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002689 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002690 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2691 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002692 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002693 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002694 good_text = _runopenssl(
2695 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002696 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002697
Alex Gaynor37726112016-07-04 09:51:32 -04002698 def test_dump_certificate_bad_type(self):
2699 """
Alex Chanb00ede22017-01-30 07:24:40 +00002700 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002701 a bad type.
2702 """
2703 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2704 with pytest.raises(ValueError):
2705 dump_certificate(object(), cert)
2706
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002707 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002708 """
Alex Chanb00ede22017-01-30 07:24:40 +00002709 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002710 """
2711 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002712 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002713 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002714 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002715
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002716 def test_dump_privatekey_asn1(self):
2717 """
Alex Chanb00ede22017-01-30 07:24:40 +00002718 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002719 """
2720 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2721 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2722
Rick Dean5b7b6372009-04-01 11:34:06 -05002723 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002724 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002725 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002726 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002727 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2728 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002729 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002730
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002731 def test_dump_privatekey_text(self):
2732 """
Alex Chanb00ede22017-01-30 07:24:40 +00002733 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002734 """
2735 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2736 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2737
Rick Dean5b7b6372009-04-01 11:34:06 -05002738 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002739 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002740 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002741
Cory Benfield6492f7c2015-10-27 16:57:58 +09002742 def test_dump_publickey_pem(self):
2743 """
Cory Benfield11c10192015-10-27 17:23:03 +09002744 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002745 """
2746 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2747 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002748 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002749
2750 def test_dump_publickey_asn1(self):
2751 """
Cory Benfield11c10192015-10-27 17:23:03 +09002752 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002753 """
2754 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2755 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2756 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2757 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002758 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002759
Cory Benfielde02c7d82015-10-27 17:34:49 +09002760 def test_dump_publickey_invalid_type(self):
2761 """
2762 dump_publickey doesn't support FILETYPE_TEXT.
2763 """
2764 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2765
2766 with pytest.raises(ValueError):
2767 dump_publickey(FILETYPE_TEXT, key)
2768
Rick Dean5b7b6372009-04-01 11:34:06 -05002769 def test_dump_certificate_request(self):
2770 """
Alex Chanb00ede22017-01-30 07:24:40 +00002771 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002772 """
Alex Gaynor31287502015-09-05 16:11:27 -04002773 req = load_certificate_request(
2774 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002775 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002776 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002777 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002778 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002779 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002780 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2781 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002782 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002783 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002784 good_text = _runopenssl(
2785 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002786 assert dumped_text == good_text
2787 with pytest.raises(ValueError):
2788 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002789
Alex Chanb00ede22017-01-30 07:24:40 +00002790 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002791 """
Alex Chanb00ede22017-01-30 07:24:40 +00002792 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002793 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002794 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002795 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002796 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002797
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002798 def cb(writing):
2799 called.append(writing)
2800 return passphrase
2801 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002802 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Gaynor12576002019-11-18 00:18:50 -05002803 assert isinstance(pem, bytes)
Alex Chanb00ede22017-01-30 07:24:40 +00002804 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002805 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002806 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002807 assert loadedKey.type() == key.type()
2808 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002809
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002810 def test_dump_privatekey_passphrase_exception(self):
2811 """
Alex Chanb00ede22017-01-30 07:24:40 +00002812 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002813 by the passphrase callback.
2814 """
2815 def cb(ignored):
2816 raise ArithmeticError
2817
2818 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002819 with pytest.raises(ArithmeticError):
2820 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002821
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002822 def test_dump_privatekey_passphraseCallbackLength(self):
2823 """
Alex Chanb00ede22017-01-30 07:24:40 +00002824 `crypto.dump_privatekey` should raise an error when the passphrase
2825 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002826 """
2827 def cb(ignored):
2828 return "a" * 1025
2829
2830 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002831 with pytest.raises(ValueError):
2832 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002833
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002834 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002835 """
Alex Chanb00ede22017-01-30 07:24:40 +00002836 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2837 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002838 """
2839 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002840 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002841
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002842 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002843 """
Alex Chanb00ede22017-01-30 07:24:40 +00002844 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2845 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002846 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002847 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002848 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002849
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002850 def test_load_pkcs7_data_invalid(self):
2851 """
Alex Chanb00ede22017-01-30 07:24:40 +00002852 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002853 """
Alex Chanb00ede22017-01-30 07:24:40 +00002854 with pytest.raises(Error):
2855 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002856
Alex Gaynor09a386e2016-07-03 09:32:44 -04002857 def test_load_pkcs7_type_invalid(self):
2858 """
Alex Chanb00ede22017-01-30 07:24:40 +00002859 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002860 """
2861 with pytest.raises(ValueError):
2862 load_pkcs7_data(object(), b"foo")
2863
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002864
Alex Chan9e2a9932017-01-25 14:29:19 +00002865class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002866 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002867 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002868 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002869
Alex Chan9e2a9932017-01-25 14:29:19 +00002870 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002871 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002872 If the file type passed to `load_certificate_request` is neither
2873 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002874 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002875 with pytest.raises(ValueError):
2876 load_certificate_request(object(), b"")
2877 with pytest.raises(ValueError):
2878 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002879
Alex Gaynor37726112016-07-04 09:51:32 -04002880 def test_bad_certificate(self):
2881 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002882 If the bytes passed to `load_certificate` are not a valid certificate,
2883 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002884 """
2885 with pytest.raises(Error):
2886 load_certificate(FILETYPE_ASN1, b"lol")
2887
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002888
Alex Chanb00ede22017-01-30 07:24:40 +00002889class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002890 """
Alex Chanb00ede22017-01-30 07:24:40 +00002891 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002892 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002893
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002894 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002895 """
Alex Chanb00ede22017-01-30 07:24:40 +00002896 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2897 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002898 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002899 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002900 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002901
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002902 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002903 """
Alex Chanb00ede22017-01-30 07:24:40 +00002904 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2905 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002906 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002907 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002908 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002909
Alex Chanb00ede22017-01-30 07:24:40 +00002910 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002911 """
Alex Chanb00ede22017-01-30 07:24:40 +00002912 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002913 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002914 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002915 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002916 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002917
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002918 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002919 """
Alex Chanb00ede22017-01-30 07:24:40 +00002920 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2921 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002922 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002923 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002924 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002925
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002926 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002927 """
Alex Chanb00ede22017-01-30 07:24:40 +00002928 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002929 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002930 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002931 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002932 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002933
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002934 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002935 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002936 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002937 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002938 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002939 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002940 with pytest.raises(AttributeError):
2941 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002942
2943
Alex Chanb00ede22017-01-30 07:24:40 +00002944class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002945 """
Alex Chanb00ede22017-01-30 07:24:40 +00002946 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002947 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002948
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002949 def signable(self):
2950 """
Alex Chanb00ede22017-01-30 07:24:40 +00002951 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002952 """
2953 return NetscapeSPKI()
2954
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002955 def test_type(self):
2956 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002957 `NetscapeSPKI` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002958 """
Alex Chanb00ede22017-01-30 07:24:40 +00002959 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002960
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002961 def test_construction(self):
2962 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002963 `NetscapeSPKI` returns an instance of `NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002964 """
2965 nspki = NetscapeSPKI()
Alex Gaynor01f90a12019-02-07 09:14:48 -05002966 assert isinstance(nspki, NetscapeSPKI)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002967
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002968 def test_invalid_attribute(self):
2969 """
Alex Chanb00ede22017-01-30 07:24:40 +00002970 Accessing a non-existent attribute of a `NetscapeSPKI` instance
2971 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002972 """
2973 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002974 with pytest.raises(AttributeError):
2975 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002976
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002977 def test_b64_encode(self):
2978 """
Alex Chanb00ede22017-01-30 07:24:40 +00002979 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002980 """
2981 nspki = NetscapeSPKI()
2982 blob = nspki.b64_encode()
Alex Gaynor12576002019-11-18 00:18:50 -05002983 assert isinstance(blob, bytes)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002984
2985
Paul Kehrer2c605ba2016-03-11 11:17:26 -04002986class TestRevoked(object):
2987 """
Alex Chandeec9342016-12-19 22:00:38 +00002988 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04002989 """
2990 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
2991 """
2992 The get_reason method on the Revoked class checks to see if the
2993 extension is NID_crl_reason and should skip it otherwise. This test
2994 loads a CRL with extensions it should ignore.
2995 """
2996 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
2997 revoked = crl.get_revoked()
2998 reason = revoked[1].get_reason()
2999 assert reason == b'Unspecified'
3000
3001 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3002 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3003 revoked = crl.get_revoked()
3004 revoked[1].set_reason(None)
3005 reason = revoked[1].get_reason()
3006 assert reason is None
3007
Rick Dean536ba022009-07-24 23:57:27 -05003008 def test_construction(self):
3009 """
Alex Chandeec9342016-12-19 22:00:38 +00003010 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3011 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003012 """
3013 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003014 assert isinstance(revoked, Revoked)
3015 assert type(revoked) == Revoked
3016 assert revoked.get_serial() == b'00'
3017 assert revoked.get_rev_date() is None
3018 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003019
Rick Dean536ba022009-07-24 23:57:27 -05003020 def test_serial(self):
3021 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003022 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003023 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003024 """
3025 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003026 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003027 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003028 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003029 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003030
Alex Gaynore7f51982016-09-11 11:48:14 -04003031 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003032 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003033 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003034
Alex Chandeec9342016-12-19 22:00:38 +00003035 with pytest.raises(ValueError):
3036 revoked.set_serial(b'pqrst')
3037 with pytest.raises(TypeError):
3038 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003039
Rick Dean536ba022009-07-24 23:57:27 -05003040 def test_date(self):
3041 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003042 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003043 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003044 """
3045 revoked = Revoked()
3046 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003047 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003048
Alex Gaynore7f51982016-09-11 11:48:14 -04003049 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003050 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003051 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003052 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003053 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003054
Rick Dean6385faf2009-07-26 00:07:47 -05003055 def test_reason(self):
3056 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003057 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003058 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3059 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003060 """
3061 revoked = Revoked()
3062 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003063 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003064 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003065 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003066 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003067 assert (
3068 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003069 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003070 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003071
3072 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003073 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003074
Alex Chanfb078d82017-04-20 11:16:15 +01003075 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3076 def test_set_reason_wrong_args(self, reason):
3077 """
3078 `Revoked.set_reason` raises `TypeError` if called with an argument
3079 which is neither `None` nor a byte string.
3080 """
3081 revoked = Revoked()
3082 with pytest.raises(TypeError):
3083 revoked.set_reason(reason)
3084
Alex Chandeec9342016-12-19 22:00:38 +00003085 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003086 """
Alex Chandeec9342016-12-19 22:00:38 +00003087 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3088 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003089 """
3090 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003091 with pytest.raises(ValueError):
3092 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003093
3094
Alex Chan7be83a52017-01-24 15:19:29 +00003095class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003096 """
Alex Chan7be83a52017-01-24 15:19:29 +00003097 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003098 """
3099 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3100 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3101
Dan Sully44e767a2016-06-04 18:05:27 -07003102 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3103 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3104 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3105 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3106 intermediate_server_cert = load_certificate(
3107 FILETYPE_PEM, intermediate_server_cert_pem)
3108 intermediate_server_key = load_privatekey(
3109 FILETYPE_PEM, intermediate_server_key_pem)
3110
Rick Dean536ba022009-07-24 23:57:27 -05003111 def test_construction(self):
3112 """
Alex Chan7be83a52017-01-24 15:19:29 +00003113 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003114 that it is empty
3115 """
3116 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003117 assert isinstance(crl, CRL)
3118 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003119
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003120 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003121 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003122 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003123 """
3124 crl = CRL()
3125 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003126 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003127 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003128 revoked.set_serial(b'3ab')
3129 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003130 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003131 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003132
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003133 def test_export_pem(self):
3134 """
3135 If not passed a format, ``CRL.export`` returns a "PEM" format string
3136 representing a serial number, a revoked reason, and certificate issuer
3137 information.
3138 """
Rick Dean536ba022009-07-24 23:57:27 -05003139 # PEM format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003140 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003141 self.cert, self.pkey, days=20, digest=b"sha256"
3142 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003143 crl = x509.load_pem_x509_crl(dumped_crl, backend)
3144 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3145 assert revoked is not None
3146 assert crl.issuer == x509.Name([
3147 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3148 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3149 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3150 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3151 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3152 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003153
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003154 def test_export_der(self):
3155 """
3156 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3157 "DER" format string representing a serial number, a revoked reason, and
3158 certificate issuer information.
3159 """
3160 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003161
3162 # DER format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003163 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003164 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3165 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003166 crl = x509.load_der_x509_crl(dumped_crl, backend)
3167 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3168 assert revoked is not None
3169 assert crl.issuer == x509.Name([
3170 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3171 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3172 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3173 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3174 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3175 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003176
Alex Gaynore466bc92017-07-06 23:43:47 -04003177 # Flaky because we compare the output of running commands which sometimes
3178 # varies by 1 second
3179 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003180 def test_export_text(self):
3181 """
3182 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3183 text format string like the one produced by the openssl command line
3184 tool.
3185 """
3186 crl = self._get_crl()
3187
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003188 dumped_crl = crl.export(
3189 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3190 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003191 text = _runopenssl(
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003192 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER",
3193 b"-nameopt", b""
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003194 )
Rick Dean536ba022009-07-24 23:57:27 -05003195
3196 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003197 dumped_text = crl.export(
3198 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3199 )
Alex Chan7be83a52017-01-24 15:19:29 +00003200 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003201
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003202 def test_export_custom_digest(self):
3203 """
3204 If passed the name of a digest function, ``CRL.export`` uses a
3205 signature algorithm based on that digest function.
3206 """
3207 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003208 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003209 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003210 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003211
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003212 def test_export_md5_digest(self):
3213 """
3214 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3215 not emit a deprecation warning.
3216 """
3217 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003218 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003219 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003220 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003221 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3222 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003223 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003224
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003225 def test_export_default_digest(self):
3226 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003227 If not passed the name of a digest function, ``CRL.export`` raises a
3228 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003229 """
3230 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003231 with pytest.raises(TypeError):
3232 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003233
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003234 def test_export_invalid(self):
3235 """
Alex Chan7be83a52017-01-24 15:19:29 +00003236 If `CRL.export` is used with an uninitialized `X509` instance,
3237 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003238 """
3239 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003240 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003241 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003242
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003243 def test_add_revoked_keyword(self):
3244 """
Alex Chan7be83a52017-01-24 15:19:29 +00003245 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003246 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003247 """
3248 crl = CRL()
3249 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003250 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003251 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003252 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003253 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003254
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003255 def test_export_wrong_args(self):
3256 """
Alex Chan7be83a52017-01-24 15:19:29 +00003257 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003258 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003259 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003260 """
3261 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003262 with pytest.raises(TypeError):
3263 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3264 with pytest.raises(TypeError):
3265 crl.export(self.cert, None, FILETYPE_PEM, 10)
3266 with pytest.raises(TypeError):
3267 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003268 with pytest.raises(TypeError):
3269 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003270
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003271 def test_export_unknown_filetype(self):
3272 """
Alex Chan7be83a52017-01-24 15:19:29 +00003273 Calling `OpenSSL.CRL.export` with a file type other than
3274 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3275 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003276 """
3277 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003278 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003279 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003280
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003281 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003282 """
Alex Chan7be83a52017-01-24 15:19:29 +00003283 Calling `OpenSSL.CRL.export` with an unsupported digest results
3284 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003285 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003286 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003287 with pytest.raises(ValueError):
3288 crl.export(
3289 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003290
Rick Dean536ba022009-07-24 23:57:27 -05003291 def test_get_revoked(self):
3292 """
Alex Chan7be83a52017-01-24 15:19:29 +00003293 Use python to create a simple CRL with two revocations. Get back the
3294 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003295 """
3296 crl = CRL()
3297
3298 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003299 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003300 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003301 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003302 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003303 revoked.set_serial(b'100')
3304 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003305 crl.add_revoked(revoked)
3306
3307 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003308 assert len(revs) == 2
3309 assert type(revs[0]) == Revoked
3310 assert type(revs[1]) == Revoked
3311 assert revs[0].get_serial() == b'03AB'
3312 assert revs[1].get_serial() == b'0100'
3313 assert revs[0].get_rev_date() == now
3314 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003315
Rick Dean536ba022009-07-24 23:57:27 -05003316 def test_load_crl(self):
3317 """
Alex Chan7be83a52017-01-24 15:19:29 +00003318 Load a known CRL and inspect its revocations. Both EM and DER formats
3319 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003320 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003321 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003322 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003323 assert len(revs) == 2
3324 assert revs[0].get_serial() == b'03AB'
3325 assert revs[0].get_reason() is None
3326 assert revs[1].get_serial() == b'0100'
3327 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003328
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003329 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003330 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003331 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003332 assert len(revs) == 2
3333 assert revs[0].get_serial() == b'03AB'
3334 assert revs[0].get_reason() is None
3335 assert revs[1].get_serial() == b'0100'
3336 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003337
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003338 def test_load_crl_bad_filetype(self):
3339 """
Alex Chan7be83a52017-01-24 15:19:29 +00003340 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3341 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003342 """
Alex Chan7be83a52017-01-24 15:19:29 +00003343 with pytest.raises(ValueError):
3344 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003345
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003346 def test_load_crl_bad_data(self):
3347 """
Alex Chan7be83a52017-01-24 15:19:29 +00003348 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3349 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003350 """
Alex Chan7be83a52017-01-24 15:19:29 +00003351 with pytest.raises(Error):
3352 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003353
Dan Sully44e767a2016-06-04 18:05:27 -07003354 def test_get_issuer(self):
3355 """
Alex Chan7be83a52017-01-24 15:19:29 +00003356 Load a known CRL and assert its issuer's common name is what we expect
3357 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003358 """
3359 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003360 assert isinstance(crl.get_issuer(), X509Name)
3361 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003362
Dominic Chenf05b2122015-10-13 16:32:35 +00003363 def test_dump_crl(self):
3364 """
3365 The dumped CRL matches the original input.
3366 """
3367 crl = load_crl(FILETYPE_PEM, crlData)
3368 buf = dump_crl(FILETYPE_PEM, crl)
3369 assert buf == crlData
3370
Dan Sully44e767a2016-06-04 18:05:27 -07003371 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3372 """
3373 Create a CRL.
3374
3375 :param list[X509] certs: A list of certificates to revoke.
3376 :rtype: CRL
3377 """
3378 crl = CRL()
3379 for cert in certs:
3380 revoked = Revoked()
3381 # FIXME: This string splicing is an unfortunate implementation
3382 # detail that has been reported in
3383 # https://github.com/pyca/pyopenssl/issues/258
3384 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3385 revoked.set_serial(serial)
3386 revoked.set_reason(b'unspecified')
3387 revoked.set_rev_date(b'20140601000000Z')
3388 crl.add_revoked(revoked)
3389 crl.set_version(1)
3390 crl.set_lastUpdate(b'20140601000000Z')
3391 crl.set_nextUpdate(b'20180601000000Z')
3392 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3393 return crl
3394
3395 def test_verify_with_revoked(self):
3396 """
Alex Chan7be83a52017-01-24 15:19:29 +00003397 `verify_certificate` raises error when an intermediate certificate is
3398 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003399 """
3400 store = X509Store()
3401 store.add_cert(self.root_cert)
3402 store.add_cert(self.intermediate_cert)
3403 root_crl = self._make_test_crl(
3404 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3405 intermediate_crl = self._make_test_crl(
3406 self.intermediate_cert, self.intermediate_key, certs=[])
3407 store.add_crl(root_crl)
3408 store.add_crl(intermediate_crl)
3409 store.set_flags(
3410 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3411 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003412 with pytest.raises(X509StoreContextError) as err:
3413 store_ctx.verify_certificate()
3414 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003415
3416 def test_verify_with_missing_crl(self):
3417 """
Alex Chan7be83a52017-01-24 15:19:29 +00003418 `verify_certificate` raises error when an intermediate certificate's
3419 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003420 """
3421 store = X509Store()
3422 store.add_cert(self.root_cert)
3423 store.add_cert(self.intermediate_cert)
3424 root_crl = self._make_test_crl(
3425 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3426 store.add_crl(root_crl)
3427 store.set_flags(
3428 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3429 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003430 with pytest.raises(X509StoreContextError) as err:
3431 store_ctx.verify_certificate()
3432 assert err.value.args[0][2] == 'unable to get certificate CRL'
3433 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003434
Paul Kehrer41c10242017-06-29 18:24:17 -05003435 def test_convert_from_cryptography(self):
3436 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3437 crl = CRL.from_cryptography(crypto_crl)
3438 assert isinstance(crl, CRL)
3439
3440 def test_convert_from_cryptography_unsupported_type(self):
3441 with pytest.raises(TypeError):
3442 CRL.from_cryptography(object())
3443
3444 def test_convert_to_cryptography_key(self):
3445 crl = load_crl(FILETYPE_PEM, crlData)
3446 crypto_crl = crl.to_cryptography()
3447 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3448
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003449
Alex Chan7be83a52017-01-24 15:19:29 +00003450class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003451 """
Alex Chan7be83a52017-01-24 15:19:29 +00003452 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003453 """
3454 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3455 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003456 intermediate_server_cert = load_certificate(
3457 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003458
3459 def test_valid(self):
3460 """
Alex Chan7be83a52017-01-24 15:19:29 +00003461 `verify_certificate` returns ``None`` when called with a certificate
3462 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003463 """
3464 store = X509Store()
3465 store.add_cert(self.root_cert)
3466 store.add_cert(self.intermediate_cert)
3467 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003468 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003469
3470 def test_reuse(self):
3471 """
Alex Chan7be83a52017-01-24 15:19:29 +00003472 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003473 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003474 """
3475 store = X509Store()
3476 store.add_cert(self.root_cert)
3477 store.add_cert(self.intermediate_cert)
3478 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003479 assert store_ctx.verify_certificate() is None
3480 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003481
3482 def test_trusted_self_signed(self):
3483 """
Alex Chan7be83a52017-01-24 15:19:29 +00003484 `verify_certificate` returns ``None`` when called with a self-signed
3485 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003486 """
3487 store = X509Store()
3488 store.add_cert(self.root_cert)
3489 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003490 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003491
3492 def test_untrusted_self_signed(self):
3493 """
Alex Chan7be83a52017-01-24 15:19:29 +00003494 `verify_certificate` raises error when a self-signed certificate is
3495 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003496 """
3497 store = X509Store()
3498 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003499 with pytest.raises(X509StoreContextError) as exc:
3500 store_ctx.verify_certificate()
3501
3502 assert exc.value.args[0][2] == 'self signed certificate'
3503 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003504
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003505 def test_invalid_chain_no_root(self):
3506 """
Alex Chan7be83a52017-01-24 15:19:29 +00003507 `verify_certificate` raises error when a root certificate is missing
3508 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003509 """
3510 store = X509Store()
3511 store.add_cert(self.intermediate_cert)
3512 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003513
3514 with pytest.raises(X509StoreContextError) as exc:
3515 store_ctx.verify_certificate()
3516
3517 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3518 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003519
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003520 def test_invalid_chain_no_intermediate(self):
3521 """
Alex Chan7be83a52017-01-24 15:19:29 +00003522 `verify_certificate` raises error when an intermediate certificate is
3523 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003524 """
3525 store = X509Store()
3526 store.add_cert(self.root_cert)
3527 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003528
Alex Gaynor85b49702015-09-05 16:30:59 -04003529 with pytest.raises(X509StoreContextError) as exc:
3530 store_ctx.verify_certificate()
3531
3532 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3533 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003534
Stephen Holsapple46a09252015-02-12 14:45:43 -08003535 def test_modification_pre_verify(self):
3536 """
Alex Chan7be83a52017-01-24 15:19:29 +00003537 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003538 instantiation.
3539 """
3540 store_bad = X509Store()
3541 store_bad.add_cert(self.intermediate_cert)
3542 store_good = X509Store()
3543 store_good.add_cert(self.root_cert)
3544 store_good.add_cert(self.intermediate_cert)
3545 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003546
3547 with pytest.raises(X509StoreContextError) as exc:
3548 store_ctx.verify_certificate()
3549
3550 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3551 assert exc.value.certificate.get_subject().CN == 'intermediate'
3552
Stephen Holsapple46a09252015-02-12 14:45:43 -08003553 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003554 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003555
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003556 def test_verify_with_time(self):
3557 """
3558 `verify_certificate` raises error when the verification time is
3559 set at notAfter.
3560 """
3561 store = X509Store()
3562 store.add_cert(self.root_cert)
3563 store.add_cert(self.intermediate_cert)
3564
3565 expire_time = self.intermediate_server_cert.get_notAfter()
3566 expire_datetime = datetime.strptime(
3567 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3568 )
3569 store.set_time(expire_datetime)
3570
3571 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3572 with pytest.raises(X509StoreContextError) as exc:
3573 store_ctx.verify_certificate()
3574
3575 assert exc.value.args[0][2] == 'certificate has expired'
3576
Stephen Holsapple46a09252015-02-12 14:45:43 -08003577
Alex Chan7be83a52017-01-24 15:19:29 +00003578class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003579 """
Alex Chan7be83a52017-01-24 15:19:29 +00003580 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003581 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003582
James Yonan7c2e5d32010-02-27 05:45:50 -07003583 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003584 """
Alex Chan7be83a52017-01-24 15:19:29 +00003585 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003586 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003587 content = (
3588 b"It was a bright cold day in April, and the clocks were striking "
3589 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3590 b"effort to escape the vile wind, slipped quickly through the "
3591 b"glass doors of Victory Mansions, though not quickly enough to "
3592 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003593
3594 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003595 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003596 # verify the content with this cert
3597 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3598 # certificate unrelated to priv_key, used to trigger an error
3599 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003600
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003601 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003602 sig = sign(priv_key, content, digest)
3603
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003604 # Verify the signature of content, will throw an exception if
3605 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003606 verify(good_cert, sig, content, digest)
3607
3608 # This should fail because the certificate doesn't match the
3609 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003610 with pytest.raises(Error):
3611 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003612
3613 # This should fail because we've "tainted" the content after
3614 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003615 with pytest.raises(Error):
3616 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003617
3618 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003619 with pytest.raises(ValueError):
3620 sign(priv_key, content, "strange-digest")
3621 with pytest.raises(ValueError):
3622 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003623
Abraham Martinc5484ba2015-03-25 15:33:05 +00003624 def test_sign_verify_with_text(self):
3625 """
Alex Chan7be83a52017-01-24 15:19:29 +00003626 `sign` generates a cryptographic signature which
3627 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003628 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003629 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003630 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003631 b"It was a bright cold day in April, and the clocks were striking "
3632 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3633 b"effort to escape the vile wind, slipped quickly through the "
3634 b"glass doors of Victory Mansions, though not quickly enough to "
3635 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003636 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003637
3638 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3639 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3640 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003641 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003642 simplefilter("always")
3643 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003644 assert (
3645 "{0} for data is no longer accepted, use bytes".format(
3646 WARNING_TYPE_EXPECTED
3647 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003648
Alex Chan7be83a52017-01-24 15:19:29 +00003649 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003650 simplefilter("always")
3651 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003652 assert (
3653 "{0} for data is no longer accepted, use bytes".format(
3654 WARNING_TYPE_EXPECTED
3655 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003656
Paul Kehrer59d26252017-07-20 10:45:54 +02003657 def test_sign_verify_ecdsa(self):
3658 """
3659 `sign` generates a cryptographic signature which `verify` can check.
3660 ECDSA Signatures in the X9.62 format may have variable length,
3661 different from the length of the private key.
3662 """
3663 content = (
3664 b"It was a bright cold day in April, and the clocks were striking "
3665 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3666 b"effort to escape the vile wind, slipped quickly through the "
3667 b"glass doors of Victory Mansions, though not quickly enough to "
3668 b"prevent a swirl of gritty dust from entering along with him."
3669 ).decode("ascii")
3670 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3671 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3672 sig = sign(priv_key, content, "sha1")
3673 verify(cert, sig, content, "sha1")
3674
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003675 def test_sign_nulls(self):
3676 """
Alex Chan7be83a52017-01-24 15:19:29 +00003677 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003678 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003679 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003680 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3681 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3682 sig = sign(priv_key, content, "sha1")
3683 verify(good_cert, sig, content, "sha1")
3684
Colleen Murphye09399b2016-03-01 17:40:49 -08003685 def test_sign_with_large_key(self):
3686 """
Alex Chan7be83a52017-01-24 15:19:29 +00003687 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003688 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003689 content = (
3690 b"It was a bright cold day in April, and the clocks were striking "
3691 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3692 b"effort to escape the vile wind, slipped quickly through the "
3693 b"glass doors of Victory Mansions, though not quickly enough to "
3694 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003695
3696 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3697 sign(priv_key, content, "sha1")
3698
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003699
Alex Chan63ef9bc2016-12-19 12:02:06 +00003700class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003701 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003702 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3703 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003704 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003705
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003706 def test_set(self):
3707 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003708 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003709 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003710 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003711
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003712 def test_a_curve(self):
3713 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003714 `get_elliptic_curve` can be used to retrieve a particular supported
3715 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003716 """
3717 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003718 curve = next(iter(curves))
3719 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003720
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003721 def test_not_a_curve(self):
3722 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003723 `get_elliptic_curve` raises `ValueError` if called with a name which
3724 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003725 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003726 with pytest.raises(ValueError):
3727 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003728
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003729 def test_repr(self):
3730 """
3731 The string representation of a curve object includes simply states the
3732 object is a curve and what its name is.
3733 """
3734 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003735 curve = next(iter(curves))
3736 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003737
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003738 def test_to_EC_KEY(self):
3739 """
3740 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003741 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003742 """
3743 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003744 curve = next(iter(curves))
3745 # It's not easy to assert anything about this object. However, see
3746 # leakcheck/crypto.py for a test that demonstrates it at least does
3747 # not leak memory.
3748 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003749
3750
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003751class EllipticCurveFactory(object):
3752 """
3753 A helper to get the names of two curves.
3754 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003755
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003756 def __init__(self):
3757 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003758 self.curve_name = next(curves).name
3759 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003760
3761
Alex Chan63ef9bc2016-12-19 12:02:06 +00003762class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003763 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003764 Tests `_EllipticCurve`'s implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003765 """
3766 curve_factory = EllipticCurveFactory()
3767
3768 if curve_factory.curve_name is None:
3769 skip = "There are no curves available there can be no curve objects."
3770
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003771 def anInstance(self):
3772 """
3773 Get the curve object for an arbitrary curve supported by the system.
3774 """
3775 return get_elliptic_curve(self.curve_factory.curve_name)
3776
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003777 def anotherInstance(self):
3778 """
3779 Get the curve object for an arbitrary curve supported by the system -
3780 but not the one returned by C{anInstance}.
3781 """
3782 return get_elliptic_curve(self.curve_factory.another_curve_name)
3783
3784
Alex Chan63ef9bc2016-12-19 12:02:06 +00003785class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003786 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003787 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3788 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003789 """
3790 curve_factory = EllipticCurveFactory()
3791
3792 if curve_factory.curve_name is None:
3793 skip = "There are no curves available there can be no curve objects."
3794
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003795 def test_contains(self):
3796 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003797 The ``in`` operator reports that a `set` containing a curve does
3798 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003799 """
3800 curve = get_elliptic_curve(self.curve_factory.curve_name)
3801 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003802 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003803
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003804 def test_does_not_contain(self):
3805 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003806 The ``in`` operator reports that a `set` not containing a curve
3807 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003808 """
3809 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003810 curves = set([
3811 get_elliptic_curve(self.curve_factory.another_curve_name)
3812 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003813 assert curve not in curves