blob: 34a9d6e765496266ffbd5defb2d5655f7694c941 [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()
1732 cert.set_pubkey(pkey)
1733 cert.get_subject().commonName = "Unit Tests"
1734 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001735 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001736 cert.set_notBefore(when)
1737 cert.set_notAfter(when)
1738
1739 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001740 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001741 return load_certificate(
1742 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1743
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001744 def test_extension_count(self):
1745 """
Alex Chanb00ede22017-01-30 07:24:40 +00001746 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001747 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001748 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001749 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001750 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1751 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001752 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001753 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001754
1755 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001756 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001757 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001758
1759 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001760 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001761 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001762
1763 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001764 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001765 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001766
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001767 def test_get_extension(self):
1768 """
Alex Chanb00ede22017-01-30 07:24:40 +00001769 `X509.get_extension` takes an integer and returns an
1770 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001771 """
1772 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001773 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1774 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001775 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001776 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001777
1778 cert = self._extcert(pkey, [ca, key, subjectAltName])
1779
1780 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001781 assert isinstance(ext, X509Extension)
1782 assert ext.get_critical()
1783 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001784
1785 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001786 assert isinstance(ext, X509Extension)
1787 assert ext.get_critical()
1788 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001789
1790 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001791 assert isinstance(ext, X509Extension)
1792 assert not ext.get_critical()
1793 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001794
Alex Chanb00ede22017-01-30 07:24:40 +00001795 with pytest.raises(IndexError):
1796 cert.get_extension(-1)
1797 with pytest.raises(IndexError):
1798 cert.get_extension(4)
1799 with pytest.raises(TypeError):
1800 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001801
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001802 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001803 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001804 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001805 bytes and this value is reflected in the string representation of the
1806 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001807 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001808 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001809
1810 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001811 assert ext.get_short_name() == b'subjectAltName'
1812 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001813 b"DNS:altnull.python.org\x00example.com, "
1814 b"email:null@python.org\x00user@example.org, "
1815 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001816 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 -04001817 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001818
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001819 def test_invalid_digest_algorithm(self):
1820 """
Alex Chanb00ede22017-01-30 07:24:40 +00001821 `X509.digest` raises `ValueError` if called with an unrecognized hash
1822 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001823 """
1824 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001825 with pytest.raises(ValueError):
1826 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001827
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001828 def test_get_subject(self):
1829 """
Alex Chanb00ede22017-01-30 07:24:40 +00001830 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001831 """
1832 cert = load_certificate(FILETYPE_PEM, self.pemData)
1833 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001834 assert isinstance(subj, X509Name)
1835 assert (
1836 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001837 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1838 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001839
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001840 def test_set_subject_wrong_args(self):
1841 """
Alex Chanb00ede22017-01-30 07:24:40 +00001842 `X509.set_subject` raises a `TypeError` if called with an argument not
1843 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001844 """
1845 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001846 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001847 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001848
1849 def test_set_subject(self):
1850 """
Alex Chanb00ede22017-01-30 07:24:40 +00001851 `X509.set_subject` changes the subject of the certificate to the one
1852 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001853 """
1854 cert = X509()
1855 name = cert.get_subject()
1856 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001857 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001858 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001859 assert (
1860 cert.get_subject().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001861 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001862
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001863 def test_get_issuer(self):
1864 """
Alex Chanb00ede22017-01-30 07:24:40 +00001865 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001866 """
1867 cert = load_certificate(FILETYPE_PEM, self.pemData)
1868 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001869 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001870 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001871 assert (
1872 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001873 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1874 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001875
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001876 def test_set_issuer_wrong_args(self):
1877 """
Alex Chanb00ede22017-01-30 07:24:40 +00001878 `X509.set_issuer` raises a `TypeError` if called with an argument not
1879 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001880 """
1881 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001882 with pytest.raises(TypeError):
1883 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001884
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001885 def test_set_issuer(self):
1886 """
Alex Chanb00ede22017-01-30 07:24:40 +00001887 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001888 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001889 """
1890 cert = X509()
1891 name = cert.get_issuer()
1892 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001893 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001894 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001895 assert (
1896 cert.get_issuer().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001897 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001898
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001899 def test_get_pubkey_uninitialized(self):
1900 """
Alex Chanb00ede22017-01-30 07:24:40 +00001901 When called on a certificate with no public key, `X509.get_pubkey`
1902 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001903 """
1904 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001905 with pytest.raises(Error):
1906 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001907
Alex Gaynor7778e792016-07-03 23:38:48 -04001908 def test_set_pubkey_wrong_type(self):
1909 """
Alex Chanb00ede22017-01-30 07:24:40 +00001910 `X509.set_pubkey` raises `TypeError` when given an object of the
1911 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001912 """
1913 cert = X509()
1914 with pytest.raises(TypeError):
1915 cert.set_pubkey(object())
1916
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001917 def test_subject_name_hash(self):
1918 """
Alex Chanb00ede22017-01-30 07:24:40 +00001919 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001920 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001921 """
1922 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor4cb05202019-02-02 11:06:41 -05001923 # SHA1
1924 assert cert.subject_name_hash() == 3278919224
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001925
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001926 def test_get_signature_algorithm(self):
1927 """
Alex Chanb00ede22017-01-30 07:24:40 +00001928 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001929 the algorithm used to sign the certificate.
1930 """
1931 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001932 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001933
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001934 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001935 """
Alex Chanb00ede22017-01-30 07:24:40 +00001936 `X509.get_signature_algorithm` raises `ValueError` if the signature
1937 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001938 """
1939 # This certificate has been modified to indicate a bogus OID in the
1940 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001941 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001942-----BEGIN CERTIFICATE-----
1943MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1944EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1945cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1946MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1947EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1948CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1949AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1950+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1951hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1952BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1953FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1954dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1955aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1956MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1957jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1958PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1959tgI5
1960-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001961"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001962 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001963 with pytest.raises(ValueError):
1964 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001965
Alex Gaynor37726112016-07-04 09:51:32 -04001966 def test_sign_bad_pubkey_type(self):
1967 """
Alex Chanb00ede22017-01-30 07:24:40 +00001968 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001969 """
1970 cert = X509()
1971 with pytest.raises(TypeError):
1972 cert.sign(object(), b"sha256")
1973
Alex Gaynor9939ba12017-06-25 16:28:24 -04001974 def test_convert_from_cryptography(self):
1975 crypto_cert = x509.load_pem_x509_certificate(
1976 intermediate_cert_pem, backend
1977 )
1978 cert = X509.from_cryptography(crypto_cert)
1979
1980 assert isinstance(cert, X509)
1981 assert cert.get_version() == crypto_cert.version.value
1982
1983 def test_convert_from_cryptography_unsupported_type(self):
1984 with pytest.raises(TypeError):
1985 X509.from_cryptography(object())
1986
1987 def test_convert_to_cryptography_key(self):
1988 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1989 crypto_cert = cert.to_cryptography()
1990
1991 assert isinstance(crypto_cert, x509.Certificate)
1992 assert crypto_cert.version.value == cert.get_version()
1993
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001994
Alex Chan9e2a9932017-01-25 14:29:19 +00001995class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001996 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001997 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001998 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001999
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000 def test_type(self):
2001 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002002 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002003 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002004 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002005
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002007 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002008 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002009 """
2010 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002011 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002012 store.add_cert(cert)
2013
Alex Chanfb078d82017-04-20 11:16:15 +01002014 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2015 def test_add_cert_wrong_args(self, cert):
2016 """
2017 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2018 as its first argument.
2019 """
2020 store = X509Store()
2021 with pytest.raises(TypeError):
2022 store.add_cert(cert)
2023
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002024 def test_add_cert_accepts_duplicate(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002025 """
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002026 `X509Store.add_cert` doesn't raise `OpenSSL.crypto.Error` if an attempt
2027 is made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002028 """
2029 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2030 store = X509Store()
2031 store.add_cert(cert)
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002032 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002033
2034
Alex Chanb00ede22017-01-30 07:24:40 +00002035class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002036 """
Alex Chanb00ede22017-01-30 07:24:40 +00002037 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002038 """
2039 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2040
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002041 def test_type(self):
2042 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002043 `PKCS12` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002044 """
Alex Chanb00ede22017-01-30 07:24:40 +00002045 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002046
Rick Deanf94096c2009-07-18 14:23:06 -05002047 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002048 """
Alex Chanb00ede22017-01-30 07:24:40 +00002049 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2050 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002051 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002052 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002053 assert None is p12.get_certificate()
2054 assert None is p12.get_privatekey()
2055 assert None is p12.get_ca_certificates()
2056 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002057
2058 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002059 """
Alex Chanb00ede22017-01-30 07:24:40 +00002060 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2061 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2062 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002063 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002064 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002065 for bad_arg in [3, PKey(), X509]:
2066 with pytest.raises(TypeError):
2067 p12.set_certificate(bad_arg)
2068 for bad_arg in [3, 'legbone', X509()]:
2069 with pytest.raises(TypeError):
2070 p12.set_privatekey(bad_arg)
2071 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2072 with pytest.raises(TypeError):
2073 p12.set_ca_certificates(bad_arg)
2074 for bad_arg in [6, ('foo', 'bar')]:
2075 with pytest.raises(TypeError):
2076 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002077
2078 def test_key_only(self):
2079 """
Alex Chanb00ede22017-01-30 07:24:40 +00002080 A `PKCS12` with only a private key can be exported using
2081 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002082 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002083 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002084 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002085 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002086 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002087 assert None is p12.get_certificate()
2088 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002089 try:
2090 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2091 except Error:
2092 # Some versions of OpenSSL will throw an exception
2093 # for this nearly useless PKCS12 we tried to generate:
2094 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2095 return
Rick Dean623ee362009-07-17 12:22:16 -05002096 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002097 assert None is p12.get_ca_certificates()
2098 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002099
2100 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2101 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002102 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002103
2104 def test_cert_only(self):
2105 """
Alex Chanb00ede22017-01-30 07:24:40 +00002106 A `PKCS12` with only a certificate can be exported using
2107 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002108 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002109 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002110 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002111 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002112 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002113 assert cert == p12.get_certificate()
2114 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002115 try:
2116 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2117 except Error:
2118 # Some versions of OpenSSL will throw an exception
2119 # for this nearly useless PKCS12 we tried to generate:
2120 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2121 return
Rick Dean623ee362009-07-17 12:22:16 -05002122 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002123 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002124
2125 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002126 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002127
2128 # Oh ho. It puts the certificate into the ca certificates list, in
2129 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2130 # that to check to see if it reconstructed the certificate we expected
2131 # it to. At some point, hopefully this will change so that
2132 # p12.get_certificate() is actually what returns the loaded
2133 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002134 assert (
2135 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002136 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002137
Alex Gaynor31287502015-09-05 16:11:27 -04002138 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2139 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002140 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002141 Generate a PKCS12 object with components from PEM. Verify that the set
2142 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002143 """
Rick Deanf94096c2009-07-18 14:23:06 -05002144 p12 = PKCS12()
2145 if cert_pem:
2146 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002147 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002148 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002149 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002150 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002151 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002152 ret = p12.set_ca_certificates(
2153 (load_certificate(FILETYPE_PEM, ca_pem),)
2154 )
Alex Chanb00ede22017-01-30 07:24:40 +00002155 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002156 if friendly_name:
2157 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002158 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002159 return p12
2160
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002161 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002162 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002163 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002164 Use openssl program to confirm three components are recoverable from a
2165 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002166 """
2167 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002168 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002169 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2170 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002171 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002172 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002173 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002174 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2175 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002176 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002177 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002178 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002179 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2180 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002181 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002182
Stephen Holsapple38482622014-04-05 20:29:34 -07002183 def verify_pkcs12_container(self, p12):
2184 """
2185 Verify that the PKCS#12 container contains the correct client
2186 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002187
2188 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002189 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002190 """
2191 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2192 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002193 assert (
2194 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002195 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002196
Rick Deanf94096c2009-07-18 14:23:06 -05002197 def test_load_pkcs12(self):
2198 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002199 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002200 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002201 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002202 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002203 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002204 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002205 pem,
2206 b"pkcs12",
2207 b"-export",
2208 b"-clcerts",
2209 b"-passout",
2210 b"pass:" + passwd
2211 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002212 p12 = load_pkcs12(p12_str, passphrase=passwd)
2213 self.verify_pkcs12_container(p12)
2214
Abraham Martinc5484ba2015-03-25 15:33:05 +00002215 def test_load_pkcs12_text_passphrase(self):
2216 """
2217 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002218 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002219 Using text as passphrase instead of bytes. DeprecationWarning expected.
2220 """
2221 pem = client_key_pem + client_cert_pem
2222 passwd = b"whatever"
2223 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2224 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002225 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002226 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002227 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002228 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002229 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002230 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002231 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002232
Abraham Martinc5484ba2015-03-25 15:33:05 +00002233 self.verify_pkcs12_container(p12)
2234
Stephen Holsapple38482622014-04-05 20:29:34 -07002235 def test_load_pkcs12_no_passphrase(self):
2236 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002237 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002238 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002239 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002240 """
2241 pem = client_key_pem + client_cert_pem
2242 p12_str = _runopenssl(
2243 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2244 p12 = load_pkcs12(p12_str)
2245 self.verify_pkcs12_container(p12)
2246
Stephen Holsapple38482622014-04-05 20:29:34 -07002247 def _dump_and_load(self, dump_passphrase, load_passphrase):
2248 """
2249 A helper method to dump and load a PKCS12 object.
2250 """
2251 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2252 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2253 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2254
Stephen Holsapple38482622014-04-05 20:29:34 -07002255 def test_load_pkcs12_null_passphrase_load_empty(self):
2256 """
2257 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002258 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002259 extracted and examined.
2260 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002261 self.verify_pkcs12_container(
2262 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002263
Stephen Holsapple38482622014-04-05 20:29:34 -07002264 def test_load_pkcs12_null_passphrase_load_null(self):
2265 """
2266 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002267 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002268 extracted and examined.
2269 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002270 self.verify_pkcs12_container(
2271 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002272
Stephen Holsapple38482622014-04-05 20:29:34 -07002273 def test_load_pkcs12_empty_passphrase_load_empty(self):
2274 """
2275 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002276 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002277 extracted and examined.
2278 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002279 self.verify_pkcs12_container(
2280 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002281
Stephen Holsapple38482622014-04-05 20:29:34 -07002282 def test_load_pkcs12_empty_passphrase_load_null(self):
2283 """
2284 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002285 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002286 extracted and examined.
2287 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002288 self.verify_pkcs12_container(
2289 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002290
Rick Deanee568302009-07-24 09:56:29 -05002291 def test_load_pkcs12_garbage(self):
2292 """
Alex Chanb00ede22017-01-30 07:24:40 +00002293 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002294 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002295 """
2296 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002297 with pytest.raises(Error) as err:
2298 load_pkcs12(b'fruit loops', passwd)
2299 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2300 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002301
Rick Deanf94096c2009-07-18 14:23:06 -05002302 def test_replace(self):
2303 """
Alex Chanb00ede22017-01-30 07:24:40 +00002304 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2305 cluster. `PKCS12.set_privatekey` replaces the private key.
2306 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002307 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002308 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2309 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2310 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002311 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002312 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002313 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002314 assert 1 == len(p12.get_ca_certificates())
2315 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002316 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002317 assert 2 == len(p12.get_ca_certificates())
2318 assert client_cert == p12.get_ca_certificates()[0]
2319 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002320
Rick Deanf94096c2009-07-18 14:23:06 -05002321 def test_friendly_name(self):
2322 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002323 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002324 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2325 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002326 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002327 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002328 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002329 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002330 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002331 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002332 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002333 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002334 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002335 # We would use the openssl program to confirm the friendly
2336 # name, but it is not possible. The pkcs12 command
2337 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002338 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002339 self.check_recovery(
2340 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2341 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002342
Rick Deanf94096c2009-07-18 14:23:06 -05002343 def test_various_empty_passphrases(self):
2344 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002345 Test that missing, None, and '' passphrases are identical for PKCS12
2346 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002347 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002348 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002349 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002350 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2351 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2352 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2353 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2354 self.check_recovery(
2355 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2356 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002357
Rick Deanf94096c2009-07-18 14:23:06 -05002358 def test_removing_ca_cert(self):
2359 """
Alex Chanb00ede22017-01-30 07:24:40 +00002360 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2361 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002362 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002363 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2364 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002365 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002366
Rick Deanf94096c2009-07-18 14:23:06 -05002367 def test_export_without_mac(self):
2368 """
Alex Chanb00ede22017-01-30 07:24:40 +00002369 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002370 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002371 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002372 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002373 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002374 self.check_recovery(
2375 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002376 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002377
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002378 def test_load_without_mac(self):
2379 """
2380 Loading a PKCS12 without a MAC does something other than crash.
2381 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002382 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002383 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2384 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002385 try:
2386 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2387 # The person who generated this PCKS12 should be flogged,
2388 # or better yet we should have a means to determine
2389 # whether a PCKS12 had a MAC that was verified.
2390 # Anyway, libopenssl chooses to allow it, so the
2391 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002392 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002393 except Error:
2394 # Failing here with an exception is preferred as some openssl
2395 # versions do.
2396 pass
Rick Dean623ee362009-07-17 12:22:16 -05002397
Rick Dean25bcc1f2009-07-20 11:53:13 -05002398 def test_zero_len_list_for_ca(self):
2399 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002400 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002401 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002402 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002403 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002404 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002405 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002406 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2407 self.check_recovery(
2408 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2409 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002410
Rick Deanf94096c2009-07-18 14:23:06 -05002411 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002412 """
Alex Chanb00ede22017-01-30 07:24:40 +00002413 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002414 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002415 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002416 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002417 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002418 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002419
Abraham Martinc5484ba2015-03-25 15:33:05 +00002420 def test_export_without_bytes(self):
2421 """
Alex Chanb00ede22017-01-30 07:24:40 +00002422 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002423 """
2424 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2425
Alex Chanb00ede22017-01-30 07:24:40 +00002426 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002427 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002428 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002429 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002430 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002431 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002432 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002433 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002434 dumped_p12,
2435 key=server_key_pem,
2436 cert=server_cert_pem,
2437 passwd=b"randomtext"
2438 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002439
Rick Deanf94096c2009-07-18 14:23:06 -05002440 def test_key_cert_mismatch(self):
2441 """
Alex Chanb00ede22017-01-30 07:24:40 +00002442 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002443 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002444 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002445 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002446 with pytest.raises(Error):
2447 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002448
2449
Rick Dean4c9ad612009-07-17 15:05:22 -05002450def _runopenssl(pem, *args):
2451 """
2452 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002453 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002454 """
Alex Gaynor6cbc69a2017-07-25 09:07:04 -04002455 proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002456 proc.stdin.write(pem)
2457 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002458 output = proc.stdout.read()
2459 proc.stdout.close()
2460 proc.wait()
2461 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002462
2463
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002464class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002465 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002466 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002467 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002468 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002469 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002470 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002471 """
2472 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002473
2474 assert True is key._only_public
2475 assert 2048 == key.bits()
2476 assert TYPE_RSA == key.type()
2477
2478 def test_invalid_type(self):
2479 """
2480 load_publickey doesn't support FILETYPE_TEXT.
2481 """
2482 with pytest.raises(ValueError):
2483 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2484
2485 def test_invalid_key_format(self):
2486 """
2487 load_publickey explodes on incorrect keys.
2488 """
2489 with pytest.raises(Error):
2490 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2491
2492 def test_tolerates_unicode_strings(self):
2493 """
2494 load_publickey works with text strings, not just bytes.
2495 """
2496 serialized = cleartextPublicKeyPEM.decode('ascii')
2497 key = load_publickey(FILETYPE_PEM, serialized)
2498 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2499
2500 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002501
2502
Alex Chanb00ede22017-01-30 07:24:40 +00002503class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002504 """
Alex Chanb00ede22017-01-30 07:24:40 +00002505 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002506 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002507
2508 def test_load_privatekey_invalid_format(self):
2509 """
Alex Chanb00ede22017-01-30 07:24:40 +00002510 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002511 """
Alex Chanb00ede22017-01-30 07:24:40 +00002512 with pytest.raises(ValueError):
2513 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002514
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002515 def test_load_privatekey_invalid_passphrase_type(self):
2516 """
Alex Chanb00ede22017-01-30 07:24:40 +00002517 `load_privatekey` raises `TypeError` if passed a passphrase that is
2518 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002519 """
Alex Chanb00ede22017-01-30 07:24:40 +00002520 with pytest.raises(TypeError):
2521 load_privatekey(
2522 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002523
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002524 def test_load_privatekey_wrongPassphrase(self):
2525 """
Alex Chanb00ede22017-01-30 07:24:40 +00002526 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2527 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002528 """
Alex Chanb00ede22017-01-30 07:24:40 +00002529 with pytest.raises(Error) as err:
2530 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2531 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002532
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002533 def test_load_privatekey_passphraseWrongType(self):
2534 """
Alex Chanb00ede22017-01-30 07:24:40 +00002535 `load_privatekey` raises `ValueError` when it is passeda passphrase
2536 with a private key encoded in a format, that doesn't support
2537 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002538 """
2539 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2540 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002541 with pytest.raises(ValueError):
2542 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002543
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002544 def test_load_privatekey_passphrase(self):
2545 """
Alex Chanb00ede22017-01-30 07:24:40 +00002546 `load_privatekey` can create a `PKey` object from an encrypted PEM
2547 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002548 """
2549 key = load_privatekey(
2550 FILETYPE_PEM, encryptedPrivateKeyPEM,
2551 encryptedPrivateKeyPEMPassphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002552 assert isinstance(key, PKey)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002553
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002554 def test_load_privatekey_passphrase_exception(self):
2555 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002556 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002557 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002558 """
2559 def cb(ignored):
2560 raise ArithmeticError
2561
Alex Gaynor791212d2015-09-05 15:46:08 -04002562 with pytest.raises(ArithmeticError):
2563 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002564
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002565 def test_load_privatekey_wrongPassphraseCallback(self):
2566 """
Alex Chanb00ede22017-01-30 07:24:40 +00002567 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002568 is passed an encrypted PEM and a passphrase callback which returns an
2569 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002570 """
2571 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002572
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002573 def cb(*a):
2574 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002575 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002576 with pytest.raises(Error) as err:
2577 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2578 assert called
2579 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002580
2581 def test_load_privatekey_passphraseCallback(self):
2582 """
Alex Chanb00ede22017-01-30 07:24:40 +00002583 `load_privatekey` can create a `PKey` object from an encrypted PEM
2584 string if given a passphrase callback which returns the correct
2585 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002586 """
2587 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002588
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002589 def cb(writing):
2590 called.append(writing)
2591 return encryptedPrivateKeyPEMPassphrase
2592 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002593 assert isinstance(key, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002594 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002595
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002596 def test_load_privatekey_passphrase_wrong_return_type(self):
2597 """
Alex Chanb00ede22017-01-30 07:24:40 +00002598 `load_privatekey` raises `ValueError` if the passphrase callback
2599 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002600 """
Alex Chanb00ede22017-01-30 07:24:40 +00002601 with pytest.raises(ValueError):
2602 load_privatekey(
2603 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002604
Alex Chanfb078d82017-04-20 11:16:15 +01002605 def test_dump_privatekey_wrong_args(self):
2606 """
2607 `dump_privatekey` raises `TypeError` if called with a `cipher`
2608 argument but no `passphrase` argument.
2609 """
2610 key = PKey()
2611 key.generate_key(TYPE_RSA, 512)
2612 with pytest.raises(TypeError):
2613 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2614
Paul Kehrercded9932017-06-29 18:43:42 -05002615 def test_dump_privatekey_not_rsa_key(self):
2616 """
2617 `dump_privatekey` raises `TypeError` if called with a key that is
2618 not RSA.
2619 """
2620 key = PKey()
2621 key.generate_key(TYPE_DSA, 512)
2622 with pytest.raises(TypeError):
2623 dump_privatekey(FILETYPE_TEXT, key)
2624
2625 def test_dump_privatekey_invalid_pkey(self):
2626 with pytest.raises(TypeError):
2627 dump_privatekey(FILETYPE_TEXT, object())
2628
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002629 def test_dump_privatekey_unknown_cipher(self):
2630 """
Alex Chanb00ede22017-01-30 07:24:40 +00002631 `dump_privatekey` raises `ValueError` if called with an unrecognized
2632 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002633 """
2634 key = PKey()
2635 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002636 with pytest.raises(ValueError):
2637 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002638
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002639 def test_dump_privatekey_invalid_passphrase_type(self):
2640 """
Alex Chanb00ede22017-01-30 07:24:40 +00002641 `dump_privatekey` raises `TypeError` if called with a passphrase which
2642 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002643 """
2644 key = PKey()
2645 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002646 with pytest.raises(TypeError):
2647 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002648
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002649 def test_dump_privatekey_invalid_filetype(self):
2650 """
Alex Chanb00ede22017-01-30 07:24:40 +00002651 `dump_privatekey` raises `ValueError` if called with an unrecognized
2652 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002653 """
2654 key = PKey()
2655 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002656 with pytest.raises(ValueError):
2657 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002658
Alex Chanb00ede22017-01-30 07:24:40 +00002659 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002660 """
Alex Chanb00ede22017-01-30 07:24:40 +00002661 `crypto.load_privatekey` should raise an error when the passphrase
2662 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002663 """
2664 def cb(ignored):
2665 return "a" * 1025
2666
Alex Gaynor791212d2015-09-05 15:46:08 -04002667 with pytest.raises(ValueError):
2668 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002669
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002670 def test_dump_privatekey_passphrase(self):
2671 """
Alex Chanb00ede22017-01-30 07:24:40 +00002672 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002673 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002674 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002675 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002676 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Gaynor12576002019-11-18 00:18:50 -05002677 assert isinstance(pem, bytes)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002678 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002679 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002680 assert loadedKey.type() == key.type()
2681 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002682
Alex Chanb00ede22017-01-30 07:24:40 +00002683 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002684 """
Alex Chanb00ede22017-01-30 07:24:40 +00002685 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2686 with a private key encoded in a format, that doesn't support
2687 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002688 """
2689 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002690 with pytest.raises(ValueError):
2691 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002692
Rick Dean5b7b6372009-04-01 11:34:06 -05002693 def test_dump_certificate(self):
2694 """
Alex Chanb00ede22017-01-30 07:24:40 +00002695 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002696 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002697 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002698 cert = load_certificate(FILETYPE_PEM, pemData)
2699 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002700 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002701 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002702 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002703 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002704 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2705 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002706 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002707 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002708 good_text = _runopenssl(
2709 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002710 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002711
Alex Gaynor37726112016-07-04 09:51:32 -04002712 def test_dump_certificate_bad_type(self):
2713 """
Alex Chanb00ede22017-01-30 07:24:40 +00002714 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002715 a bad type.
2716 """
2717 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2718 with pytest.raises(ValueError):
2719 dump_certificate(object(), cert)
2720
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002721 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002722 """
Alex Chanb00ede22017-01-30 07:24:40 +00002723 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002724 """
2725 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002726 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002727 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002728 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002729
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002730 def test_dump_privatekey_asn1(self):
2731 """
Alex Chanb00ede22017-01-30 07:24:40 +00002732 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002733 """
2734 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2735 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2736
Rick Dean5b7b6372009-04-01 11:34:06 -05002737 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002738 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002739 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002740 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002741 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2742 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002743 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002744
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002745 def test_dump_privatekey_text(self):
2746 """
Alex Chanb00ede22017-01-30 07:24:40 +00002747 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002748 """
2749 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2750 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2751
Rick Dean5b7b6372009-04-01 11:34:06 -05002752 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002753 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002754 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002755
Cory Benfield6492f7c2015-10-27 16:57:58 +09002756 def test_dump_publickey_pem(self):
2757 """
Cory Benfield11c10192015-10-27 17:23:03 +09002758 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002759 """
2760 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2761 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002762 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002763
2764 def test_dump_publickey_asn1(self):
2765 """
Cory Benfield11c10192015-10-27 17:23:03 +09002766 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002767 """
2768 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2769 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2770 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2771 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002772 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002773
Cory Benfielde02c7d82015-10-27 17:34:49 +09002774 def test_dump_publickey_invalid_type(self):
2775 """
2776 dump_publickey doesn't support FILETYPE_TEXT.
2777 """
2778 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2779
2780 with pytest.raises(ValueError):
2781 dump_publickey(FILETYPE_TEXT, key)
2782
Rick Dean5b7b6372009-04-01 11:34:06 -05002783 def test_dump_certificate_request(self):
2784 """
Alex Chanb00ede22017-01-30 07:24:40 +00002785 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002786 """
Alex Gaynor31287502015-09-05 16:11:27 -04002787 req = load_certificate_request(
2788 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002789 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002790 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002791 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002792 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002793 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002794 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2795 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002796 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002797 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002798 good_text = _runopenssl(
2799 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002800 assert dumped_text == good_text
2801 with pytest.raises(ValueError):
2802 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002803
Alex Chanb00ede22017-01-30 07:24:40 +00002804 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002805 """
Alex Chanb00ede22017-01-30 07:24:40 +00002806 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002807 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002808 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002809 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002810 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002811
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002812 def cb(writing):
2813 called.append(writing)
2814 return passphrase
2815 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002816 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Gaynor12576002019-11-18 00:18:50 -05002817 assert isinstance(pem, bytes)
Alex Chanb00ede22017-01-30 07:24:40 +00002818 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002819 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Gaynor01f90a12019-02-07 09:14:48 -05002820 assert isinstance(loadedKey, PKey)
Alex Chanb00ede22017-01-30 07:24:40 +00002821 assert loadedKey.type() == key.type()
2822 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002823
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002824 def test_dump_privatekey_passphrase_exception(self):
2825 """
Alex Chanb00ede22017-01-30 07:24:40 +00002826 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002827 by the passphrase callback.
2828 """
2829 def cb(ignored):
2830 raise ArithmeticError
2831
2832 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002833 with pytest.raises(ArithmeticError):
2834 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002835
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002836 def test_dump_privatekey_passphraseCallbackLength(self):
2837 """
Alex Chanb00ede22017-01-30 07:24:40 +00002838 `crypto.dump_privatekey` should raise an error when the passphrase
2839 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002840 """
2841 def cb(ignored):
2842 return "a" * 1025
2843
2844 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002845 with pytest.raises(ValueError):
2846 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002847
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002848 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002849 """
Alex Chanb00ede22017-01-30 07:24:40 +00002850 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2851 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002852 """
2853 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002854 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002855
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002856 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002857 """
Alex Chanb00ede22017-01-30 07:24:40 +00002858 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2859 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002860 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002861 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002862 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002863
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002864 def test_load_pkcs7_data_invalid(self):
2865 """
Alex Chanb00ede22017-01-30 07:24:40 +00002866 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002867 """
Alex Chanb00ede22017-01-30 07:24:40 +00002868 with pytest.raises(Error):
2869 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002870
Alex Gaynor09a386e2016-07-03 09:32:44 -04002871 def test_load_pkcs7_type_invalid(self):
2872 """
Alex Chanb00ede22017-01-30 07:24:40 +00002873 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002874 """
2875 with pytest.raises(ValueError):
2876 load_pkcs7_data(object(), b"foo")
2877
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002878
Alex Chan9e2a9932017-01-25 14:29:19 +00002879class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002880 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002881 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002882 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002883
Alex Chan9e2a9932017-01-25 14:29:19 +00002884 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002885 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002886 If the file type passed to `load_certificate_request` is neither
2887 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002888 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002889 with pytest.raises(ValueError):
2890 load_certificate_request(object(), b"")
2891 with pytest.raises(ValueError):
2892 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002893
Alex Gaynor37726112016-07-04 09:51:32 -04002894 def test_bad_certificate(self):
2895 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002896 If the bytes passed to `load_certificate` are not a valid certificate,
2897 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002898 """
2899 with pytest.raises(Error):
2900 load_certificate(FILETYPE_ASN1, b"lol")
2901
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002902
Alex Chanb00ede22017-01-30 07:24:40 +00002903class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002904 """
Alex Chanb00ede22017-01-30 07:24:40 +00002905 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002906 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002907
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002908 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002909 """
Alex Chanb00ede22017-01-30 07:24:40 +00002910 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2911 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002912 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002913 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002914 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002915
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002916 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002917 """
Alex Chanb00ede22017-01-30 07:24:40 +00002918 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2919 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002920 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002921 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002922 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002923
Alex Chanb00ede22017-01-30 07:24:40 +00002924 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002925 """
Alex Chanb00ede22017-01-30 07:24:40 +00002926 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002927 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002928 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002929 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002930 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002931
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002932 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002933 """
Alex Chanb00ede22017-01-30 07:24:40 +00002934 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2935 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002936 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002937 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002938 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002939
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002940 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002941 """
Alex Chanb00ede22017-01-30 07:24:40 +00002942 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002943 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002944 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002945 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002946 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002947
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002948 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002949 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002950 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002951 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002952 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002953 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002954 with pytest.raises(AttributeError):
2955 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002956
2957
Alex Chanb00ede22017-01-30 07:24:40 +00002958class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002959 """
Alex Chanb00ede22017-01-30 07:24:40 +00002960 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002961 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002962
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002963 def signable(self):
2964 """
Alex Chanb00ede22017-01-30 07:24:40 +00002965 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002966 """
2967 return NetscapeSPKI()
2968
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002969 def test_type(self):
2970 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002971 `NetscapeSPKI` can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002972 """
Alex Chanb00ede22017-01-30 07:24:40 +00002973 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002974
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002975 def test_construction(self):
2976 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002977 `NetscapeSPKI` returns an instance of `NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002978 """
2979 nspki = NetscapeSPKI()
Alex Gaynor01f90a12019-02-07 09:14:48 -05002980 assert isinstance(nspki, NetscapeSPKI)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002981
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002982 def test_invalid_attribute(self):
2983 """
Alex Chanb00ede22017-01-30 07:24:40 +00002984 Accessing a non-existent attribute of a `NetscapeSPKI` instance
2985 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002986 """
2987 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002988 with pytest.raises(AttributeError):
2989 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002990
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002991 def test_b64_encode(self):
2992 """
Alex Chanb00ede22017-01-30 07:24:40 +00002993 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002994 """
2995 nspki = NetscapeSPKI()
2996 blob = nspki.b64_encode()
Alex Gaynor12576002019-11-18 00:18:50 -05002997 assert isinstance(blob, bytes)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002998
2999
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003000class TestRevoked(object):
3001 """
Alex Chandeec9342016-12-19 22:00:38 +00003002 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003003 """
3004 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
3005 """
3006 The get_reason method on the Revoked class checks to see if the
3007 extension is NID_crl_reason and should skip it otherwise. This test
3008 loads a CRL with extensions it should ignore.
3009 """
3010 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3011 revoked = crl.get_revoked()
3012 reason = revoked[1].get_reason()
3013 assert reason == b'Unspecified'
3014
3015 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3016 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3017 revoked = crl.get_revoked()
3018 revoked[1].set_reason(None)
3019 reason = revoked[1].get_reason()
3020 assert reason is None
3021
Rick Dean536ba022009-07-24 23:57:27 -05003022 def test_construction(self):
3023 """
Alex Chandeec9342016-12-19 22:00:38 +00003024 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3025 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003026 """
3027 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003028 assert isinstance(revoked, Revoked)
3029 assert type(revoked) == Revoked
3030 assert revoked.get_serial() == b'00'
3031 assert revoked.get_rev_date() is None
3032 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003033
Rick Dean536ba022009-07-24 23:57:27 -05003034 def test_serial(self):
3035 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003036 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003037 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003038 """
3039 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003040 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003041 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003042 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003043 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003044
Alex Gaynore7f51982016-09-11 11:48:14 -04003045 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003046 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003047 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003048
Alex Chandeec9342016-12-19 22:00:38 +00003049 with pytest.raises(ValueError):
3050 revoked.set_serial(b'pqrst')
3051 with pytest.raises(TypeError):
3052 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003053
Rick Dean536ba022009-07-24 23:57:27 -05003054 def test_date(self):
3055 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003056 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003057 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003058 """
3059 revoked = Revoked()
3060 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003061 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003062
Alex Gaynore7f51982016-09-11 11:48:14 -04003063 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003064 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003065 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003066 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003067 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003068
Rick Dean6385faf2009-07-26 00:07:47 -05003069 def test_reason(self):
3070 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003071 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003072 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3073 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003074 """
3075 revoked = Revoked()
3076 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003077 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003078 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003079 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003080 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003081 assert (
3082 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003083 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003084 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003085
3086 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003087 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003088
Alex Chanfb078d82017-04-20 11:16:15 +01003089 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3090 def test_set_reason_wrong_args(self, reason):
3091 """
3092 `Revoked.set_reason` raises `TypeError` if called with an argument
3093 which is neither `None` nor a byte string.
3094 """
3095 revoked = Revoked()
3096 with pytest.raises(TypeError):
3097 revoked.set_reason(reason)
3098
Alex Chandeec9342016-12-19 22:00:38 +00003099 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003100 """
Alex Chandeec9342016-12-19 22:00:38 +00003101 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3102 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003103 """
3104 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003105 with pytest.raises(ValueError):
3106 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003107
3108
Alex Chan7be83a52017-01-24 15:19:29 +00003109class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003110 """
Alex Chan7be83a52017-01-24 15:19:29 +00003111 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003112 """
3113 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3114 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3115
Dan Sully44e767a2016-06-04 18:05:27 -07003116 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3117 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3118 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3119 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3120 intermediate_server_cert = load_certificate(
3121 FILETYPE_PEM, intermediate_server_cert_pem)
3122 intermediate_server_key = load_privatekey(
3123 FILETYPE_PEM, intermediate_server_key_pem)
3124
Rick Dean536ba022009-07-24 23:57:27 -05003125 def test_construction(self):
3126 """
Alex Chan7be83a52017-01-24 15:19:29 +00003127 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003128 that it is empty
3129 """
3130 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003131 assert isinstance(crl, CRL)
3132 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003133
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003134 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003135 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003136 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003137 """
3138 crl = CRL()
3139 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003140 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003141 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003142 revoked.set_serial(b'3ab')
3143 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003144 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003145 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003146
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003147 def test_export_pem(self):
3148 """
3149 If not passed a format, ``CRL.export`` returns a "PEM" format string
3150 representing a serial number, a revoked reason, and certificate issuer
3151 information.
3152 """
Rick Dean536ba022009-07-24 23:57:27 -05003153 # PEM format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003154 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003155 self.cert, self.pkey, days=20, digest=b"sha256"
3156 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003157 crl = x509.load_pem_x509_crl(dumped_crl, backend)
3158 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3159 assert revoked is not None
3160 assert crl.issuer == x509.Name([
3161 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3162 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3163 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3164 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3165 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3166 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003167
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003168 def test_export_der(self):
3169 """
3170 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3171 "DER" format string representing a serial number, a revoked reason, and
3172 certificate issuer information.
3173 """
3174 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003175
3176 # DER format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003177 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003178 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3179 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003180 crl = x509.load_der_x509_crl(dumped_crl, backend)
3181 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3182 assert revoked is not None
3183 assert crl.issuer == x509.Name([
3184 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3185 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3186 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3187 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3188 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3189 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003190
Alex Gaynore466bc92017-07-06 23:43:47 -04003191 # Flaky because we compare the output of running commands which sometimes
3192 # varies by 1 second
3193 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003194 def test_export_text(self):
3195 """
3196 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3197 text format string like the one produced by the openssl command line
3198 tool.
3199 """
3200 crl = self._get_crl()
3201
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003202 dumped_crl = crl.export(
3203 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3204 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003205 text = _runopenssl(
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003206 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER",
3207 b"-nameopt", b""
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003208 )
Rick Dean536ba022009-07-24 23:57:27 -05003209
3210 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003211 dumped_text = crl.export(
3212 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3213 )
Alex Chan7be83a52017-01-24 15:19:29 +00003214 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003215
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003216 def test_export_custom_digest(self):
3217 """
3218 If passed the name of a digest function, ``CRL.export`` uses a
3219 signature algorithm based on that digest function.
3220 """
3221 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003222 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003223 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003224 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003225
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003226 def test_export_md5_digest(self):
3227 """
3228 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3229 not emit a deprecation warning.
3230 """
3231 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003232 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003233 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003234 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003235 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3236 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003237 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003238
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003239 def test_export_default_digest(self):
3240 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003241 If not passed the name of a digest function, ``CRL.export`` raises a
3242 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003243 """
3244 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003245 with pytest.raises(TypeError):
3246 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003247
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003248 def test_export_invalid(self):
3249 """
Alex Chan7be83a52017-01-24 15:19:29 +00003250 If `CRL.export` is used with an uninitialized `X509` instance,
3251 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003252 """
3253 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003254 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003255 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003256
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003257 def test_add_revoked_keyword(self):
3258 """
Alex Chan7be83a52017-01-24 15:19:29 +00003259 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003260 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003261 """
3262 crl = CRL()
3263 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003264 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003265 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003266 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003267 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003268
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003269 def test_export_wrong_args(self):
3270 """
Alex Chan7be83a52017-01-24 15:19:29 +00003271 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003272 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003273 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003274 """
3275 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003276 with pytest.raises(TypeError):
3277 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3278 with pytest.raises(TypeError):
3279 crl.export(self.cert, None, FILETYPE_PEM, 10)
3280 with pytest.raises(TypeError):
3281 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003282 with pytest.raises(TypeError):
3283 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003284
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003285 def test_export_unknown_filetype(self):
3286 """
Alex Chan7be83a52017-01-24 15:19:29 +00003287 Calling `OpenSSL.CRL.export` with a file type other than
3288 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3289 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003290 """
3291 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003292 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003293 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003294
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003295 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003296 """
Alex Chan7be83a52017-01-24 15:19:29 +00003297 Calling `OpenSSL.CRL.export` with an unsupported digest results
3298 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003299 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003300 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003301 with pytest.raises(ValueError):
3302 crl.export(
3303 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003304
Rick Dean536ba022009-07-24 23:57:27 -05003305 def test_get_revoked(self):
3306 """
Alex Chan7be83a52017-01-24 15:19:29 +00003307 Use python to create a simple CRL with two revocations. Get back the
3308 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003309 """
3310 crl = CRL()
3311
3312 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003313 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003314 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003315 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003316 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003317 revoked.set_serial(b'100')
3318 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003319 crl.add_revoked(revoked)
3320
3321 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003322 assert len(revs) == 2
3323 assert type(revs[0]) == Revoked
3324 assert type(revs[1]) == Revoked
3325 assert revs[0].get_serial() == b'03AB'
3326 assert revs[1].get_serial() == b'0100'
3327 assert revs[0].get_rev_date() == now
3328 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003329
Rick Dean536ba022009-07-24 23:57:27 -05003330 def test_load_crl(self):
3331 """
Alex Chan7be83a52017-01-24 15:19:29 +00003332 Load a known CRL and inspect its revocations. Both EM and DER formats
3333 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003334 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003335 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003336 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003337 assert len(revs) == 2
3338 assert revs[0].get_serial() == b'03AB'
3339 assert revs[0].get_reason() is None
3340 assert revs[1].get_serial() == b'0100'
3341 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003342
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003343 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003344 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003345 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003346 assert len(revs) == 2
3347 assert revs[0].get_serial() == b'03AB'
3348 assert revs[0].get_reason() is None
3349 assert revs[1].get_serial() == b'0100'
3350 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003351
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003352 def test_load_crl_bad_filetype(self):
3353 """
Alex Chan7be83a52017-01-24 15:19:29 +00003354 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3355 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003356 """
Alex Chan7be83a52017-01-24 15:19:29 +00003357 with pytest.raises(ValueError):
3358 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003359
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003360 def test_load_crl_bad_data(self):
3361 """
Alex Chan7be83a52017-01-24 15:19:29 +00003362 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3363 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003364 """
Alex Chan7be83a52017-01-24 15:19:29 +00003365 with pytest.raises(Error):
3366 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003367
Dan Sully44e767a2016-06-04 18:05:27 -07003368 def test_get_issuer(self):
3369 """
Alex Chan7be83a52017-01-24 15:19:29 +00003370 Load a known CRL and assert its issuer's common name is what we expect
3371 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003372 """
3373 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003374 assert isinstance(crl.get_issuer(), X509Name)
3375 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003376
Dominic Chenf05b2122015-10-13 16:32:35 +00003377 def test_dump_crl(self):
3378 """
3379 The dumped CRL matches the original input.
3380 """
3381 crl = load_crl(FILETYPE_PEM, crlData)
3382 buf = dump_crl(FILETYPE_PEM, crl)
3383 assert buf == crlData
3384
Dan Sully44e767a2016-06-04 18:05:27 -07003385 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3386 """
3387 Create a CRL.
3388
3389 :param list[X509] certs: A list of certificates to revoke.
3390 :rtype: CRL
3391 """
3392 crl = CRL()
3393 for cert in certs:
3394 revoked = Revoked()
3395 # FIXME: This string splicing is an unfortunate implementation
3396 # detail that has been reported in
3397 # https://github.com/pyca/pyopenssl/issues/258
3398 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3399 revoked.set_serial(serial)
3400 revoked.set_reason(b'unspecified')
3401 revoked.set_rev_date(b'20140601000000Z')
3402 crl.add_revoked(revoked)
3403 crl.set_version(1)
3404 crl.set_lastUpdate(b'20140601000000Z')
3405 crl.set_nextUpdate(b'20180601000000Z')
3406 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3407 return crl
3408
3409 def test_verify_with_revoked(self):
3410 """
Alex Chan7be83a52017-01-24 15:19:29 +00003411 `verify_certificate` raises error when an intermediate certificate is
3412 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003413 """
3414 store = X509Store()
3415 store.add_cert(self.root_cert)
3416 store.add_cert(self.intermediate_cert)
3417 root_crl = self._make_test_crl(
3418 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3419 intermediate_crl = self._make_test_crl(
3420 self.intermediate_cert, self.intermediate_key, certs=[])
3421 store.add_crl(root_crl)
3422 store.add_crl(intermediate_crl)
3423 store.set_flags(
3424 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3425 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003426 with pytest.raises(X509StoreContextError) as err:
3427 store_ctx.verify_certificate()
3428 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003429
3430 def test_verify_with_missing_crl(self):
3431 """
Alex Chan7be83a52017-01-24 15:19:29 +00003432 `verify_certificate` raises error when an intermediate certificate's
3433 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003434 """
3435 store = X509Store()
3436 store.add_cert(self.root_cert)
3437 store.add_cert(self.intermediate_cert)
3438 root_crl = self._make_test_crl(
3439 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3440 store.add_crl(root_crl)
3441 store.set_flags(
3442 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3443 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003444 with pytest.raises(X509StoreContextError) as err:
3445 store_ctx.verify_certificate()
3446 assert err.value.args[0][2] == 'unable to get certificate CRL'
3447 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003448
Paul Kehrer41c10242017-06-29 18:24:17 -05003449 def test_convert_from_cryptography(self):
3450 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3451 crl = CRL.from_cryptography(crypto_crl)
3452 assert isinstance(crl, CRL)
3453
3454 def test_convert_from_cryptography_unsupported_type(self):
3455 with pytest.raises(TypeError):
3456 CRL.from_cryptography(object())
3457
3458 def test_convert_to_cryptography_key(self):
3459 crl = load_crl(FILETYPE_PEM, crlData)
3460 crypto_crl = crl.to_cryptography()
3461 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3462
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003463
Alex Chan7be83a52017-01-24 15:19:29 +00003464class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003465 """
Alex Chan7be83a52017-01-24 15:19:29 +00003466 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003467 """
3468 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3469 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003470 intermediate_server_cert = load_certificate(
3471 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003472
3473 def test_valid(self):
3474 """
Alex Chan7be83a52017-01-24 15:19:29 +00003475 `verify_certificate` returns ``None`` when called with a certificate
3476 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003477 """
3478 store = X509Store()
3479 store.add_cert(self.root_cert)
3480 store.add_cert(self.intermediate_cert)
3481 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003482 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003483
3484 def test_reuse(self):
3485 """
Alex Chan7be83a52017-01-24 15:19:29 +00003486 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003487 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003488 """
3489 store = X509Store()
3490 store.add_cert(self.root_cert)
3491 store.add_cert(self.intermediate_cert)
3492 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003493 assert store_ctx.verify_certificate() is None
3494 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003495
3496 def test_trusted_self_signed(self):
3497 """
Alex Chan7be83a52017-01-24 15:19:29 +00003498 `verify_certificate` returns ``None`` when called with a self-signed
3499 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003500 """
3501 store = X509Store()
3502 store.add_cert(self.root_cert)
3503 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003504 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003505
3506 def test_untrusted_self_signed(self):
3507 """
Alex Chan7be83a52017-01-24 15:19:29 +00003508 `verify_certificate` raises error when a self-signed certificate is
3509 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003510 """
3511 store = X509Store()
3512 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003513 with pytest.raises(X509StoreContextError) as exc:
3514 store_ctx.verify_certificate()
3515
3516 assert exc.value.args[0][2] == 'self signed certificate'
3517 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003518
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003519 def test_invalid_chain_no_root(self):
3520 """
Alex Chan7be83a52017-01-24 15:19:29 +00003521 `verify_certificate` raises error when a root certificate is missing
3522 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003523 """
3524 store = X509Store()
3525 store.add_cert(self.intermediate_cert)
3526 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003527
3528 with pytest.raises(X509StoreContextError) as exc:
3529 store_ctx.verify_certificate()
3530
3531 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3532 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003533
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003534 def test_invalid_chain_no_intermediate(self):
3535 """
Alex Chan7be83a52017-01-24 15:19:29 +00003536 `verify_certificate` raises error when an intermediate certificate is
3537 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003538 """
3539 store = X509Store()
3540 store.add_cert(self.root_cert)
3541 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003542
Alex Gaynor85b49702015-09-05 16:30:59 -04003543 with pytest.raises(X509StoreContextError) as exc:
3544 store_ctx.verify_certificate()
3545
3546 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3547 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003548
Stephen Holsapple46a09252015-02-12 14:45:43 -08003549 def test_modification_pre_verify(self):
3550 """
Alex Chan7be83a52017-01-24 15:19:29 +00003551 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003552 instantiation.
3553 """
3554 store_bad = X509Store()
3555 store_bad.add_cert(self.intermediate_cert)
3556 store_good = X509Store()
3557 store_good.add_cert(self.root_cert)
3558 store_good.add_cert(self.intermediate_cert)
3559 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003560
3561 with pytest.raises(X509StoreContextError) as exc:
3562 store_ctx.verify_certificate()
3563
3564 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3565 assert exc.value.certificate.get_subject().CN == 'intermediate'
3566
Stephen Holsapple46a09252015-02-12 14:45:43 -08003567 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003568 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003569
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003570 def test_verify_with_time(self):
3571 """
3572 `verify_certificate` raises error when the verification time is
3573 set at notAfter.
3574 """
3575 store = X509Store()
3576 store.add_cert(self.root_cert)
3577 store.add_cert(self.intermediate_cert)
3578
3579 expire_time = self.intermediate_server_cert.get_notAfter()
3580 expire_datetime = datetime.strptime(
3581 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3582 )
3583 store.set_time(expire_datetime)
3584
3585 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3586 with pytest.raises(X509StoreContextError) as exc:
3587 store_ctx.verify_certificate()
3588
3589 assert exc.value.args[0][2] == 'certificate has expired'
3590
Stephen Holsapple46a09252015-02-12 14:45:43 -08003591
Alex Chan7be83a52017-01-24 15:19:29 +00003592class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003593 """
Alex Chan7be83a52017-01-24 15:19:29 +00003594 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003595 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003596
James Yonan7c2e5d32010-02-27 05:45:50 -07003597 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003598 """
Alex Chan7be83a52017-01-24 15:19:29 +00003599 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003600 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003601 content = (
3602 b"It was a bright cold day in April, and the clocks were striking "
3603 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3604 b"effort to escape the vile wind, slipped quickly through the "
3605 b"glass doors of Victory Mansions, though not quickly enough to "
3606 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003607
3608 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003609 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003610 # verify the content with this cert
3611 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3612 # certificate unrelated to priv_key, used to trigger an error
3613 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003614
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003615 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003616 sig = sign(priv_key, content, digest)
3617
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003618 # Verify the signature of content, will throw an exception if
3619 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003620 verify(good_cert, sig, content, digest)
3621
3622 # This should fail because the certificate doesn't match the
3623 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003624 with pytest.raises(Error):
3625 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003626
3627 # This should fail because we've "tainted" the content after
3628 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003629 with pytest.raises(Error):
3630 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003631
3632 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003633 with pytest.raises(ValueError):
3634 sign(priv_key, content, "strange-digest")
3635 with pytest.raises(ValueError):
3636 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003637
Abraham Martinc5484ba2015-03-25 15:33:05 +00003638 def test_sign_verify_with_text(self):
3639 """
Alex Chan7be83a52017-01-24 15:19:29 +00003640 `sign` generates a cryptographic signature which
3641 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003642 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003643 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003644 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003645 b"It was a bright cold day in April, and the clocks were striking "
3646 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3647 b"effort to escape the vile wind, slipped quickly through the "
3648 b"glass doors of Victory Mansions, though not quickly enough to "
3649 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003650 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003651
3652 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3653 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3654 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003655 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003656 simplefilter("always")
3657 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003658 assert (
3659 "{0} for data is no longer accepted, use bytes".format(
3660 WARNING_TYPE_EXPECTED
3661 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003662
Alex Chan7be83a52017-01-24 15:19:29 +00003663 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003664 simplefilter("always")
3665 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003666 assert (
3667 "{0} for data is no longer accepted, use bytes".format(
3668 WARNING_TYPE_EXPECTED
3669 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003670
Paul Kehrer59d26252017-07-20 10:45:54 +02003671 def test_sign_verify_ecdsa(self):
3672 """
3673 `sign` generates a cryptographic signature which `verify` can check.
3674 ECDSA Signatures in the X9.62 format may have variable length,
3675 different from the length of the private key.
3676 """
3677 content = (
3678 b"It was a bright cold day in April, and the clocks were striking "
3679 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3680 b"effort to escape the vile wind, slipped quickly through the "
3681 b"glass doors of Victory Mansions, though not quickly enough to "
3682 b"prevent a swirl of gritty dust from entering along with him."
3683 ).decode("ascii")
3684 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3685 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3686 sig = sign(priv_key, content, "sha1")
3687 verify(cert, sig, content, "sha1")
3688
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003689 def test_sign_nulls(self):
3690 """
Alex Chan7be83a52017-01-24 15:19:29 +00003691 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003692 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003693 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003694 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3695 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3696 sig = sign(priv_key, content, "sha1")
3697 verify(good_cert, sig, content, "sha1")
3698
Colleen Murphye09399b2016-03-01 17:40:49 -08003699 def test_sign_with_large_key(self):
3700 """
Alex Chan7be83a52017-01-24 15:19:29 +00003701 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003702 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003703 content = (
3704 b"It was a bright cold day in April, and the clocks were striking "
3705 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3706 b"effort to escape the vile wind, slipped quickly through the "
3707 b"glass doors of Victory Mansions, though not quickly enough to "
3708 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003709
3710 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3711 sign(priv_key, content, "sha1")
3712
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003713
Alex Chan63ef9bc2016-12-19 12:02:06 +00003714class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003715 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003716 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3717 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003718 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003719
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003720 def test_set(self):
3721 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003722 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003723 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003724 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003725
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003726 def test_a_curve(self):
3727 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003728 `get_elliptic_curve` can be used to retrieve a particular supported
3729 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003730 """
3731 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003732 curve = next(iter(curves))
3733 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003734
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003735 def test_not_a_curve(self):
3736 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003737 `get_elliptic_curve` raises `ValueError` if called with a name which
3738 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003739 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003740 with pytest.raises(ValueError):
3741 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003742
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003743 def test_repr(self):
3744 """
3745 The string representation of a curve object includes simply states the
3746 object is a curve and what its name is.
3747 """
3748 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003749 curve = next(iter(curves))
3750 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003751
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003752 def test_to_EC_KEY(self):
3753 """
3754 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003755 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003756 """
3757 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003758 curve = next(iter(curves))
3759 # It's not easy to assert anything about this object. However, see
3760 # leakcheck/crypto.py for a test that demonstrates it at least does
3761 # not leak memory.
3762 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003763
3764
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003765class EllipticCurveFactory(object):
3766 """
3767 A helper to get the names of two curves.
3768 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003769
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003770 def __init__(self):
3771 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003772 self.curve_name = next(curves).name
3773 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003774
3775
Alex Chan63ef9bc2016-12-19 12:02:06 +00003776class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003777 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003778 Tests `_EllipticCurve`'s implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003779 """
3780 curve_factory = EllipticCurveFactory()
3781
3782 if curve_factory.curve_name is None:
3783 skip = "There are no curves available there can be no curve objects."
3784
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003785 def anInstance(self):
3786 """
3787 Get the curve object for an arbitrary curve supported by the system.
3788 """
3789 return get_elliptic_curve(self.curve_factory.curve_name)
3790
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003791 def anotherInstance(self):
3792 """
3793 Get the curve object for an arbitrary curve supported by the system -
3794 but not the one returned by C{anInstance}.
3795 """
3796 return get_elliptic_curve(self.curve_factory.another_curve_name)
3797
3798
Alex Chan63ef9bc2016-12-19 12:02:06 +00003799class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003800 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003801 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3802 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003803 """
3804 curve_factory = EllipticCurveFactory()
3805
3806 if curve_factory.curve_name is None:
3807 skip = "There are no curves available there can be no curve objects."
3808
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003809 def test_contains(self):
3810 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003811 The ``in`` operator reports that a `set` containing a curve does
3812 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003813 """
3814 curve = get_elliptic_curve(self.curve_factory.curve_name)
3815 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003816 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003817
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003818 def test_does_not_contain(self):
3819 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003820 The ``in`` operator reports that a `set` not containing a curve
3821 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003822 """
3823 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003824 curves = set([
3825 get_elliptic_curve(self.curve_factory.another_curve_name)
3826 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003827 assert curve not in curves