blob: 2a0c967d433f59a11d769ff0314761b606b033b6 [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
Mrmaxmeier8cd3b172020-03-11 22:03:59 +0100564rsa_p_not_prime_pem = """
565-----BEGIN RSA PRIVATE KEY-----
566MBsCAQACAS0CAQcCAQACAQ8CAQMCAQACAQACAQA=
567-----END RSA PRIVATE KEY-----
568"""
569
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400570
Alex Chanc6077062016-11-18 13:53:39 +0000571@pytest.fixture
572def x509_data():
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400573 """
Alex Chanc6077062016-11-18 13:53:39 +0000574 Create a new private key and start a certificate request (for a test
575 to finish in one way or another).
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400576 """
Alex Chanc6077062016-11-18 13:53:39 +0000577 # Basic setup stuff to generate a certificate
578 pkey = PKey()
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400579 pkey.generate_key(TYPE_RSA, 512)
Alex Chanc6077062016-11-18 13:53:39 +0000580 req = X509Req()
581 req.set_pubkey(pkey)
582 # Authority good you have.
583 req.get_subject().commonName = "Yoda root CA"
584 x509 = X509()
585 subject = x509.get_subject()
586 subject.commonName = req.get_subject().commonName
587 x509.set_issuer(subject)
588 x509.set_pubkey(pkey)
589 now = datetime.now()
590 expire = datetime.now() + timedelta(days=100)
591 x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
592 x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
593 yield pkey, x509
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400594
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400595
Alex Chanc6077062016-11-18 13:53:39 +0000596class TestX509Ext(object):
597 """
598 Tests for `OpenSSL.crypto.X509Extension`.
599 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -0800600
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400601 def test_str(self):
602 """
Alex Chanc6077062016-11-18 13:53:39 +0000603 The string representation of `X509Extension` instances as
604 returned by `str` includes stuff.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400605 """
606 # This isn't necessarily the best string representation. Perhaps it
607 # will be changed/improved in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000608 assert (
609 str(X509Extension(b'basicConstraints', True, b'CA:false')) ==
610 'CA:FALSE'
611 )
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400612
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400613 def test_type(self):
614 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500615 `X509Extension` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400616 """
Alex Chanc6077062016-11-18 13:53:39 +0000617 assert is_consistent_type(
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400618 X509Extension,
Alex Gaynore7f51982016-09-11 11:48:14 -0400619 'X509Extension', b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400620
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500621 def test_construction(self):
622 """
Alex Chanc6077062016-11-18 13:53:39 +0000623 `X509Extension` accepts an extension type name, a critical flag,
Alex Gaynor01f90a12019-02-07 09:14:48 -0500624 and an extension value and returns an `X509Extension` instance.
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500625 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400626 basic = X509Extension(b'basicConstraints', True, b'CA:true')
Alex Gaynor01f90a12019-02-07 09:14:48 -0500627 assert isinstance(basic, X509Extension)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500628
Alex Chanc6077062016-11-18 13:53:39 +0000629 comment = X509Extension(b'nsComment', False, b'pyOpenSSL unit test')
Alex Gaynor01f90a12019-02-07 09:14:48 -0500630 assert isinstance(comment, X509Extension)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500631
Alex Chanc6077062016-11-18 13:53:39 +0000632 @pytest.mark.parametrize('type_name, critical, value', [
633 (b'thisIsMadeUp', False, b'hi'),
634 (b'basicConstraints', False, b'blah blah'),
Jean-Paul Calderone391585f2008-12-31 14:36:31 -0500635
Jean-Paul Calderone2ee1e7c2008-12-31 14:58:38 -0500636 # Exercise a weird one (an extension which uses the r2i method). This
637 # exercises the codepath that requires a non-NULL ctx to be passed to
638 # X509V3_EXT_nconf. It can't work now because we provide no
639 # configuration database. It might be made to work in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000640 (b'proxyCertInfo', True,
641 b'language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')
642 ])
643 def test_invalid_extension(self, type_name, critical, value):
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500644 """
Alex Chanc6077062016-11-18 13:53:39 +0000645 `X509Extension` raises something if it is passed a bad
646 extension name or value.
647 """
648 with pytest.raises(Error):
649 X509Extension(type_name, critical, value)
650
651 @pytest.mark.parametrize('critical_flag', [True, False])
652 def test_get_critical(self, critical_flag):
653 """
654 `X509ExtensionType.get_critical` returns the value of the
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500655 extension's critical flag.
656 """
Alex Chanc6077062016-11-18 13:53:39 +0000657 ext = X509Extension(b'basicConstraints', critical_flag, b'CA:true')
658 assert ext.get_critical() == critical_flag
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500659
Alex Chanc6077062016-11-18 13:53:39 +0000660 @pytest.mark.parametrize('short_name, value', [
661 (b'basicConstraints', b'CA:true'),
662 (b'nsComment', b'foo bar'),
663 ])
664 def test_get_short_name(self, short_name, value):
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500665 """
Alex Chanc6077062016-11-18 13:53:39 +0000666 `X509ExtensionType.get_short_name` returns a string giving the
Alex Gaynor31287502015-09-05 16:11:27 -0400667 short type name of the extension.
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500668 """
Alex Chanc6077062016-11-18 13:53:39 +0000669 ext = X509Extension(short_name, True, value)
670 assert ext.get_short_name() == short_name
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500671
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400672 def test_get_data(self):
673 """
Alex Chanc6077062016-11-18 13:53:39 +0000674 `X509Extension.get_data` returns a string giving the data of
Alex Gaynor31287502015-09-05 16:11:27 -0400675 the extension.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400676 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400677 ext = X509Extension(b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400678 # Expect to get back the DER encoded form of CA:true.
Alex Chanc6077062016-11-18 13:53:39 +0000679 assert ext.get_data() == b'0\x03\x01\x01\xff'
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400680
Alex Chanc6077062016-11-18 13:53:39 +0000681 def test_unused_subject(self, x509_data):
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400682 """
Alex Chanc6077062016-11-18 13:53:39 +0000683 The `subject` parameter to `X509Extension` may be provided for an
684 extension which does not use it and is ignored in this case.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400685 """
Alex Chanc6077062016-11-18 13:53:39 +0000686 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400687 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000688 b'basicConstraints', False, b'CA:TRUE', subject=x509)
689 x509.add_extensions([ext1])
690 x509.sign(pkey, 'sha1')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400691 # This is a little lame. Can we think of a better way?
Alex Chanc6077062016-11-18 13:53:39 +0000692 text = dump_certificate(FILETYPE_TEXT, x509)
693 assert b'X509v3 Basic Constraints:' in text
694 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400695
Alex Chanc6077062016-11-18 13:53:39 +0000696 def test_subject(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400697 """
Alex Chanc6077062016-11-18 13:53:39 +0000698 If an extension requires a subject, the `subject` parameter to
699 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400700 """
Alex Chanc6077062016-11-18 13:53:39 +0000701 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400702 ext3 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000703 b'subjectKeyIdentifier', False, b'hash', subject=x509)
704 x509.add_extensions([ext3])
705 x509.sign(pkey, 'sha1')
706 text = dump_certificate(FILETYPE_TEXT, x509)
707 assert b'X509v3 Subject Key Identifier:' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400708
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400709 def test_missing_subject(self):
710 """
Alex Chanc6077062016-11-18 13:53:39 +0000711 If an extension requires a subject and the `subject` parameter
Alex Gaynor31287502015-09-05 16:11:27 -0400712 is given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400713 """
Alex Chanc6077062016-11-18 13:53:39 +0000714 with pytest.raises(Error):
715 X509Extension(b'subjectKeyIdentifier', False, b'hash')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400716
Alex Chanc6077062016-11-18 13:53:39 +0000717 @pytest.mark.parametrize('bad_obj', [
718 True,
719 object(),
720 "hello",
721 [],
722 ])
723 def test_invalid_subject(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400724 """
Alex Chanc6077062016-11-18 13:53:39 +0000725 If the `subject` parameter is given a value which is not an
726 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400727 """
Alex Chanc6077062016-11-18 13:53:39 +0000728 with pytest.raises(TypeError):
729 X509Extension(
730 'basicConstraints', False, 'CA:TRUE', subject=bad_obj)
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400731
Alex Chanc6077062016-11-18 13:53:39 +0000732 def test_unused_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400733 """
Alex Chanc6077062016-11-18 13:53:39 +0000734 The `issuer` parameter to `X509Extension` may be provided for an
735 extension which does not use it and is ignored in this case.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400736 """
Alex Chanc6077062016-11-18 13:53:39 +0000737 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400738 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000739 b'basicConstraints', False, b'CA:TRUE', issuer=x509)
740 x509.add_extensions([ext1])
741 x509.sign(pkey, 'sha1')
742 text = dump_certificate(FILETYPE_TEXT, x509)
743 assert b'X509v3 Basic Constraints:' in text
744 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400745
Alex Chanc6077062016-11-18 13:53:39 +0000746 def test_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400747 """
Alex Chanc6077062016-11-18 13:53:39 +0000748 If an extension requires an issuer, the `issuer` parameter to
749 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400750 """
Alex Chanc6077062016-11-18 13:53:39 +0000751 pkey, x509 = x509_data
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400752 ext2 = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -0400753 b'authorityKeyIdentifier', False, b'issuer:always',
Alex Chanc6077062016-11-18 13:53:39 +0000754 issuer=x509)
755 x509.add_extensions([ext2])
756 x509.sign(pkey, 'sha1')
757 text = dump_certificate(FILETYPE_TEXT, x509)
758 assert b'X509v3 Authority Key Identifier:' in text
759 assert b'DirName:/CN=Yoda root CA' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400760
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400761 def test_missing_issuer(self):
762 """
Alex Chanc6077062016-11-18 13:53:39 +0000763 If an extension requires an issue and the `issuer` parameter is
764 given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400765 """
Alex Chanc6077062016-11-18 13:53:39 +0000766 with pytest.raises(Error):
767 X509Extension(
768 b'authorityKeyIdentifier',
769 False, b'keyid:always,issuer:always')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400770
Alex Chanc6077062016-11-18 13:53:39 +0000771 @pytest.mark.parametrize('bad_obj', [
772 True,
773 object(),
774 "hello",
775 [],
776 ])
777 def test_invalid_issuer(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400778 """
Alex Chanc6077062016-11-18 13:53:39 +0000779 If the `issuer` parameter is given a value which is not an
780 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400781 """
Alex Chanc6077062016-11-18 13:53:39 +0000782 with pytest.raises(TypeError):
783 X509Extension(
784 'basicConstraints', False, 'keyid:always,issuer:always',
785 issuer=bad_obj)
Rick Dean47262da2009-07-08 16:17:17 -0500786
787
Paul Kehrer72d968b2016-07-29 15:31:04 +0800788class TestPKey(object):
789 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +0100790 Tests for `OpenSSL.crypto.PKey`.
Paul Kehrer72d968b2016-07-29 15:31:04 +0800791 """
792
793 def test_convert_from_cryptography_private_key(self):
794 """
795 PKey.from_cryptography_key creates a proper private PKey.
796 """
797 key = serialization.load_pem_private_key(
798 intermediate_key_pem, None, backend
799 )
800 pkey = PKey.from_cryptography_key(key)
801
802 assert isinstance(pkey, PKey)
803 assert pkey.bits() == key.key_size
804 assert pkey._only_public is False
805 assert pkey._initialized is True
806
807 def test_convert_from_cryptography_public_key(self):
808 """
809 PKey.from_cryptography_key creates a proper public PKey.
810 """
811 key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
812 pkey = PKey.from_cryptography_key(key)
813
814 assert isinstance(pkey, PKey)
815 assert pkey.bits() == key.key_size
816 assert pkey._only_public is True
817 assert pkey._initialized is True
818
819 def test_convert_from_cryptography_unsupported_type(self):
820 """
821 PKey.from_cryptography_key raises TypeError with an unsupported type.
822 """
823 key = serialization.load_pem_private_key(
824 ec_private_key_pem, None, backend
825 )
826 with pytest.raises(TypeError):
827 PKey.from_cryptography_key(key)
828
829 def test_convert_public_pkey_to_cryptography_key(self):
830 """
831 PKey.to_cryptography_key creates a proper cryptography public key.
832 """
833 pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
834 key = pkey.to_cryptography_key()
835
836 assert isinstance(key, rsa.RSAPublicKey)
837 assert pkey.bits() == key.key_size
838
839 def test_convert_private_pkey_to_cryptography_key(self):
840 """
841 PKey.to_cryptography_key creates a proper cryptography private key.
842 """
843 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
844 key = pkey.to_cryptography_key()
845
846 assert isinstance(key, rsa.RSAPrivateKey)
847 assert pkey.bits() == key.key_size
848
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400849 def test_type(self):
850 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500851 `PKey` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400852 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000853 assert is_consistent_type(PKey, 'PKey')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400854
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500855 def test_construction(self):
856 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000857 `PKey` takes no arguments and returns a new `PKey` instance.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500858 """
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500859 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000860 assert isinstance(key, PKey)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500861
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500862 def test_pregeneration(self):
863 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000864 `PKey.bits` and `PKey.type` return `0` before the key is generated.
865 `PKey.check` raises `TypeError` before the key is generated.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500866 """
867 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000868 assert key.type() == 0
869 assert key.bits() == 0
870 with pytest.raises(TypeError):
871 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500872
Alex Chan9e2a9932017-01-25 14:29:19 +0000873 def test_failed_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500874 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000875 `PKey.generate_key` takes two arguments, the first giving the key type
876 as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
877 bits to generate. If an invalid type is specified or generation fails,
878 `Error` is raised. If an invalid number of bits is specified,
879 `ValueError` or `Error` is raised.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500880 """
881 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000882 with pytest.raises(TypeError):
883 key.generate_key("foo", "bar")
884 with pytest.raises(Error):
885 key.generate_key(-1, 0)
Jean-Paul Calderoneab82db72008-03-06 00:09:31 -0500886
Alex Chan9e2a9932017-01-25 14:29:19 +0000887 with pytest.raises(ValueError):
888 key.generate_key(TYPE_RSA, -1)
889 with pytest.raises(ValueError):
890 key.generate_key(TYPE_RSA, 0)
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500891
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400892 with pytest.raises(TypeError):
893 key.generate_key(TYPE_RSA, object())
894
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500895 # XXX RSA generation for small values of bits is fairly buggy in a wide
896 # range of OpenSSL versions. I need to figure out what the safe lower
897 # bound for a reasonable number of OpenSSL versions is and explicitly
898 # check for that in the wrapper. The failure behavior is typically an
899 # infinite loop inside OpenSSL.
900
Alex Chan9e2a9932017-01-25 14:29:19 +0000901 # with pytest.raises(Error):
902 # key.generate_key(TYPE_RSA, 2)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500903
904 # XXX DSA generation seems happy with any number of bits. The DSS
905 # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
906 # generator doesn't seem to care about the upper limit at all. For
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500907 # the lower limit, it uses 512 if anything smaller is specified.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500908 # So, it doesn't seem possible to make generate_key fail for
909 # TYPE_DSA with a bits argument which is at least an int.
910
Alex Chan9e2a9932017-01-25 14:29:19 +0000911 # with pytest.raises(Error):
912 # key.generate_key(TYPE_DSA, -7)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500913
Alex Chan9e2a9932017-01-25 14:29:19 +0000914 def test_rsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500915 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000916 `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
917 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500918 """
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400919 bits = 512
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500920 key = PKey()
921 key.generate_key(TYPE_RSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000922 assert key.type() == TYPE_RSA
923 assert key.bits() == bits
924 assert key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500925
Alex Chan9e2a9932017-01-25 14:29:19 +0000926 def test_dsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500927 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000928 `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
929 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500930 """
931 # 512 is a magic number. The DSS (Digital Signature Standard)
932 # allows a minimum of 512 bits for DSA. DSA_generate_parameters
933 # will silently promote any value below 512 to 512.
934 bits = 512
935 key = PKey()
936 key.generate_key(TYPE_DSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000937 assert key.type() == TYPE_DSA
938 assert key.bits() == bits
939 with pytest.raises(TypeError):
940 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500941
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500942 def test_regeneration(self):
943 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000944 `PKey.generate_key` can be called multiple times on the same key to
945 generate new keys.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500946 """
947 key = PKey()
948 for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
Alex Gaynor7f636492015-09-04 13:26:52 -0400949 key.generate_key(type, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000950 assert key.type() == type
951 assert key.bits() == bits
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500952
Alex Chan9e2a9932017-01-25 14:29:19 +0000953 def test_inconsistent_key(self):
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400954 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000955 `PKey.check` returns `Error` if the key is not consistent.
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400956 """
957 key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
Alex Chan9e2a9932017-01-25 14:29:19 +0000958 with pytest.raises(Error):
959 key.check()
Jean-Paul Calderonee81020e2011-06-12 21:48:57 -0400960
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400961 def test_check_public_key(self):
962 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000963 `PKey.check` raises `TypeError` if only the public part of the key
964 is available.
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400965 """
966 # A trick to get a public-only key
967 key = PKey()
968 key.generate_key(TYPE_RSA, 512)
969 cert = X509()
970 cert.set_pubkey(key)
971 pub = cert.get_pubkey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000972 with pytest.raises(TypeError):
973 pub.check()
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400974
Mrmaxmeier8cd3b172020-03-11 22:03:59 +0100975 def test_check_pr_897(self):
976 """
977 `PKey.check` raises `OpenSSL.crypto.Error` if provided with broken key
978 """
979 pkey = load_privatekey(FILETYPE_PEM, rsa_p_not_prime_pem)
980 with pytest.raises(Error):
981 pkey.check()
982
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400983
Alex Chan9e2a9932017-01-25 14:29:19 +0000984def x509_name(**attrs):
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500985 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000986 Return a new X509Name with the given attributes.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500987 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000988 # XXX There's no other way to get a new X509Name yet.
989 name = X509().get_subject()
990 attrs = list(attrs.items())
Alex Gaynoraceb3e22015-09-05 12:00:22 -0400991
Alex Chan9e2a9932017-01-25 14:29:19 +0000992 # Make the order stable - order matters!
993 def key(attr):
994 return attr[1]
995 attrs.sort(key=key)
996 for k, v in attrs:
997 setattr(name, k, v)
998 return name
Alex Gaynor85b49702015-09-05 16:30:59 -0400999
Alex Chan9e2a9932017-01-25 14:29:19 +00001000
1001class TestX509Name(object):
1002 """
1003 Unit tests for `OpenSSL.crypto.X509Name`.
1004 """
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001005
Rick Deane15b1472009-07-09 15:53:42 -05001006 def test_type(self):
1007 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001008 The type of X509Name objects is `X509Name`.
Rick Deane15b1472009-07-09 15:53:42 -05001009 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001010 name = x509_name()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001011 assert isinstance(name, X509Name)
Rick Deane15b1472009-07-09 15:53:42 -05001012
Alex Chan9e2a9932017-01-25 14:29:19 +00001013 def test_only_string_attributes(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001014 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001015 Attempting to set a non-`str` attribute name on an `X509Name` instance
1016 causes `TypeError` to be raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001017 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001018 name = x509_name()
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001019 # Beyond these cases, you may also think that unicode should be
Alex Gaynor31287502015-09-05 16:11:27 -04001020 # rejected. Sorry, you're wrong. unicode is automatically converted
1021 # to str outside of the control of X509Name, so there's no way to
1022 # reject it.
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -08001023
Alex Gaynor31287502015-09-05 16:11:27 -04001024 # Also, this used to test str subclasses, but that test is less
1025 # relevant now that the implementation is in Python instead of C. Also
1026 # PyPy automatically converts str subclasses to str when they are
1027 # passed to setattr, so we can't test it on PyPy. Apparently CPython
1028 # does this sometimes as well.
Alex Chan9e2a9932017-01-25 14:29:19 +00001029 with pytest.raises(TypeError):
1030 setattr(name, None, "hello")
1031 with pytest.raises(TypeError):
1032 setattr(name, 30, "hello")
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001033
Alex Chan9e2a9932017-01-25 14:29:19 +00001034 def test_set_invalid_attribute(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001035 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001036 Attempting to set any attribute name on an `X509Name` instance for
1037 which no corresponding NID is defined causes `AttributeError` to be
1038 raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001039 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001040 name = x509_name()
1041 with pytest.raises(AttributeError):
1042 setattr(name, "no such thing", None)
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001043
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001044 def test_attributes(self):
1045 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001046 `X509Name` instances have attributes for each standard (?)
1047 X509Name field.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001048 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001049 name = x509_name()
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001050 name.commonName = "foo"
Alex Gaynor37726112016-07-04 09:51:32 -04001051 assert name.commonName == "foo"
1052 assert name.CN == "foo"
1053
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001054 name.CN = "baz"
Alex Gaynor37726112016-07-04 09:51:32 -04001055 assert name.commonName == "baz"
1056 assert name.CN == "baz"
1057
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001058 name.commonName = "bar"
Alex Gaynor37726112016-07-04 09:51:32 -04001059 assert name.commonName == "bar"
1060 assert name.CN == "bar"
1061
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001062 name.CN = "quux"
Alex Gaynor37726112016-07-04 09:51:32 -04001063 assert name.commonName == "quux"
1064 assert name.CN == "quux"
1065
1066 assert name.OU is None
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001067
Alex Gaynor7778e792016-07-03 23:38:48 -04001068 with pytest.raises(AttributeError):
1069 name.foobar
1070
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001071 def test_copy(self):
1072 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001073 `X509Name` creates a new `X509Name` instance with all the same
1074 attributes as an existing `X509Name` instance when called with one.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001075 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001076 name = x509_name(commonName="foo", emailAddress="bar@example.com")
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001077
1078 copy = X509Name(name)
Alex Chan9e2a9932017-01-25 14:29:19 +00001079 assert copy.commonName == "foo"
1080 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001081
1082 # Mutate the copy and ensure the original is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001083 copy.commonName = "baz"
Alex Chan9e2a9932017-01-25 14:29:19 +00001084 assert name.commonName == "foo"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001085
1086 # Mutate the original and ensure the copy is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001087 name.emailAddress = "quux@example.com"
Alex Chan9e2a9932017-01-25 14:29:19 +00001088 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001089
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001090 def test_repr(self):
1091 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001092 `repr` passed an `X509Name` instance should return a string containing
1093 a description of the type and the NIDs which have been set on it.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001094 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001095 name = x509_name(commonName="foo", emailAddress="bar")
1096 assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001097
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001098 def test_comparison(self):
1099 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001100 `X509Name` instances should compare based on their NIDs.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001101 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001102 def _equality(a, b, assert_true, assert_false):
1103 assert_true(a == b)
1104 assert_false(a != b)
1105 assert_true(b == a)
1106 assert_false(b != a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001107
Alex Chan9e2a9932017-01-25 14:29:19 +00001108 def assert_true(x):
1109 assert x
1110
1111 def assert_false(x):
1112 assert not x
1113
1114 def assert_equal(a, b):
1115 _equality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001116
1117 # Instances compare equal to themselves.
Alex Chan9e2a9932017-01-25 14:29:19 +00001118 name = x509_name()
1119 assert_equal(name, name)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001120
1121 # Empty instances should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001122 assert_equal(x509_name(), x509_name())
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001123
1124 # Instances with equal NIDs should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001125 assert_equal(x509_name(commonName="foo"),
1126 x509_name(commonName="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001127
1128 # Instance with equal NIDs set using different aliases should compare
1129 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001130 assert_equal(x509_name(commonName="foo"),
1131 x509_name(CN="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001132
1133 # Instances with more than one NID with the same values should compare
1134 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001135 assert_equal(x509_name(CN="foo", organizationalUnitName="bar"),
1136 x509_name(commonName="foo", OU="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001137
Alex Chan9e2a9932017-01-25 14:29:19 +00001138 def assert_not_equal(a, b):
1139 _equality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001140
1141 # Instances with different values for the same NID should not compare
1142 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001143 assert_not_equal(x509_name(CN="foo"),
1144 x509_name(CN="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001145
1146 # Instances with different NIDs should not compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001147 assert_not_equal(x509_name(CN="foo"),
1148 x509_name(OU="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001149
Alex Chan9e2a9932017-01-25 14:29:19 +00001150 assert_not_equal(x509_name(), object())
Alex Gaynor7778e792016-07-03 23:38:48 -04001151
Alex Chan9e2a9932017-01-25 14:29:19 +00001152 def _inequality(a, b, assert_true, assert_false):
1153 assert_true(a < b)
1154 assert_true(a <= b)
1155 assert_true(b > a)
1156 assert_true(b >= a)
1157 assert_false(a > b)
1158 assert_false(a >= b)
1159 assert_false(b < a)
1160 assert_false(b <= a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001161
Alex Chan9e2a9932017-01-25 14:29:19 +00001162 def assert_less_than(a, b):
1163 _inequality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001164
1165 # An X509Name with a NID with a value which sorts less than the value
1166 # of the same NID on another X509Name compares less than the other
1167 # X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001168 assert_less_than(x509_name(CN="abc"),
1169 x509_name(CN="def"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001170
Alex Chan9e2a9932017-01-25 14:29:19 +00001171 def assert_greater_than(a, b):
1172 _inequality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001173
1174 # An X509Name with a NID with a value which sorts greater than the
1175 # value of the same NID on another X509Name compares greater than the
1176 # other X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001177 assert_greater_than(x509_name(CN="def"),
1178 x509_name(CN="abc"))
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001179
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001180 def test_hash(self):
1181 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001182 `X509Name.hash` returns an integer hash based on the value of the name.
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001183 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001184 a = x509_name(CN="foo")
1185 b = x509_name(CN="foo")
1186 assert a.hash() == b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001187 a.CN = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001188 assert a.hash() != b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001189
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001190 def test_der(self):
1191 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001192 `X509Name.der` returns the DER encoded form of the name.
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001193 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001194 a = x509_name(CN="foo", C="US")
1195 assert (a.der() ==
1196 b'0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
1197 b'1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo')
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001198
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001199 def test_get_components(self):
1200 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001201 `X509Name.get_components` returns a `list` of two-tuples of `str`
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001202 giving the NIDs and associated values which make up the name.
1203 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001204 a = x509_name()
1205 assert a.get_components() == []
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001206 a.CN = "foo"
Alex Chan9e2a9932017-01-25 14:29:19 +00001207 assert a.get_components() == [(b"CN", b"foo")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001208 a.organizationalUnitName = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001209 assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001210
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001211 def test_load_nul_byte_attribute(self):
1212 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001213 An `X509Name` from an `X509` instance loaded from a file can have a
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001214 NUL byte in the value of one of its attributes.
1215 """
1216 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1217 subject = cert.get_subject()
Alex Chan9e2a9932017-01-25 14:29:19 +00001218 assert "null.python.org\x00example.org" == subject.commonName
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001219
Romuald Brunet4183beb2019-01-21 19:38:33 +01001220 def test_load_nul_byte_components(self):
1221 """
1222 An `X509Name` from an `X509` instance loaded from a file can have a
1223 NUL byte in the value of its components
1224 """
1225 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1226 subject = cert.get_subject()
1227 components = subject.get_components()
1228 ccn = [value for name, value in components if name == b'CN']
1229 assert ccn[0] == b'null.python.org\x00example.org'
1230
Alex Chan9e2a9932017-01-25 14:29:19 +00001231 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001232 """
1233 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001234 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001235 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001236 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001237 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001238 with pytest.raises(Error):
1239 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001240
1241
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001242class _PKeyInteractionTestsMixin:
1243 """
1244 Tests which involve another thing and a PKey.
1245 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001246
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001247 def signable(self):
1248 """
Alex Chanfb078d82017-04-20 11:16:15 +01001249 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001250 """
1251 raise NotImplementedError()
1252
Alex Chanb00ede22017-01-30 07:24:40 +00001253 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001254 """
Alex Chanb00ede22017-01-30 07:24:40 +00001255 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001256 """
1257 request = self.signable()
1258 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001259 with pytest.raises(ValueError):
1260 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001261
Alex Chanb00ede22017-01-30 07:24:40 +00001262 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001263 """
Alex Chanb00ede22017-01-30 07:24:40 +00001264 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1265 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001266 """
1267 request = self.signable()
1268 key = PKey()
1269 key.generate_key(TYPE_RSA, 512)
1270 request.set_pubkey(key)
1271 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001272 with pytest.raises(ValueError):
1273 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001274
Alex Chanb00ede22017-01-30 07:24:40 +00001275 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001276 """
Alex Chanb00ede22017-01-30 07:24:40 +00001277 `X509Req.sign` raises `ValueError` when passed a digest name which is
1278 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001279 """
1280 request = self.signable()
1281 key = PKey()
1282 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001283 with pytest.raises(ValueError):
1284 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001285
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001286 def test_sign(self):
1287 """
Alex Chanb00ede22017-01-30 07:24:40 +00001288 `X509Req.sign` succeeds when passed a private key object and a
1289 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001290 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001291 """
1292 request = self.signable()
1293 key = PKey()
1294 key.generate_key(TYPE_RSA, 512)
1295 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001296 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001297 # If the type has a verify method, cover that too.
1298 if getattr(request, 'verify', None) is not None:
1299 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001300 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001301 # Make another key that won't verify.
1302 key = PKey()
1303 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001304 with pytest.raises(Error):
1305 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001306
1307
Alex Chanb00ede22017-01-30 07:24:40 +00001308class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001309 """
Alex Chanb00ede22017-01-30 07:24:40 +00001310 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001311 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001312
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001313 def signable(self):
1314 """
Alex Chanb00ede22017-01-30 07:24:40 +00001315 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001316 """
1317 return X509Req()
1318
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001319 def test_type(self):
1320 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001321 `X509Req` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001322 """
Alex Chanb00ede22017-01-30 07:24:40 +00001323 assert is_consistent_type(X509Req, 'X509Req')
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001324
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001325 def test_construction(self):
1326 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001327 `X509Req` takes no arguments and returns an `X509Req` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001328 """
1329 request = X509Req()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001330 assert isinstance(request, X509Req)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001331
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001332 def test_version(self):
1333 """
Alex Chanb00ede22017-01-30 07:24:40 +00001334 `X509Req.set_version` sets the X.509 version of the certificate
1335 request. `X509Req.get_version` returns the X.509 version of the
1336 certificate request. The initial value of the version is 0.
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001337 """
1338 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001339 assert request.get_version() == 0
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001340 request.set_version(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001341 assert request.get_version() == 1
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001342 request.set_version(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001343 assert request.get_version() == 3
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001344
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001345 def test_version_wrong_args(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001346 """
Alex Chanb00ede22017-01-30 07:24:40 +00001347 `X509Req.set_version` raises `TypeError` if called with a non-`int`
1348 argument.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001349 """
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001350 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001351 with pytest.raises(TypeError):
1352 request.set_version("foo")
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001353
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001354 def test_get_subject(self):
1355 """
Alex Chanb00ede22017-01-30 07:24:40 +00001356 `X509Req.get_subject` returns an `X509Name` for the subject of the
1357 request and which is valid even after the request object is
1358 otherwise dead.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001359 """
1360 request = X509Req()
1361 subject = request.get_subject()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001362 assert isinstance(subject, X509Name)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001363 subject.commonName = "foo"
Alex Chanb00ede22017-01-30 07:24:40 +00001364 assert request.get_subject().commonName == "foo"
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001365 del request
1366 subject.commonName = "bar"
Alex Chanb00ede22017-01-30 07:24:40 +00001367 assert subject.commonName == "bar"
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001368
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001369 def test_add_extensions(self):
1370 """
Alex Chanb00ede22017-01-30 07:24:40 +00001371 `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
1372 and adds them to the X509 request.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001373 """
1374 request = X509Req()
1375 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001376 X509Extension(b'basicConstraints', True, b'CA:false')])
Stephen Holsappleca545b72014-01-28 21:43:25 -08001377 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001378 assert len(exts) == 1
1379 assert exts[0].get_short_name() == b'basicConstraints'
1380 assert exts[0].get_critical() == 1
1381 assert exts[0].get_data() == b'0\x00'
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001382
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001383 def test_get_extensions(self):
1384 """
Alex Chanb00ede22017-01-30 07:24:40 +00001385 `X509Req.get_extensions` returns a `list` of extensions added to this
1386 X509 request.
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001387 """
1388 request = X509Req()
1389 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001390 assert exts == []
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001391 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001392 X509Extension(b'basicConstraints', True, b'CA:true'),
1393 X509Extension(b'keyUsage', False, b'digitalSignature')])
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001394 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001395 assert len(exts) == 2
1396 assert exts[0].get_short_name() == b'basicConstraints'
1397 assert exts[0].get_critical() == 1
1398 assert exts[0].get_data() == b'0\x03\x01\x01\xff'
1399 assert exts[1].get_short_name() == b'keyUsage'
1400 assert exts[1].get_critical() == 0
1401 assert exts[1].get_data() == b'\x03\x02\x07\x80'
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001402
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001403 def test_add_extensions_wrong_args(self):
1404 """
Alex Chanb00ede22017-01-30 07:24:40 +00001405 `X509Req.add_extensions` raises `TypeError` if called with a
1406 non-`list`. Or it raises `ValueError` if called with a `list`
1407 containing objects other than `X509Extension` instances.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001408 """
1409 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001410 with pytest.raises(TypeError):
1411 request.add_extensions(object())
1412 with pytest.raises(ValueError):
1413 request.add_extensions([object()])
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001414
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001415 def test_verify_wrong_args(self):
1416 """
Alex Chanb00ede22017-01-30 07:24:40 +00001417 `X509Req.verify` raises `TypeError` if passed anything other than a
1418 `PKey` instance as its single argument.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001419 """
1420 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001421 with pytest.raises(TypeError):
1422 request.verify(object())
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001423
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001424 def test_verify_uninitialized_key(self):
1425 """
Alex Chanb00ede22017-01-30 07:24:40 +00001426 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1427 `OpenSSL.crypto.PKey` which contains no key data.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001428 """
1429 request = X509Req()
1430 pkey = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001431 with pytest.raises(Error):
1432 request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001433
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001434 def test_verify_wrong_key(self):
1435 """
Alex Chanb00ede22017-01-30 07:24:40 +00001436 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1437 `OpenSSL.crypto.PKey` which does not represent the public part of the
Alex Gaynor31287502015-09-05 16:11:27 -04001438 key which signed the request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001439 """
1440 request = X509Req()
1441 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001442 request.sign(pkey, GOOD_DIGEST)
Alex Chanb00ede22017-01-30 07:24:40 +00001443 another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
1444 with pytest.raises(Error):
1445 request.verify(another_pkey)
1446
1447 def test_verify_success(self):
1448 """
1449 `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
1450 which represents the public part of the key which signed the request.
1451 """
1452 request = X509Req()
1453 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
1454 request.sign(pkey, GOOD_DIGEST)
1455 assert request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001456
Paul Kehrer41c10242017-06-29 18:24:17 -05001457 def test_convert_from_cryptography(self):
1458 crypto_req = x509.load_pem_x509_csr(
1459 cleartextCertificateRequestPEM, backend
1460 )
1461 req = X509Req.from_cryptography(crypto_req)
1462 assert isinstance(req, X509Req)
1463
1464 def test_convert_from_cryptography_unsupported_type(self):
1465 with pytest.raises(TypeError):
1466 X509Req.from_cryptography(object())
1467
1468 def test_convert_to_cryptography_key(self):
1469 req = load_certificate_request(
1470 FILETYPE_PEM, cleartextCertificateRequestPEM
1471 )
1472 crypto_req = req.to_cryptography()
1473 assert isinstance(crypto_req, x509.CertificateSigningRequest)
1474
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001475
Alex Chanb00ede22017-01-30 07:24:40 +00001476class TestX509(_PKeyInteractionTestsMixin):
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001477 """
Alex Chanb00ede22017-01-30 07:24:40 +00001478 Tests for `OpenSSL.crypto.X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001479 """
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001480 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Jean-Paul Calderone8114b452008-03-25 15:27:59 -04001481
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001482 extpem = """
1483-----BEGIN CERTIFICATE-----
1484MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
1485BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
1486eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
1487MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
1488aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
1489hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
1490Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
1491zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
1492hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
1493TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
149403HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
1495MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
1496b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
1497MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
1498uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
1499WpOdIpB8KksUTCzV591Nr1wd
1500-----END CERTIFICATE-----
1501 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001502
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001503 def signable(self):
1504 """
Alex Chanb00ede22017-01-30 07:24:40 +00001505 Create and return a new `X509`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001506 """
1507 return X509()
1508
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001509 def test_type(self):
1510 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001511 `X509` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001512 """
Alex Chanb00ede22017-01-30 07:24:40 +00001513 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001514
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001515 def test_construction(self):
1516 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05001517 `X509` takes no arguments and returns an instance of `X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001518 """
1519 certificate = X509()
Alex Gaynor01f90a12019-02-07 09:14:48 -05001520 assert isinstance(certificate, X509)
Alex Chanb00ede22017-01-30 07:24:40 +00001521 assert type(certificate).__name__ == 'X509'
Alex Chanb00ede22017-01-30 07:24:40 +00001522 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001523
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001524 def test_set_version_wrong_args(self):
1525 """
Alex Chanb00ede22017-01-30 07:24:40 +00001526 `X509.set_version` raises `TypeError` if invoked with an argument
1527 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001528 """
1529 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001530 with pytest.raises(TypeError):
1531 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001532
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001533 def test_version(self):
1534 """
Alex Chanb00ede22017-01-30 07:24:40 +00001535 `X509.set_version` sets the certificate version number.
1536 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001537 """
1538 cert = X509()
1539 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001540 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001541
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001542 def test_serial_number(self):
1543 """
Alex Chanb00ede22017-01-30 07:24:40 +00001544 The serial number of an `X509` can be retrieved and
1545 modified with `X509.get_serial_number` and
1546 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001547 """
1548 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001549 with pytest.raises(TypeError):
1550 certificate.set_serial_number("1")
1551 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001552 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001553 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001554 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001555 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001556 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001557 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001558 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001559 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001560
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001561 def _setBoundTest(self, which):
1562 """
Alex Chanb00ede22017-01-30 07:24:40 +00001563 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001564 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1565 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001566 """
1567 certificate = X509()
1568 set = getattr(certificate, 'set_not' + which)
1569 get = getattr(certificate, 'get_not' + which)
1570
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001571 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001572 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001573
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001574 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001575 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001576 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001577 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001578
1579 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001580 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001581 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001582 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001583
1584 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001585 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001586 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001587 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001588
1589 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001590 with pytest.raises(ValueError):
1591 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001592
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001593 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001594 with pytest.raises(TypeError):
1595 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001596 with pytest.raises(TypeError):
1597 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001598 with pytest.raises(TypeError):
1599 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001600
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001601 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001602
1603 def test_set_notBefore(self):
1604 """
Alex Chanb00ede22017-01-30 07:24:40 +00001605 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001606 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1607 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001608 """
1609 self._setBoundTest("Before")
1610
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001611 def test_set_notAfter(self):
1612 """
Alex Chanb00ede22017-01-30 07:24:40 +00001613 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001614 GENERALIZEDTIME and sets the end of the certificate's validity period
1615 to it.
1616 """
1617 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001618
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001619 def test_get_notBefore(self):
1620 """
Alex Chanb00ede22017-01-30 07:24:40 +00001621 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001622 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001623 internally.
1624 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001625 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001626 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001627
Rick Dean38a05c82009-07-18 01:41:30 -05001628 def test_get_notAfter(self):
1629 """
Alex Chanb00ede22017-01-30 07:24:40 +00001630 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001631 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001632 internally.
1633 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001634 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001635 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001636
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001637 def test_gmtime_adj_notBefore_wrong_args(self):
1638 """
Alex Chanb00ede22017-01-30 07:24:40 +00001639 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1640 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001641 """
1642 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001643 with pytest.raises(TypeError):
1644 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001645
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001646 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001647 def test_gmtime_adj_notBefore(self):
1648 """
Alex Chanb00ede22017-01-30 07:24:40 +00001649 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1650 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001651 """
1652 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001653 not_before_min = (
1654 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1655 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001656 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001657 not_before = datetime.strptime(
1658 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1659 )
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001660 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001661 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001662
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001663 def test_gmtime_adj_notAfter_wrong_args(self):
1664 """
Alex Chanb00ede22017-01-30 07:24:40 +00001665 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1666 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001667 """
1668 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001669 with pytest.raises(TypeError):
1670 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001671
Alex Gaynor642de6f2017-07-24 00:57:38 -04001672 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001673 def test_gmtime_adj_notAfter(self):
1674 """
Alex Chanb00ede22017-01-30 07:24:40 +00001675 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001676 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001677 """
1678 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001679 not_after_min = (
1680 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1681 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001682 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001683 not_after = datetime.strptime(
1684 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1685 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001686 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001687 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001688
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001689 def test_has_expired(self):
1690 """
Alex Chanb00ede22017-01-30 07:24:40 +00001691 `X509.has_expired` returns `True` if the certificate's not-after time
1692 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001693 """
1694 cert = X509()
1695 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001696 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001697
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001698 def test_has_not_expired(self):
1699 """
Alex Chanb00ede22017-01-30 07:24:40 +00001700 `X509.has_expired` returns `False` if the certificate's not-after time
1701 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001702 """
1703 cert = X509()
1704 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001705 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001706
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001707 def test_root_has_not_expired(self):
1708 """
Alex Chanb00ede22017-01-30 07:24:40 +00001709 `X509.has_expired` returns `False` if the certificate's not-after time
1710 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001711 """
1712 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001713 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001714
Rick Dean38a05c82009-07-18 01:41:30 -05001715 def test_digest(self):
1716 """
Alex Chanb00ede22017-01-30 07:24:40 +00001717 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001718 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001719 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001720 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001721 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001722 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1723 # actually matters to the assertion (ie, another arbitrary, good
1724 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001725 # Digest verified with the command:
1726 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001727 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001728 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001729
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001730 def _extcert(self, pkey, extensions):
1731 cert = X509()
David Benjamin6b799472020-06-24 17:14:16 -04001732 # Certificates with extensions must be X.509v3, which is encoded with a
1733 # version of two.
1734 cert.set_version(2)
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001735 cert.set_pubkey(pkey)
1736 cert.get_subject().commonName = "Unit Tests"
1737 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001738 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001739 cert.set_notBefore(when)
1740 cert.set_notAfter(when)
1741
1742 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001743 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001744 return load_certificate(
1745 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1746
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001747 def test_extension_count(self):
1748 """
Alex Chanb00ede22017-01-30 07:24:40 +00001749 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001750 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001751 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001752 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001753 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1754 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001755 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001756 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001757
1758 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001759 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001760 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001761
1762 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001763 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001764 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001765
1766 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001767 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001768 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001769
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001770 def test_get_extension(self):
1771 """
Alex Chanb00ede22017-01-30 07:24:40 +00001772 `X509.get_extension` takes an integer and returns an
1773 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001774 """
1775 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001776 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1777 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001778 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001779 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001780
1781 cert = self._extcert(pkey, [ca, key, subjectAltName])
1782
1783 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001784 assert isinstance(ext, X509Extension)
1785 assert ext.get_critical()
1786 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001787
1788 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001789 assert isinstance(ext, X509Extension)
1790 assert ext.get_critical()
1791 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001792
1793 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001794 assert isinstance(ext, X509Extension)
1795 assert not ext.get_critical()
1796 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001797
Alex Chanb00ede22017-01-30 07:24:40 +00001798 with pytest.raises(IndexError):
1799 cert.get_extension(-1)
1800 with pytest.raises(IndexError):
1801 cert.get_extension(4)
1802 with pytest.raises(TypeError):
1803 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001804
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001805 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001806 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001807 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001808 bytes and this value is reflected in the string representation of the
1809 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001810 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001811 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001812
1813 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001814 assert ext.get_short_name() == b'subjectAltName'
1815 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001816 b"DNS:altnull.python.org\x00example.com, "
1817 b"email:null@python.org\x00user@example.org, "
1818 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001819 b"IP Address:192.0.2.1, IP Address:2001:DB8:0:0:0:0:0:1\n" ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001820 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001821
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001822 def test_invalid_digest_algorithm(self):
1823 """
Alex Chanb00ede22017-01-30 07:24:40 +00001824 `X509.digest` raises `ValueError` if called with an unrecognized hash
1825 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001826 """
1827 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001828 with pytest.raises(ValueError):
1829 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001830
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001831 def test_get_subject(self):
1832 """
Alex Chanb00ede22017-01-30 07:24:40 +00001833 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001834 """
1835 cert = load_certificate(FILETYPE_PEM, self.pemData)
1836 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001837 assert isinstance(subj, X509Name)
1838 assert (
1839 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001840 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1841 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001842
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001843 def test_set_subject_wrong_args(self):
1844 """
Alex Chanb00ede22017-01-30 07:24:40 +00001845 `X509.set_subject` raises a `TypeError` if called with an argument not
1846 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001847 """
1848 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001849 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001850 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001851
1852 def test_set_subject(self):
1853 """
Alex Chanb00ede22017-01-30 07:24:40 +00001854 `X509.set_subject` changes the subject of the certificate to the one
1855 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001856 """
1857 cert = X509()
1858 name = cert.get_subject()
1859 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001860 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001861 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001862 assert (
1863 cert.get_subject().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001864 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001865
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001866 def test_get_issuer(self):
1867 """
Alex Chanb00ede22017-01-30 07:24:40 +00001868 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001869 """
1870 cert = load_certificate(FILETYPE_PEM, self.pemData)
1871 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001872 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001873 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001874 assert (
1875 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001876 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1877 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001878
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001879 def test_set_issuer_wrong_args(self):
1880 """
Alex Chanb00ede22017-01-30 07:24:40 +00001881 `X509.set_issuer` raises a `TypeError` if called with an argument not
1882 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001883 """
1884 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001885 with pytest.raises(TypeError):
1886 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001887
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001888 def test_set_issuer(self):
1889 """
Alex Chanb00ede22017-01-30 07:24:40 +00001890 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001891 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001892 """
1893 cert = X509()
1894 name = cert.get_issuer()
1895 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001896 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001897 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001898 assert (
1899 cert.get_issuer().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001900 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001901
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001902 def test_get_pubkey_uninitialized(self):
1903 """
Alex Chanb00ede22017-01-30 07:24:40 +00001904 When called on a certificate with no public key, `X509.get_pubkey`
1905 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001906 """
1907 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001908 with pytest.raises(Error):
1909 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001910
Alex Gaynor7778e792016-07-03 23:38:48 -04001911 def test_set_pubkey_wrong_type(self):
1912 """
Alex Chanb00ede22017-01-30 07:24:40 +00001913 `X509.set_pubkey` raises `TypeError` when given an object of the
1914 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001915 """
1916 cert = X509()
1917 with pytest.raises(TypeError):
1918 cert.set_pubkey(object())
1919
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001920 def test_subject_name_hash(self):
1921 """
Alex Chanb00ede22017-01-30 07:24:40 +00001922 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001923 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001924 """
1925 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor4cb05202019-02-02 11:06:41 -05001926 # SHA1
1927 assert cert.subject_name_hash() == 3278919224
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001928
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001929 def test_get_signature_algorithm(self):
1930 """
Alex Chanb00ede22017-01-30 07:24:40 +00001931 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001932 the algorithm used to sign the certificate.
1933 """
1934 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001935 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001936
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001937 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001938 """
Alex Chanb00ede22017-01-30 07:24:40 +00001939 `X509.get_signature_algorithm` raises `ValueError` if the signature
1940 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001941 """
1942 # This certificate has been modified to indicate a bogus OID in the
1943 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001944 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001945-----BEGIN CERTIFICATE-----
1946MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1947EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1948cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1949MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1950EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1951CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1952AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1953+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1954hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1955BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1956FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1957dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1958aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1959MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1960jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1961PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1962tgI5
1963-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001964"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001965 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001966 with pytest.raises(ValueError):
1967 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001968
Alex Gaynor37726112016-07-04 09:51:32 -04001969 def test_sign_bad_pubkey_type(self):
1970 """
Alex Chanb00ede22017-01-30 07:24:40 +00001971 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001972 """
1973 cert = X509()
1974 with pytest.raises(TypeError):
1975 cert.sign(object(), b"sha256")
1976
Alex Gaynor9939ba12017-06-25 16:28:24 -04001977 def test_convert_from_cryptography(self):
1978 crypto_cert = x509.load_pem_x509_certificate(
1979 intermediate_cert_pem, backend
1980 )
1981 cert = X509.from_cryptography(crypto_cert)
1982
1983 assert isinstance(cert, X509)
1984 assert cert.get_version() == crypto_cert.version.value
1985
1986 def test_convert_from_cryptography_unsupported_type(self):
1987 with pytest.raises(TypeError):
1988 X509.from_cryptography(object())
1989
1990 def test_convert_to_cryptography_key(self):
1991 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1992 crypto_cert = cert.to_cryptography()
1993
1994 assert isinstance(crypto_cert, x509.Certificate)
1995 assert crypto_cert.version.value == cert.get_version()
1996
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001997
Alex Chan9e2a9932017-01-25 14:29:19 +00001998class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001999 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002000 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002001 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002002
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002003 def test_type(self):
2004 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002005 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002007 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002008
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002010 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002011 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002012 """
2013 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002014 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002015 store.add_cert(cert)
2016
Alex Chanfb078d82017-04-20 11:16:15 +01002017 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2018 def test_add_cert_wrong_args(self, cert):
2019 """
2020 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2021 as its first argument.
2022 """
2023 store = X509Store()
2024 with pytest.raises(TypeError):
2025 store.add_cert(cert)
2026
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002027 def test_add_cert_accepts_duplicate(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002028 """
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002029 `X509Store.add_cert` doesn't raise `OpenSSL.crypto.Error` if an attempt
2030 is made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002031 """
2032 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2033 store = X509Store()
2034 store.add_cert(cert)
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002035 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002036
2037
Alex Chanb00ede22017-01-30 07:24:40 +00002038class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002039 """
Alex Chanb00ede22017-01-30 07:24:40 +00002040 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002041 """
2042 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2043
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002044 def test_type(self):
2045 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002046 `PKCS12` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002047 """
Alex Chanb00ede22017-01-30 07:24:40 +00002048 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002049
Rick Deanf94096c2009-07-18 14:23:06 -05002050 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002051 """
Alex Chanb00ede22017-01-30 07:24:40 +00002052 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2053 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002054 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002055 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002056 assert None is p12.get_certificate()
2057 assert None is p12.get_privatekey()
2058 assert None is p12.get_ca_certificates()
2059 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002060
2061 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002062 """
Alex Chanb00ede22017-01-30 07:24:40 +00002063 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2064 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2065 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002066 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002067 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002068 for bad_arg in [3, PKey(), X509]:
2069 with pytest.raises(TypeError):
2070 p12.set_certificate(bad_arg)
2071 for bad_arg in [3, 'legbone', X509()]:
2072 with pytest.raises(TypeError):
2073 p12.set_privatekey(bad_arg)
2074 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2075 with pytest.raises(TypeError):
2076 p12.set_ca_certificates(bad_arg)
2077 for bad_arg in [6, ('foo', 'bar')]:
2078 with pytest.raises(TypeError):
2079 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002080
2081 def test_key_only(self):
2082 """
Alex Chanb00ede22017-01-30 07:24:40 +00002083 A `PKCS12` with only a private key can be exported using
2084 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002085 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002086 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002087 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002088 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002089 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002090 assert None is p12.get_certificate()
2091 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002092 try:
2093 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2094 except Error:
2095 # Some versions of OpenSSL will throw an exception
2096 # for this nearly useless PKCS12 we tried to generate:
2097 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2098 return
Rick Dean623ee362009-07-17 12:22:16 -05002099 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002100 assert None is p12.get_ca_certificates()
2101 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002102
2103 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2104 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002105 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002106
2107 def test_cert_only(self):
2108 """
Alex Chanb00ede22017-01-30 07:24:40 +00002109 A `PKCS12` with only a certificate can be exported using
2110 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002111 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002112 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002113 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002114 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002115 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002116 assert cert == p12.get_certificate()
2117 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002118 try:
2119 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2120 except Error:
2121 # Some versions of OpenSSL will throw an exception
2122 # for this nearly useless PKCS12 we tried to generate:
2123 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2124 return
Rick Dean623ee362009-07-17 12:22:16 -05002125 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002126 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002127
2128 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002129 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002130
2131 # Oh ho. It puts the certificate into the ca certificates list, in
2132 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2133 # that to check to see if it reconstructed the certificate we expected
2134 # it to. At some point, hopefully this will change so that
2135 # p12.get_certificate() is actually what returns the loaded
2136 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002137 assert (
2138 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002139 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002140
Alex Gaynor31287502015-09-05 16:11:27 -04002141 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2142 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002143 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002144 Generate a PKCS12 object with components from PEM. Verify that the set
2145 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002146 """
Rick Deanf94096c2009-07-18 14:23:06 -05002147 p12 = PKCS12()
2148 if cert_pem:
2149 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002150 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002151 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002152 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002153 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002154 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002155 ret = p12.set_ca_certificates(
2156 (load_certificate(FILETYPE_PEM, ca_pem),)
2157 )
Alex Chanb00ede22017-01-30 07:24:40 +00002158 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002159 if friendly_name:
2160 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002161 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002162 return p12
2163
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002164 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002165 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002166 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002167 Use openssl program to confirm three components are recoverable from a
2168 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002169 """
2170 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002171 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002172 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2173 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002174 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002175 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002176 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002177 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2178 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002179 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002180 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002181 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002182 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2183 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002184 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002185
Stephen Holsapple38482622014-04-05 20:29:34 -07002186 def verify_pkcs12_container(self, p12):
2187 """
2188 Verify that the PKCS#12 container contains the correct client
2189 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002190
2191 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002192 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002193 """
2194 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2195 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002196 assert (
2197 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002198 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002199
Rick Deanf94096c2009-07-18 14:23:06 -05002200 def test_load_pkcs12(self):
2201 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002202 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002203 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002204 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002205 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002206 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002207 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002208 pem,
2209 b"pkcs12",
2210 b"-export",
2211 b"-clcerts",
2212 b"-passout",
2213 b"pass:" + passwd
2214 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002215 p12 = load_pkcs12(p12_str, passphrase=passwd)
2216 self.verify_pkcs12_container(p12)
2217
Abraham Martinc5484ba2015-03-25 15:33:05 +00002218 def test_load_pkcs12_text_passphrase(self):
2219 """
2220 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002221 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002222 Using text as passphrase instead of bytes. DeprecationWarning expected.
2223 """
2224 pem = client_key_pem + client_cert_pem
2225 passwd = b"whatever"
2226 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2227 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002228 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002229 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002230 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002231 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002232 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002233 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002234 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002235
Abraham Martinc5484ba2015-03-25 15:33:05 +00002236 self.verify_pkcs12_container(p12)
2237
Stephen Holsapple38482622014-04-05 20:29:34 -07002238 def test_load_pkcs12_no_passphrase(self):
2239 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002240 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002241 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002242 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002243 """
2244 pem = client_key_pem + client_cert_pem
2245 p12_str = _runopenssl(
2246 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2247 p12 = load_pkcs12(p12_str)
2248 self.verify_pkcs12_container(p12)
2249
Stephen Holsapple38482622014-04-05 20:29:34 -07002250 def _dump_and_load(self, dump_passphrase, load_passphrase):
2251 """
2252 A helper method to dump and load a PKCS12 object.
2253 """
2254 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2255 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2256 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2257
Stephen Holsapple38482622014-04-05 20:29:34 -07002258 def test_load_pkcs12_null_passphrase_load_empty(self):
2259 """
2260 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002261 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002262 extracted and examined.
2263 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002264 self.verify_pkcs12_container(
2265 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002266
Stephen Holsapple38482622014-04-05 20:29:34 -07002267 def test_load_pkcs12_null_passphrase_load_null(self):
2268 """
2269 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002270 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002271 extracted and examined.
2272 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002273 self.verify_pkcs12_container(
2274 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002275
Stephen Holsapple38482622014-04-05 20:29:34 -07002276 def test_load_pkcs12_empty_passphrase_load_empty(self):
2277 """
2278 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002279 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002280 extracted and examined.
2281 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002282 self.verify_pkcs12_container(
2283 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002284
Stephen Holsapple38482622014-04-05 20:29:34 -07002285 def test_load_pkcs12_empty_passphrase_load_null(self):
2286 """
2287 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002288 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002289 extracted and examined.
2290 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002291 self.verify_pkcs12_container(
2292 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002293
Rick Deanee568302009-07-24 09:56:29 -05002294 def test_load_pkcs12_garbage(self):
2295 """
Alex Chanb00ede22017-01-30 07:24:40 +00002296 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002297 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002298 """
2299 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002300 with pytest.raises(Error) as err:
2301 load_pkcs12(b'fruit loops', passwd)
2302 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2303 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002304
Rick Deanf94096c2009-07-18 14:23:06 -05002305 def test_replace(self):
2306 """
Alex Chanb00ede22017-01-30 07:24:40 +00002307 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2308 cluster. `PKCS12.set_privatekey` replaces the private key.
2309 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002310 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002311 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2312 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2313 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002314 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002315 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002316 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002317 assert 1 == len(p12.get_ca_certificates())
2318 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002319 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002320 assert 2 == len(p12.get_ca_certificates())
2321 assert client_cert == p12.get_ca_certificates()[0]
2322 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002323
Rick Deanf94096c2009-07-18 14:23:06 -05002324 def test_friendly_name(self):
2325 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002326 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002327 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2328 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002329 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002330 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002331 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002332 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002333 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002334 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002335 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002336 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002337 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002338 # We would use the openssl program to confirm the friendly
2339 # name, but it is not possible. The pkcs12 command
2340 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002341 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002342 self.check_recovery(
2343 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2344 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002345
Rick Deanf94096c2009-07-18 14:23:06 -05002346 def test_various_empty_passphrases(self):
2347 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002348 Test that missing, None, and '' passphrases are identical for PKCS12
2349 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002350 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002351 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002352 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002353 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2354 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2355 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2356 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2357 self.check_recovery(
2358 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2359 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002360
Rick Deanf94096c2009-07-18 14:23:06 -05002361 def test_removing_ca_cert(self):
2362 """
Alex Chanb00ede22017-01-30 07:24:40 +00002363 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2364 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002365 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002366 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2367 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002368 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002369
Rick Deanf94096c2009-07-18 14:23:06 -05002370 def test_export_without_mac(self):
2371 """
Alex Chanb00ede22017-01-30 07:24:40 +00002372 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002373 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002374 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002375 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002376 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002377 self.check_recovery(
2378 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002379 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002380
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002381 def test_load_without_mac(self):
2382 """
2383 Loading a PKCS12 without a MAC does something other than crash.
2384 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002385 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002386 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2387 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002388 try:
2389 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2390 # The person who generated this PCKS12 should be flogged,
2391 # or better yet we should have a means to determine
2392 # whether a PCKS12 had a MAC that was verified.
2393 # Anyway, libopenssl chooses to allow it, so the
2394 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002395 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002396 except Error:
2397 # Failing here with an exception is preferred as some openssl
2398 # versions do.
2399 pass
Rick Dean623ee362009-07-17 12:22:16 -05002400
Rick Dean25bcc1f2009-07-20 11:53:13 -05002401 def test_zero_len_list_for_ca(self):
2402 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002403 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002404 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002405 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002406 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002407 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002408 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002409 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2410 self.check_recovery(
2411 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2412 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002413
Rick Deanf94096c2009-07-18 14:23:06 -05002414 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002415 """
Alex Chanb00ede22017-01-30 07:24:40 +00002416 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002417 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002418 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002419 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002420 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002421 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002422
Abraham Martinc5484ba2015-03-25 15:33:05 +00002423 def test_export_without_bytes(self):
2424 """
Alex Chanb00ede22017-01-30 07:24:40 +00002425 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002426 """
2427 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2428
Alex Chanb00ede22017-01-30 07:24:40 +00002429 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002430 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002431 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002432 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002433 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002434 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002435 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002436 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002437 dumped_p12,
2438 key=server_key_pem,
2439 cert=server_cert_pem,
2440 passwd=b"randomtext"
2441 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002442
Rick Deanf94096c2009-07-18 14:23:06 -05002443 def test_key_cert_mismatch(self):
2444 """
Alex Chanb00ede22017-01-30 07:24:40 +00002445 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002446 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002447 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002448 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002449 with pytest.raises(Error):
2450 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002451
2452
Rick Dean4c9ad612009-07-17 15:05:22 -05002453def _runopenssl(pem, *args):
2454 """
2455 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002456 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002457 """
Alex Gaynor6cbc69a2017-07-25 09:07:04 -04002458 proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002459 proc.stdin.write(pem)
2460 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002461 output = proc.stdout.read()
2462 proc.stdout.close()
2463 proc.wait()
2464 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002465
2466
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002467class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002468 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002469 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002470 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002471 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002472 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002473 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002474 """
2475 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002476
2477 assert True is key._only_public
2478 assert 2048 == key.bits()
2479 assert TYPE_RSA == key.type()
2480
2481 def test_invalid_type(self):
2482 """
2483 load_publickey doesn't support FILETYPE_TEXT.
2484 """
2485 with pytest.raises(ValueError):
2486 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2487
2488 def test_invalid_key_format(self):
2489 """
2490 load_publickey explodes on incorrect keys.
2491 """
2492 with pytest.raises(Error):
2493 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2494
2495 def test_tolerates_unicode_strings(self):
2496 """
2497 load_publickey works with text strings, not just bytes.
2498 """
2499 serialized = cleartextPublicKeyPEM.decode('ascii')
2500 key = load_publickey(FILETYPE_PEM, serialized)
2501 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2502
2503 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002504
2505
Alex Chanb00ede22017-01-30 07:24:40 +00002506class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002507 """
Alex Chanb00ede22017-01-30 07:24:40 +00002508 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002509 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002510
2511 def test_load_privatekey_invalid_format(self):
2512 """
Alex Chanb00ede22017-01-30 07:24:40 +00002513 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002514 """
Alex Chanb00ede22017-01-30 07:24:40 +00002515 with pytest.raises(ValueError):
2516 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002517
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002518 def test_load_privatekey_invalid_passphrase_type(self):
2519 """
Alex Chanb00ede22017-01-30 07:24:40 +00002520 `load_privatekey` raises `TypeError` if passed a passphrase that is
2521 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002522 """
Alex Chanb00ede22017-01-30 07:24:40 +00002523 with pytest.raises(TypeError):
2524 load_privatekey(
2525 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002526
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002527 def test_load_privatekey_wrongPassphrase(self):
2528 """
Alex Chanb00ede22017-01-30 07:24:40 +00002529 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2530 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002531 """
Alex Chanb00ede22017-01-30 07:24:40 +00002532 with pytest.raises(Error) as err:
2533 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2534 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002535
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002536 def test_load_privatekey_passphraseWrongType(self):
2537 """
Alex Chanb00ede22017-01-30 07:24:40 +00002538 `load_privatekey` raises `ValueError` when it is passeda passphrase
2539 with a private key encoded in a format, that doesn't support
2540 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002541 """
2542 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2543 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002544 with pytest.raises(ValueError):
2545 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002546
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002547 def test_load_privatekey_passphrase(self):
2548 """
Alex Chanb00ede22017-01-30 07:24:40 +00002549 `load_privatekey` can create a `PKey` object from an encrypted PEM
2550 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002551 """
2552 key = load_privatekey(
2553 FILETYPE_PEM, encryptedPrivateKeyPEM,
2554 encryptedPrivateKeyPEMPassphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002555 assert isinstance(key, PKey)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002556
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002557 def test_load_privatekey_passphrase_exception(self):
2558 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002559 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002560 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002561 """
2562 def cb(ignored):
2563 raise ArithmeticError
2564
Alex Gaynor791212d2015-09-05 15:46:08 -04002565 with pytest.raises(ArithmeticError):
2566 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002567
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002568 def test_load_privatekey_wrongPassphraseCallback(self):
2569 """
Alex Chanb00ede22017-01-30 07:24:40 +00002570 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002571 is passed an encrypted PEM and a passphrase callback which returns an
2572 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002573 """
2574 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002575
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002576 def cb(*a):
2577 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002578 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002579 with pytest.raises(Error) as err:
2580 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2581 assert called
2582 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002583
2584 def test_load_privatekey_passphraseCallback(self):
2585 """
Alex Chanb00ede22017-01-30 07:24:40 +00002586 `load_privatekey` can create a `PKey` object from an encrypted PEM
2587 string if given a passphrase callback which returns the correct
2588 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002589 """
2590 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002591
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002592 def cb(writing):
2593 called.append(writing)
2594 return encryptedPrivateKeyPEMPassphrase
2595 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002596 assert isinstance(key, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002597 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002598
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002599 def test_load_privatekey_passphrase_wrong_return_type(self):
2600 """
Alex Chanb00ede22017-01-30 07:24:40 +00002601 `load_privatekey` raises `ValueError` if the passphrase callback
2602 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002603 """
Alex Chanb00ede22017-01-30 07:24:40 +00002604 with pytest.raises(ValueError):
2605 load_privatekey(
2606 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002607
Alex Chanfb078d82017-04-20 11:16:15 +01002608 def test_dump_privatekey_wrong_args(self):
2609 """
2610 `dump_privatekey` raises `TypeError` if called with a `cipher`
2611 argument but no `passphrase` argument.
2612 """
2613 key = PKey()
2614 key.generate_key(TYPE_RSA, 512)
2615 with pytest.raises(TypeError):
2616 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2617
Paul Kehrercded9932017-06-29 18:43:42 -05002618 def test_dump_privatekey_not_rsa_key(self):
2619 """
2620 `dump_privatekey` raises `TypeError` if called with a key that is
2621 not RSA.
2622 """
2623 key = PKey()
2624 key.generate_key(TYPE_DSA, 512)
2625 with pytest.raises(TypeError):
2626 dump_privatekey(FILETYPE_TEXT, key)
2627
2628 def test_dump_privatekey_invalid_pkey(self):
2629 with pytest.raises(TypeError):
2630 dump_privatekey(FILETYPE_TEXT, object())
2631
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002632 def test_dump_privatekey_unknown_cipher(self):
2633 """
Alex Chanb00ede22017-01-30 07:24:40 +00002634 `dump_privatekey` raises `ValueError` if called with an unrecognized
2635 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002636 """
2637 key = PKey()
2638 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002639 with pytest.raises(ValueError):
2640 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002641
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002642 def test_dump_privatekey_invalid_passphrase_type(self):
2643 """
Alex Chanb00ede22017-01-30 07:24:40 +00002644 `dump_privatekey` raises `TypeError` if called with a passphrase which
2645 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002646 """
2647 key = PKey()
2648 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002649 with pytest.raises(TypeError):
2650 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002651
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002652 def test_dump_privatekey_invalid_filetype(self):
2653 """
Alex Chanb00ede22017-01-30 07:24:40 +00002654 `dump_privatekey` raises `ValueError` if called with an unrecognized
2655 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002656 """
2657 key = PKey()
2658 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002659 with pytest.raises(ValueError):
2660 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002661
Alex Chanb00ede22017-01-30 07:24:40 +00002662 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002663 """
Alex Chanb00ede22017-01-30 07:24:40 +00002664 `crypto.load_privatekey` should raise an error when the passphrase
2665 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002666 """
2667 def cb(ignored):
2668 return "a" * 1025
2669
Alex Gaynor791212d2015-09-05 15:46:08 -04002670 with pytest.raises(ValueError):
2671 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002672
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002673 def test_dump_privatekey_passphrase(self):
2674 """
Alex Chanb00ede22017-01-30 07:24:40 +00002675 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002676 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002677 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002678 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002679 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Gaynor12576002019-11-18 00:18:50 -05002680 assert isinstance(pem, bytes)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002681 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002682 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002683 assert loadedKey.type() == key.type()
2684 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002685
Alex Chanb00ede22017-01-30 07:24:40 +00002686 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002687 """
Alex Chanb00ede22017-01-30 07:24:40 +00002688 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2689 with a private key encoded in a format, that doesn't support
2690 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002691 """
2692 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002693 with pytest.raises(ValueError):
2694 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002695
Rick Dean5b7b6372009-04-01 11:34:06 -05002696 def test_dump_certificate(self):
2697 """
Alex Chanb00ede22017-01-30 07:24:40 +00002698 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002699 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002700 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002701 cert = load_certificate(FILETYPE_PEM, pemData)
2702 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002703 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002704 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002705 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002706 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002707 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2708 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002709 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002710 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002711 good_text = _runopenssl(
2712 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002713 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002714
Alex Gaynor37726112016-07-04 09:51:32 -04002715 def test_dump_certificate_bad_type(self):
2716 """
Alex Chanb00ede22017-01-30 07:24:40 +00002717 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002718 a bad type.
2719 """
2720 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2721 with pytest.raises(ValueError):
2722 dump_certificate(object(), cert)
2723
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002724 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002725 """
Alex Chanb00ede22017-01-30 07:24:40 +00002726 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002727 """
2728 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002729 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002730 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002731 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002732
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002733 def test_dump_privatekey_asn1(self):
2734 """
Alex Chanb00ede22017-01-30 07:24:40 +00002735 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002736 """
2737 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2738 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2739
Rick Dean5b7b6372009-04-01 11:34:06 -05002740 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002741 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002742 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002743 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002744 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2745 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002746 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002747
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002748 def test_dump_privatekey_text(self):
2749 """
Alex Chanb00ede22017-01-30 07:24:40 +00002750 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002751 """
2752 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2753 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2754
Rick Dean5b7b6372009-04-01 11:34:06 -05002755 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002756 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002757 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002758
Cory Benfield6492f7c2015-10-27 16:57:58 +09002759 def test_dump_publickey_pem(self):
2760 """
Cory Benfield11c10192015-10-27 17:23:03 +09002761 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002762 """
2763 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2764 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002765 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002766
2767 def test_dump_publickey_asn1(self):
2768 """
Cory Benfield11c10192015-10-27 17:23:03 +09002769 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002770 """
2771 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2772 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2773 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2774 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002775 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002776
Cory Benfielde02c7d82015-10-27 17:34:49 +09002777 def test_dump_publickey_invalid_type(self):
2778 """
2779 dump_publickey doesn't support FILETYPE_TEXT.
2780 """
2781 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2782
2783 with pytest.raises(ValueError):
2784 dump_publickey(FILETYPE_TEXT, key)
2785
Rick Dean5b7b6372009-04-01 11:34:06 -05002786 def test_dump_certificate_request(self):
2787 """
Alex Chanb00ede22017-01-30 07:24:40 +00002788 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002789 """
Alex Gaynor31287502015-09-05 16:11:27 -04002790 req = load_certificate_request(
2791 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002792 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002793 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002794 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002795 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002796 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002797 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2798 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002799 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002800 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002801 good_text = _runopenssl(
2802 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002803 assert dumped_text == good_text
2804 with pytest.raises(ValueError):
2805 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002806
Alex Chanb00ede22017-01-30 07:24:40 +00002807 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002808 """
Alex Chanb00ede22017-01-30 07:24:40 +00002809 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002810 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002811 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002812 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002813 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002814
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002815 def cb(writing):
2816 called.append(writing)
2817 return passphrase
2818 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002819 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Gaynor12576002019-11-18 00:18:50 -05002820 assert isinstance(pem, bytes)
Alex Chanb00ede22017-01-30 07:24:40 +00002821 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002822 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002823 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002824 assert loadedKey.type() == key.type()
2825 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002826
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002827 def test_dump_privatekey_passphrase_exception(self):
2828 """
Alex Chanb00ede22017-01-30 07:24:40 +00002829 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002830 by the passphrase callback.
2831 """
2832 def cb(ignored):
2833 raise ArithmeticError
2834
2835 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002836 with pytest.raises(ArithmeticError):
2837 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002838
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002839 def test_dump_privatekey_passphraseCallbackLength(self):
2840 """
Alex Chanb00ede22017-01-30 07:24:40 +00002841 `crypto.dump_privatekey` should raise an error when the passphrase
2842 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002843 """
2844 def cb(ignored):
2845 return "a" * 1025
2846
2847 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002848 with pytest.raises(ValueError):
2849 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002850
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002851 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002852 """
Alex Chanb00ede22017-01-30 07:24:40 +00002853 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2854 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002855 """
2856 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002857 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002858
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002859 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002860 """
Alex Chanb00ede22017-01-30 07:24:40 +00002861 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2862 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002863 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002864 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002865 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002866
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002867 def test_load_pkcs7_data_invalid(self):
2868 """
Alex Chanb00ede22017-01-30 07:24:40 +00002869 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002870 """
Alex Chanb00ede22017-01-30 07:24:40 +00002871 with pytest.raises(Error):
2872 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002873
Alex Gaynor09a386e2016-07-03 09:32:44 -04002874 def test_load_pkcs7_type_invalid(self):
2875 """
Alex Chanb00ede22017-01-30 07:24:40 +00002876 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002877 """
2878 with pytest.raises(ValueError):
2879 load_pkcs7_data(object(), b"foo")
2880
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002881
Alex Chan9e2a9932017-01-25 14:29:19 +00002882class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002883 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002884 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002885 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002886
Alex Chan9e2a9932017-01-25 14:29:19 +00002887 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002888 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002889 If the file type passed to `load_certificate_request` is neither
2890 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002891 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002892 with pytest.raises(ValueError):
2893 load_certificate_request(object(), b"")
2894 with pytest.raises(ValueError):
2895 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002896
Alex Gaynor37726112016-07-04 09:51:32 -04002897 def test_bad_certificate(self):
2898 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002899 If the bytes passed to `load_certificate` are not a valid certificate,
2900 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002901 """
2902 with pytest.raises(Error):
2903 load_certificate(FILETYPE_ASN1, b"lol")
2904
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002905
Alex Chanb00ede22017-01-30 07:24:40 +00002906class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002907 """
Alex Chanb00ede22017-01-30 07:24:40 +00002908 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002909 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002910
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002911 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002912 """
Alex Chanb00ede22017-01-30 07:24:40 +00002913 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2914 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002915 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002916 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002917 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002918
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002919 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002920 """
Alex Chanb00ede22017-01-30 07:24:40 +00002921 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2922 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002923 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002924 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002925 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002926
Alex Chanb00ede22017-01-30 07:24:40 +00002927 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002928 """
Alex Chanb00ede22017-01-30 07:24:40 +00002929 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002930 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002931 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002932 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002933 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002934
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002935 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002936 """
Alex Chanb00ede22017-01-30 07:24:40 +00002937 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2938 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002939 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002940 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002941 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002942
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002943 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002944 """
Alex Chanb00ede22017-01-30 07:24:40 +00002945 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002946 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002947 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002948 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002949 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002950
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002951 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002952 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002953 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002954 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002955 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002956 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002957 with pytest.raises(AttributeError):
2958 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002959
2960
Alex Chanb00ede22017-01-30 07:24:40 +00002961class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002962 """
Alex Chanb00ede22017-01-30 07:24:40 +00002963 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002964 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002965
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002966 def signable(self):
2967 """
Alex Chanb00ede22017-01-30 07:24:40 +00002968 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002969 """
2970 return NetscapeSPKI()
2971
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002972 def test_type(self):
2973 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002974 `NetscapeSPKI` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002975 """
Alex Chanb00ede22017-01-30 07:24:40 +00002976 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002977
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002978 def test_construction(self):
2979 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002980 `NetscapeSPKI` returns an instance of `NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002981 """
2982 nspki = NetscapeSPKI()
Alex Gaynor01f90a12019-02-07 09:14:48 -05002983 assert isinstance(nspki, NetscapeSPKI)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002984
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002985 def test_invalid_attribute(self):
2986 """
Alex Chanb00ede22017-01-30 07:24:40 +00002987 Accessing a non-existent attribute of a `NetscapeSPKI` instance
2988 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002989 """
2990 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002991 with pytest.raises(AttributeError):
2992 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002993
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002994 def test_b64_encode(self):
2995 """
Alex Chanb00ede22017-01-30 07:24:40 +00002996 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002997 """
2998 nspki = NetscapeSPKI()
2999 blob = nspki.b64_encode()
Alex Gaynor12576002019-11-18 00:18:50 -05003000 assert isinstance(blob, bytes)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003001
3002
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003003class TestRevoked(object):
3004 """
Alex Chandeec9342016-12-19 22:00:38 +00003005 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003006 """
3007 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
3008 """
3009 The get_reason method on the Revoked class checks to see if the
3010 extension is NID_crl_reason and should skip it otherwise. This test
3011 loads a CRL with extensions it should ignore.
3012 """
3013 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3014 revoked = crl.get_revoked()
3015 reason = revoked[1].get_reason()
3016 assert reason == b'Unspecified'
3017
3018 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3019 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3020 revoked = crl.get_revoked()
3021 revoked[1].set_reason(None)
3022 reason = revoked[1].get_reason()
3023 assert reason is None
3024
Rick Dean536ba022009-07-24 23:57:27 -05003025 def test_construction(self):
3026 """
Alex Chandeec9342016-12-19 22:00:38 +00003027 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3028 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003029 """
3030 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003031 assert isinstance(revoked, Revoked)
3032 assert type(revoked) == Revoked
3033 assert revoked.get_serial() == b'00'
3034 assert revoked.get_rev_date() is None
3035 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003036
Rick Dean536ba022009-07-24 23:57:27 -05003037 def test_serial(self):
3038 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003039 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003040 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003041 """
3042 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003043 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003044 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003045 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003046 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003047
Alex Gaynore7f51982016-09-11 11:48:14 -04003048 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003049 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003050 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003051
Alex Chandeec9342016-12-19 22:00:38 +00003052 with pytest.raises(ValueError):
3053 revoked.set_serial(b'pqrst')
3054 with pytest.raises(TypeError):
3055 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003056
Rick Dean536ba022009-07-24 23:57:27 -05003057 def test_date(self):
3058 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003059 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003060 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003061 """
3062 revoked = Revoked()
3063 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003064 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003065
Alex Gaynore7f51982016-09-11 11:48:14 -04003066 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003067 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003068 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003069 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003070 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003071
Rick Dean6385faf2009-07-26 00:07:47 -05003072 def test_reason(self):
3073 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003074 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003075 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3076 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003077 """
3078 revoked = Revoked()
3079 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003080 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003081 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003082 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003083 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003084 assert (
3085 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003086 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003087 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003088
3089 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003090 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003091
Alex Chanfb078d82017-04-20 11:16:15 +01003092 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3093 def test_set_reason_wrong_args(self, reason):
3094 """
3095 `Revoked.set_reason` raises `TypeError` if called with an argument
3096 which is neither `None` nor a byte string.
3097 """
3098 revoked = Revoked()
3099 with pytest.raises(TypeError):
3100 revoked.set_reason(reason)
3101
Alex Chandeec9342016-12-19 22:00:38 +00003102 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003103 """
Alex Chandeec9342016-12-19 22:00:38 +00003104 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3105 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003106 """
3107 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003108 with pytest.raises(ValueError):
3109 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003110
3111
Alex Chan7be83a52017-01-24 15:19:29 +00003112class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003113 """
Alex Chan7be83a52017-01-24 15:19:29 +00003114 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003115 """
3116 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3117 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3118
Dan Sully44e767a2016-06-04 18:05:27 -07003119 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3120 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3121 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3122 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3123 intermediate_server_cert = load_certificate(
3124 FILETYPE_PEM, intermediate_server_cert_pem)
3125 intermediate_server_key = load_privatekey(
3126 FILETYPE_PEM, intermediate_server_key_pem)
3127
Rick Dean536ba022009-07-24 23:57:27 -05003128 def test_construction(self):
3129 """
Alex Chan7be83a52017-01-24 15:19:29 +00003130 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003131 that it is empty
3132 """
3133 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003134 assert isinstance(crl, CRL)
3135 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003136
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003137 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003138 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003139 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003140 """
3141 crl = CRL()
3142 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003143 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003144 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003145 revoked.set_serial(b'3ab')
3146 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003147 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003148 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003149
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003150 def test_export_pem(self):
3151 """
3152 If not passed a format, ``CRL.export`` returns a "PEM" format string
3153 representing a serial number, a revoked reason, and certificate issuer
3154 information.
3155 """
Rick Dean536ba022009-07-24 23:57:27 -05003156 # PEM format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003157 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003158 self.cert, self.pkey, days=20, digest=b"sha256"
3159 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003160 crl = x509.load_pem_x509_crl(dumped_crl, backend)
3161 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3162 assert revoked is not None
3163 assert crl.issuer == x509.Name([
3164 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3165 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3166 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3167 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3168 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3169 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003170
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003171 def test_export_der(self):
3172 """
3173 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3174 "DER" format string representing a serial number, a revoked reason, and
3175 certificate issuer information.
3176 """
3177 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003178
3179 # DER format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003180 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003181 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3182 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003183 crl = x509.load_der_x509_crl(dumped_crl, backend)
3184 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3185 assert revoked is not None
3186 assert crl.issuer == x509.Name([
3187 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3188 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3189 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3190 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3191 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3192 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003193
Alex Gaynore466bc92017-07-06 23:43:47 -04003194 # Flaky because we compare the output of running commands which sometimes
3195 # varies by 1 second
3196 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003197 def test_export_text(self):
3198 """
3199 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3200 text format string like the one produced by the openssl command line
3201 tool.
3202 """
3203 crl = self._get_crl()
3204
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003205 dumped_crl = crl.export(
3206 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3207 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003208 text = _runopenssl(
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003209 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER",
3210 b"-nameopt", b""
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003211 )
Rick Dean536ba022009-07-24 23:57:27 -05003212
3213 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003214 dumped_text = crl.export(
3215 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3216 )
Alex Chan7be83a52017-01-24 15:19:29 +00003217 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003218
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003219 def test_export_custom_digest(self):
3220 """
3221 If passed the name of a digest function, ``CRL.export`` uses a
3222 signature algorithm based on that digest function.
3223 """
3224 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003225 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003226 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003227 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003228
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003229 def test_export_md5_digest(self):
3230 """
3231 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3232 not emit a deprecation warning.
3233 """
3234 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003235 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003236 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003237 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003238 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3239 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003240 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003241
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003242 def test_export_default_digest(self):
3243 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003244 If not passed the name of a digest function, ``CRL.export`` raises a
3245 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003246 """
3247 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003248 with pytest.raises(TypeError):
3249 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003250
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003251 def test_export_invalid(self):
3252 """
Alex Chan7be83a52017-01-24 15:19:29 +00003253 If `CRL.export` is used with an uninitialized `X509` instance,
3254 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003255 """
3256 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003257 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003258 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003259
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003260 def test_add_revoked_keyword(self):
3261 """
Alex Chan7be83a52017-01-24 15:19:29 +00003262 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003263 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003264 """
3265 crl = CRL()
3266 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003267 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003268 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003269 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003270 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003271
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003272 def test_export_wrong_args(self):
3273 """
Alex Chan7be83a52017-01-24 15:19:29 +00003274 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003275 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003276 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003277 """
3278 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003279 with pytest.raises(TypeError):
3280 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3281 with pytest.raises(TypeError):
3282 crl.export(self.cert, None, FILETYPE_PEM, 10)
3283 with pytest.raises(TypeError):
3284 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003285 with pytest.raises(TypeError):
3286 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003287
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003288 def test_export_unknown_filetype(self):
3289 """
Alex Chan7be83a52017-01-24 15:19:29 +00003290 Calling `OpenSSL.CRL.export` with a file type other than
3291 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3292 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003293 """
3294 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003295 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003296 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003297
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003298 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003299 """
Alex Chan7be83a52017-01-24 15:19:29 +00003300 Calling `OpenSSL.CRL.export` with an unsupported digest results
3301 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003302 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003303 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003304 with pytest.raises(ValueError):
3305 crl.export(
3306 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003307
Rick Dean536ba022009-07-24 23:57:27 -05003308 def test_get_revoked(self):
3309 """
Alex Chan7be83a52017-01-24 15:19:29 +00003310 Use python to create a simple CRL with two revocations. Get back the
3311 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003312 """
3313 crl = CRL()
3314
3315 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003316 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003317 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003318 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003319 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003320 revoked.set_serial(b'100')
3321 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003322 crl.add_revoked(revoked)
3323
3324 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003325 assert len(revs) == 2
3326 assert type(revs[0]) == Revoked
3327 assert type(revs[1]) == Revoked
3328 assert revs[0].get_serial() == b'03AB'
3329 assert revs[1].get_serial() == b'0100'
3330 assert revs[0].get_rev_date() == now
3331 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003332
Rick Dean536ba022009-07-24 23:57:27 -05003333 def test_load_crl(self):
3334 """
Alex Chan7be83a52017-01-24 15:19:29 +00003335 Load a known CRL and inspect its revocations. Both EM and DER formats
3336 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003337 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003338 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003339 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003340 assert len(revs) == 2
3341 assert revs[0].get_serial() == b'03AB'
3342 assert revs[0].get_reason() is None
3343 assert revs[1].get_serial() == b'0100'
3344 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003345
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003346 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003347 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003348 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003349 assert len(revs) == 2
3350 assert revs[0].get_serial() == b'03AB'
3351 assert revs[0].get_reason() is None
3352 assert revs[1].get_serial() == b'0100'
3353 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003354
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003355 def test_load_crl_bad_filetype(self):
3356 """
Alex Chan7be83a52017-01-24 15:19:29 +00003357 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3358 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003359 """
Alex Chan7be83a52017-01-24 15:19:29 +00003360 with pytest.raises(ValueError):
3361 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003362
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003363 def test_load_crl_bad_data(self):
3364 """
Alex Chan7be83a52017-01-24 15:19:29 +00003365 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3366 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003367 """
Alex Chan7be83a52017-01-24 15:19:29 +00003368 with pytest.raises(Error):
3369 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003370
Dan Sully44e767a2016-06-04 18:05:27 -07003371 def test_get_issuer(self):
3372 """
Alex Chan7be83a52017-01-24 15:19:29 +00003373 Load a known CRL and assert its issuer's common name is what we expect
3374 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003375 """
3376 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003377 assert isinstance(crl.get_issuer(), X509Name)
3378 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003379
Dominic Chenf05b2122015-10-13 16:32:35 +00003380 def test_dump_crl(self):
3381 """
3382 The dumped CRL matches the original input.
3383 """
3384 crl = load_crl(FILETYPE_PEM, crlData)
3385 buf = dump_crl(FILETYPE_PEM, crl)
3386 assert buf == crlData
3387
Dan Sully44e767a2016-06-04 18:05:27 -07003388 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3389 """
3390 Create a CRL.
3391
3392 :param list[X509] certs: A list of certificates to revoke.
3393 :rtype: CRL
3394 """
3395 crl = CRL()
3396 for cert in certs:
3397 revoked = Revoked()
3398 # FIXME: This string splicing is an unfortunate implementation
3399 # detail that has been reported in
3400 # https://github.com/pyca/pyopenssl/issues/258
3401 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3402 revoked.set_serial(serial)
3403 revoked.set_reason(b'unspecified')
3404 revoked.set_rev_date(b'20140601000000Z')
3405 crl.add_revoked(revoked)
3406 crl.set_version(1)
3407 crl.set_lastUpdate(b'20140601000000Z')
3408 crl.set_nextUpdate(b'20180601000000Z')
3409 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3410 return crl
3411
3412 def test_verify_with_revoked(self):
3413 """
Alex Chan7be83a52017-01-24 15:19:29 +00003414 `verify_certificate` raises error when an intermediate certificate is
3415 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003416 """
3417 store = X509Store()
3418 store.add_cert(self.root_cert)
3419 store.add_cert(self.intermediate_cert)
3420 root_crl = self._make_test_crl(
3421 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3422 intermediate_crl = self._make_test_crl(
3423 self.intermediate_cert, self.intermediate_key, certs=[])
3424 store.add_crl(root_crl)
3425 store.add_crl(intermediate_crl)
3426 store.set_flags(
3427 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3428 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003429 with pytest.raises(X509StoreContextError) as err:
3430 store_ctx.verify_certificate()
3431 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003432
3433 def test_verify_with_missing_crl(self):
3434 """
Alex Chan7be83a52017-01-24 15:19:29 +00003435 `verify_certificate` raises error when an intermediate certificate's
3436 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003437 """
3438 store = X509Store()
3439 store.add_cert(self.root_cert)
3440 store.add_cert(self.intermediate_cert)
3441 root_crl = self._make_test_crl(
3442 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3443 store.add_crl(root_crl)
3444 store.set_flags(
3445 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3446 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003447 with pytest.raises(X509StoreContextError) as err:
3448 store_ctx.verify_certificate()
3449 assert err.value.args[0][2] == 'unable to get certificate CRL'
3450 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003451
Paul Kehrer41c10242017-06-29 18:24:17 -05003452 def test_convert_from_cryptography(self):
3453 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3454 crl = CRL.from_cryptography(crypto_crl)
3455 assert isinstance(crl, CRL)
3456
3457 def test_convert_from_cryptography_unsupported_type(self):
3458 with pytest.raises(TypeError):
3459 CRL.from_cryptography(object())
3460
3461 def test_convert_to_cryptography_key(self):
3462 crl = load_crl(FILETYPE_PEM, crlData)
3463 crypto_crl = crl.to_cryptography()
3464 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3465
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003466
Alex Chan7be83a52017-01-24 15:19:29 +00003467class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003468 """
Alex Chan7be83a52017-01-24 15:19:29 +00003469 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003470 """
3471 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3472 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003473 intermediate_server_cert = load_certificate(
3474 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003475
3476 def test_valid(self):
3477 """
Alex Chan7be83a52017-01-24 15:19:29 +00003478 `verify_certificate` returns ``None`` when called with a certificate
3479 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003480 """
3481 store = X509Store()
3482 store.add_cert(self.root_cert)
3483 store.add_cert(self.intermediate_cert)
3484 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003485 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003486
3487 def test_reuse(self):
3488 """
Alex Chan7be83a52017-01-24 15:19:29 +00003489 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003490 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003491 """
3492 store = X509Store()
3493 store.add_cert(self.root_cert)
3494 store.add_cert(self.intermediate_cert)
3495 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003496 assert store_ctx.verify_certificate() is None
3497 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003498
3499 def test_trusted_self_signed(self):
3500 """
Alex Chan7be83a52017-01-24 15:19:29 +00003501 `verify_certificate` returns ``None`` when called with a self-signed
3502 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003503 """
3504 store = X509Store()
3505 store.add_cert(self.root_cert)
3506 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003507 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003508
3509 def test_untrusted_self_signed(self):
3510 """
Alex Chan7be83a52017-01-24 15:19:29 +00003511 `verify_certificate` raises error when a self-signed certificate is
3512 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003513 """
3514 store = X509Store()
3515 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003516 with pytest.raises(X509StoreContextError) as exc:
3517 store_ctx.verify_certificate()
3518
3519 assert exc.value.args[0][2] == 'self signed certificate'
3520 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003521
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003522 def test_invalid_chain_no_root(self):
3523 """
Alex Chan7be83a52017-01-24 15:19:29 +00003524 `verify_certificate` raises error when a root certificate is missing
3525 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003526 """
3527 store = X509Store()
3528 store.add_cert(self.intermediate_cert)
3529 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003530
3531 with pytest.raises(X509StoreContextError) as exc:
3532 store_ctx.verify_certificate()
3533
3534 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3535 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003536
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003537 def test_invalid_chain_no_intermediate(self):
3538 """
Alex Chan7be83a52017-01-24 15:19:29 +00003539 `verify_certificate` raises error when an intermediate certificate is
3540 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003541 """
3542 store = X509Store()
3543 store.add_cert(self.root_cert)
3544 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003545
Alex Gaynor85b49702015-09-05 16:30:59 -04003546 with pytest.raises(X509StoreContextError) as exc:
3547 store_ctx.verify_certificate()
3548
3549 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3550 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003551
Stephen Holsapple46a09252015-02-12 14:45:43 -08003552 def test_modification_pre_verify(self):
3553 """
Alex Chan7be83a52017-01-24 15:19:29 +00003554 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003555 instantiation.
3556 """
3557 store_bad = X509Store()
3558 store_bad.add_cert(self.intermediate_cert)
3559 store_good = X509Store()
3560 store_good.add_cert(self.root_cert)
3561 store_good.add_cert(self.intermediate_cert)
3562 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003563
3564 with pytest.raises(X509StoreContextError) as exc:
3565 store_ctx.verify_certificate()
3566
3567 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3568 assert exc.value.certificate.get_subject().CN == 'intermediate'
3569
Stephen Holsapple46a09252015-02-12 14:45:43 -08003570 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003571 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003572
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003573 def test_verify_with_time(self):
3574 """
3575 `verify_certificate` raises error when the verification time is
3576 set at notAfter.
3577 """
3578 store = X509Store()
3579 store.add_cert(self.root_cert)
3580 store.add_cert(self.intermediate_cert)
3581
3582 expire_time = self.intermediate_server_cert.get_notAfter()
3583 expire_datetime = datetime.strptime(
3584 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3585 )
3586 store.set_time(expire_datetime)
3587
3588 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3589 with pytest.raises(X509StoreContextError) as exc:
3590 store_ctx.verify_certificate()
3591
3592 assert exc.value.args[0][2] == 'certificate has expired'
3593
Stephen Holsapple46a09252015-02-12 14:45:43 -08003594
Alex Chan7be83a52017-01-24 15:19:29 +00003595class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003596 """
Alex Chan7be83a52017-01-24 15:19:29 +00003597 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003598 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003599
James Yonan7c2e5d32010-02-27 05:45:50 -07003600 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003601 """
Alex Chan7be83a52017-01-24 15:19:29 +00003602 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003603 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003604 content = (
3605 b"It was a bright cold day in April, and the clocks were striking "
3606 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3607 b"effort to escape the vile wind, slipped quickly through the "
3608 b"glass doors of Victory Mansions, though not quickly enough to "
3609 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003610
3611 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003612 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003613 # verify the content with this cert
3614 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3615 # certificate unrelated to priv_key, used to trigger an error
3616 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003617
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003618 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003619 sig = sign(priv_key, content, digest)
3620
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003621 # Verify the signature of content, will throw an exception if
3622 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003623 verify(good_cert, sig, content, digest)
3624
3625 # This should fail because the certificate doesn't match the
3626 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003627 with pytest.raises(Error):
3628 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003629
3630 # This should fail because we've "tainted" the content after
3631 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003632 with pytest.raises(Error):
3633 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003634
3635 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003636 with pytest.raises(ValueError):
3637 sign(priv_key, content, "strange-digest")
3638 with pytest.raises(ValueError):
3639 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003640
Abraham Martinc5484ba2015-03-25 15:33:05 +00003641 def test_sign_verify_with_text(self):
3642 """
Alex Chan7be83a52017-01-24 15:19:29 +00003643 `sign` generates a cryptographic signature which
3644 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003645 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003646 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003647 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003648 b"It was a bright cold day in April, and the clocks were striking "
3649 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3650 b"effort to escape the vile wind, slipped quickly through the "
3651 b"glass doors of Victory Mansions, though not quickly enough to "
3652 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003653 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003654
3655 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3656 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3657 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003658 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003659 simplefilter("always")
3660 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003661 assert (
3662 "{0} for data is no longer accepted, use bytes".format(
3663 WARNING_TYPE_EXPECTED
3664 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003665
Alex Chan7be83a52017-01-24 15:19:29 +00003666 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003667 simplefilter("always")
3668 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003669 assert (
3670 "{0} for data is no longer accepted, use bytes".format(
3671 WARNING_TYPE_EXPECTED
3672 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003673
Paul Kehrer59d26252017-07-20 10:45:54 +02003674 def test_sign_verify_ecdsa(self):
3675 """
3676 `sign` generates a cryptographic signature which `verify` can check.
3677 ECDSA Signatures in the X9.62 format may have variable length,
3678 different from the length of the private key.
3679 """
3680 content = (
3681 b"It was a bright cold day in April, and the clocks were striking "
3682 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3683 b"effort to escape the vile wind, slipped quickly through the "
3684 b"glass doors of Victory Mansions, though not quickly enough to "
3685 b"prevent a swirl of gritty dust from entering along with him."
3686 ).decode("ascii")
3687 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3688 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3689 sig = sign(priv_key, content, "sha1")
3690 verify(cert, sig, content, "sha1")
3691
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003692 def test_sign_nulls(self):
3693 """
Alex Chan7be83a52017-01-24 15:19:29 +00003694 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003695 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003696 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003697 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3698 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3699 sig = sign(priv_key, content, "sha1")
3700 verify(good_cert, sig, content, "sha1")
3701
Colleen Murphye09399b2016-03-01 17:40:49 -08003702 def test_sign_with_large_key(self):
3703 """
Alex Chan7be83a52017-01-24 15:19:29 +00003704 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003705 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003706 content = (
3707 b"It was a bright cold day in April, and the clocks were striking "
3708 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3709 b"effort to escape the vile wind, slipped quickly through the "
3710 b"glass doors of Victory Mansions, though not quickly enough to "
3711 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003712
3713 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3714 sign(priv_key, content, "sha1")
3715
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003716
Alex Chan63ef9bc2016-12-19 12:02:06 +00003717class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003718 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003719 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3720 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003721 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003722
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003723 def test_set(self):
3724 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003725 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003726 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003727 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003728
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003729 def test_a_curve(self):
3730 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003731 `get_elliptic_curve` can be used to retrieve a particular supported
3732 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003733 """
3734 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003735 curve = next(iter(curves))
3736 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003737
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003738 def test_not_a_curve(self):
3739 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003740 `get_elliptic_curve` raises `ValueError` if called with a name which
3741 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003742 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003743 with pytest.raises(ValueError):
3744 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003745
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003746 def test_repr(self):
3747 """
3748 The string representation of a curve object includes simply states the
3749 object is a curve and what its name is.
3750 """
3751 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003752 curve = next(iter(curves))
3753 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003754
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003755 def test_to_EC_KEY(self):
3756 """
3757 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003758 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003759 """
3760 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003761 curve = next(iter(curves))
3762 # It's not easy to assert anything about this object. However, see
3763 # leakcheck/crypto.py for a test that demonstrates it at least does
3764 # not leak memory.
3765 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003766
3767
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003768class EllipticCurveFactory(object):
3769 """
3770 A helper to get the names of two curves.
3771 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003772
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003773 def __init__(self):
3774 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003775 self.curve_name = next(curves).name
3776 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003777
3778
Alex Chan63ef9bc2016-12-19 12:02:06 +00003779class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003780 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003781 Tests `_EllipticCurve`'s implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003782 """
3783 curve_factory = EllipticCurveFactory()
3784
3785 if curve_factory.curve_name is None:
3786 skip = "There are no curves available there can be no curve objects."
3787
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003788 def anInstance(self):
3789 """
3790 Get the curve object for an arbitrary curve supported by the system.
3791 """
3792 return get_elliptic_curve(self.curve_factory.curve_name)
3793
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003794 def anotherInstance(self):
3795 """
3796 Get the curve object for an arbitrary curve supported by the system -
3797 but not the one returned by C{anInstance}.
3798 """
3799 return get_elliptic_curve(self.curve_factory.another_curve_name)
3800
3801
Alex Chan63ef9bc2016-12-19 12:02:06 +00003802class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003803 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003804 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3805 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003806 """
3807 curve_factory = EllipticCurveFactory()
3808
3809 if curve_factory.curve_name is None:
3810 skip = "There are no curves available there can be no curve objects."
3811
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003812 def test_contains(self):
3813 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003814 The ``in`` operator reports that a `set` containing a curve does
3815 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003816 """
3817 curve = get_elliptic_curve(self.curve_factory.curve_name)
3818 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003819 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003820
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003821 def test_does_not_contain(self):
3822 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003823 The ``in`` operator reports that a `set` not containing a curve
3824 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003825 """
3826 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003827 curves = set([
3828 get_elliptic_curve(self.curve_factory.another_curve_name)
3829 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003830 assert curve not in curves