blob: c9380210362a4a50598f228f98fc3655680124f5 [file] [log] [blame]
Jean-Paul Calderone8671c852011-03-02 19:26:20 -05001# Copyright (c) Jean-Paul Calderone
2# See LICENSE file for details.
Jean-Paul Calderone8b63d452008-03-21 18:31:12 -04003
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -05004"""
Jonathan Ballet648875f2011-07-16 14:14:58 +09005Unit tests for :py:mod:`OpenSSL.crypto`.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -05006"""
7
Alex Chanb00ede22017-01-30 07:24:40 +00008from warnings import simplefilter
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04009
Alex Gaynor4b9c96a2014-08-14 09:51:48 -070010import base64
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -040011from subprocess import PIPE, Popen
Rick Dean47262da2009-07-08 16:17:17 -050012from datetime import datetime, timedelta
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -050013
Alex Gaynor791212d2015-09-05 15:46:08 -040014import pytest
15
Alex Gaynore7f51982016-09-11 11:48:14 -040016from six import binary_type
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050017
Alex Gaynor9939ba12017-06-25 16:28:24 -040018from cryptography import x509
Paul Kehrer72d968b2016-07-29 15:31:04 +080019from cryptography.hazmat.backends.openssl.backend import backend
20from cryptography.hazmat.primitives import serialization
21from cryptography.hazmat.primitives.asymmetric import rsa
22
Alex Gaynore466bc92017-07-06 23:43:47 -040023import flaky
24
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -050025from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
Jean-Paul Calderone78381d22008-03-06 23:35:22 -050026from OpenSSL.crypto import X509, X509Type, X509Name, X509NameType
Alex Gaynor31287502015-09-05 16:11:27 -040027from OpenSSL.crypto import (
Dan Sully44e767a2016-06-04 18:05:27 -070028 X509Store,
29 X509StoreFlags,
30 X509StoreType,
31 X509StoreContext,
32 X509StoreContextError
Alex Gaynor31287502015-09-05 16:11:27 -040033)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070034from OpenSSL.crypto import X509Req, X509ReqType
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -050035from OpenSSL.crypto import X509Extension, X509ExtensionType
Rick Dean5b7b6372009-04-01 11:34:06 -050036from OpenSSL.crypto import load_certificate, load_privatekey
Cory Benfield6492f7c2015-10-27 16:57:58 +090037from OpenSSL.crypto import load_publickey, dump_publickey
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -040038from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
Jean-Paul Calderone71919862009-04-01 13:01:19 -040039from OpenSSL.crypto import dump_certificate, load_certificate_request
40from OpenSSL.crypto import dump_certificate_request, dump_privatekey
Alex Chanb00ede22017-01-30 07:24:40 +000041from OpenSSL.crypto import PKCS7, PKCS7Type, load_pkcs7_data
Jean-Paul Calderone9178ee62010-01-25 17:55:30 -050042from OpenSSL.crypto import PKCS12, PKCS12Type, load_pkcs12
Dominic Chenf05b2122015-10-13 16:32:35 +000043from OpenSSL.crypto import CRL, Revoked, dump_crl, load_crl
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -040044from OpenSSL.crypto import NetscapeSPKI, NetscapeSPKIType
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040045from OpenSSL.crypto import (
46 sign, verify, get_elliptic_curve, get_elliptic_curves)
Hynek Schlawackf0e66852015-10-16 20:18:38 +020047
Alex Chanb00ede22017-01-30 07:24:40 +000048from .util import EqualityTestsMixin, is_consistent_type, WARNING_TYPE_EXPECTED
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040049
Alex Gaynoraceb3e22015-09-05 12:00:22 -040050
Jean-Paul Calderone9da338d2011-05-04 11:40:54 -040051def normalize_privatekey_pem(pem):
52 return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
53
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040054
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050055GOOD_CIPHER = "blowfish"
56BAD_CIPHER = "zippers"
57
Anthony Alba2ce737f2015-12-04 11:04:56 +080058GOOD_DIGEST = "SHA1"
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050059BAD_DIGEST = "monkeys"
60
Paul Kehrera40898b2017-06-11 16:30:58 -100061old_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
Rick Dean94e46fd2009-07-18 14:51:24 -050062MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
63BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
64ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
65NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
66MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
67ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
68urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
692xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
701dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
71FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
72VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
73BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
74b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
75AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
76hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
77w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
78-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -040079"""
Rick Dean94e46fd2009-07-18 14:51:24 -050080
Paul Kehrera40898b2017-06-11 16:30:58 -100081root_cert_pem = b"""-----BEGIN CERTIFICATE-----
82MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
83BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
84ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
85WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
86BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
87bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
88bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
89LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
90onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
91LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
92yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
93aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
94Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
95R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
96gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
97lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
98-----END CERTIFICATE-----
99"""
100
Alex Gaynore7f51982016-09-11 11:48:14 -0400101root_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500102MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
103jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
1043claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
105AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
106yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
1076JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
108BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
109u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
110PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
111I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
112ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
1136AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
114cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
115-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400116"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500117
Alex Gaynore7f51982016-09-11 11:48:14 -0400118intermediate_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700119MIICVzCCAcCgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQENBQAw
120WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
121DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTQw
122ODI4MDIwNDA4WhcNMjQwODI1MDIwNDA4WjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
123dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
124MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIGfMA0GCSqGSIb3DQEB
125AQUAA4GNADCBiQKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmK
126FGIbljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT
12721H2qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwID
128AQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDQUAA4GBAPIWSkLX
129QRMApOjjyC+tMxumT5e2pMqChHmxobQK4NMdrf2VCx+cRT6EmY8sK3/Xl/X8UBQ+
1309n5zXb1ZwhW/sTWgUvmOceJ4/XVs9FkdWOOn1J0XBch9ZIiFe/s5ASIgG7fUdcUF
1319mAWS6FK2ca3xIh5kIupCXOFa0dPvlw/YUFT
132-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400133"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700134
Alex Gaynore7f51982016-09-11 11:48:14 -0400135intermediate_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700136MIICWwIBAAKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmKFGIb
137ljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT21H2
138qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwIDAQAB
139AoGAfSZVV80pSeOKHTYfbGdNY/jHdU9eFUa/33YWriXU+77EhpIItJjkRRgivIfo
140rhFJpBSGmDLblaqepm8emsXMeH4+2QzOYIf0QGGP6E6scjTt1PLqdqKfVJ1a2REN
141147cujNcmFJb/5VQHHMpaPTgttEjlzuww4+BCDPsVRABWrkCQQD3loH36nLoQTtf
142+kQq0T6Bs9/UWkTAGo0ND81ALj0F8Ie1oeZg6RNT96RxZ3aVuFTESTv6/TbjWywO
143wdzlmV1vAkEA38rTJ6PTwaJlw5OttdDzAXGPB9tDmzh9oSi7cHwQQXizYd8MBYx4
144sjHUKD3dCQnb1dxJFhd3BT5HsnkRMbVZXQJAbXduH17ZTzcIOXc9jHDXYiFVZV5D
14552vV0WCbLzVCZc3jMrtSUKa8lPN5EWrdU3UchWybyG0MR5mX8S5lrF4SoQJAIyUD
146DBKaSqpqONCUUx1BTFS9FYrFjzbL4+c1qHCTTPTblt8kUCrDOZjBrKAqeiTmNSum
147/qUot9YUBF8m6BuGsQJATHHmdFy/fG1VLkyBp49CAa8tN3Z5r/CgTznI4DfMTf4C
148NbRHn2UmYlwQBa+L5lg9phewNe8aEwpPyPLoV85U8Q==
149-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400150"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700151
Alex Gaynore7f51982016-09-11 11:48:14 -0400152server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000153MIICJDCCAY2gAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
154BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
155VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMTA1
156N1oXDTM3MDYwNzAwMTA1N1owGDEWMBQGA1UEAwwNbG92ZWx5IHNlcnZlcjCBnzAN
157BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvqb4brndXS2kEL84qXbZXE6LYK+UrhNi
15870sdIM/24NVN7tXkPlOXqrMWhFHHml+aeSpPkH5b1vKnY1TcULmEubnNICtvjmZ5
159SGMQn+J+RmBs1SMd0EgY/0wBBQdlrlYp2QYgm8YC+zxTNSqWvhMFZAgHbj6Un5SS
160T8JGBqytjB0CAwEAAaM2MDQwHQYDVR0OBBYEFINVdy1eIfFJDAkk51QJEo3IfgSu
161MBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4GBAGki1K6WgHHJ
162qC6aY2EowjaWOXLO6jUZIhGk7BA7vMRfNug429AOZ4m5F6OQhzmJmlw67Jyu2FeI
163h0VtBuQoHPtjqZXF59oX6hMMmGLMs9pV0UA3fJs5MYA4/V5ZcQy0Ie0QoJNejLzE
1646V1Qz1rRTYLUyEcpI7ZCmBg2KQQI8YZI
Rick Dean94e46fd2009-07-18 14:51:24 -0500165-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400166"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500167
Alex Gaynore7f51982016-09-11 11:48:14 -0400168server_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500169MIICWwIBAAKBgQC+pvhuud1dLaQQvzipdtlcTotgr5SuE2LvSx0gz/bg1U3u1eQ+
170U5eqsxaEUceaX5p5Kk+QflvW8qdjVNxQuYS5uc0gK2+OZnlIYxCf4n5GYGzVIx3Q
171SBj/TAEFB2WuVinZBiCbxgL7PFM1Kpa+EwVkCAduPpSflJJPwkYGrK2MHQIDAQAB
172AoGAbwuZ0AR6JveahBaczjfnSpiFHf+mve2UxoQdpyr6ROJ4zg/PLW5K/KXrC48G
173j6f3tXMrfKHcpEoZrQWUfYBRCUsGD5DCazEhD8zlxEHahIsqpwA0WWssJA2VOLEN
174j6DuV2pCFbw67rfTBkTSo32ahfXxEKev5KswZk0JIzH3ooECQQDgzS9AI89h0gs8
175Dt+1m11Rzqo3vZML7ZIyGApUzVan+a7hbc33nbGRkAXjHaUBJO31it/H6dTO+uwX
176msWwNG5ZAkEA2RyFKs5xR5USTFaKLWCgpH/ydV96KPOpBND7TKQx62snDenFNNbn
177FwwOhpahld+vqhYk+pfuWWUpQciE+Bu7ZQJASjfT4sQv4qbbKK/scePicnDdx9th
1784e1EeB9xwb+tXXXUo/6Bor/AcUNwfiQ6Zt9PZOK9sR3lMZSsP7rMi7kzuQJABie6
1791sXXjFH7nNJvRG4S39cIxq8YRYTy68II/dlB2QzGpKxV/POCxbJ/zu0CU79tuYK7
180NaeNCFfH3aeTrX0LyQJAMBWjWmeKM2G2sCExheeQK0ROnaBC8itCECD4Jsve4nqf
181r50+LF74iLXFwqysVCebPKMOpDWp/qQ1BbJQIPs7/A==
182-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400183""")
Rick Dean94e46fd2009-07-18 14:51:24 -0500184
Alex Gaynore7f51982016-09-11 11:48:14 -0400185intermediate_server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700186MIICWDCCAcGgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQENBQAw
187ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
188CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
189biBEaWVnbzAeFw0xNDA4MjgwMjEwNDhaFw0yNDA4MjUwMjEwNDhaMG4xHTAbBgNV
190BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
191CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
192biBEaWVnbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqpJZygd+w1faLOr1
193iOAmbBhx5SZWcTCZ/ZjHQTJM7GuPT624QkqsixFghRKdDROwpwnAP7gMRukLqiy4
194+kRuGT5OfyGggL95i2xqA+zehjj08lSTlvGHpePJgCyTavIy5+Ljsj4DKnKyuhxm
195biXTRrH83NDgixVkObTEmh/OVK0CAwEAATANBgkqhkiG9w0BAQ0FAAOBgQBa0Npw
196UkzjaYEo1OUE1sTI6Mm4riTIHMak4/nswKh9hYup//WVOlr/RBSBtZ7Q/BwbjobN
1973bfAtV7eSAqBsfxYXyof7G1ALANQERkq3+oyLP1iVt08W1WOUlIMPhdCF/QuCwy6
198x9MJLhUCGLJPM+O2rAPWVD9wCmvq10ALsiH3yA==
199-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400200"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700201
Alex Gaynore7f51982016-09-11 11:48:14 -0400202intermediate_server_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700203MIICXAIBAAKBgQCqklnKB37DV9os6vWI4CZsGHHlJlZxMJn9mMdBMkzsa49PrbhC
204SqyLEWCFEp0NE7CnCcA/uAxG6QuqLLj6RG4ZPk5/IaCAv3mLbGoD7N6GOPTyVJOW
2058Yel48mALJNq8jLn4uOyPgMqcrK6HGZuJdNGsfzc0OCLFWQ5tMSaH85UrQIDAQAB
206AoGAIQ594j5zna3/9WaPsTgnmhlesVctt4AAx/n827DA4ayyuHFlXUuVhtoWR5Pk
2075ezj9mtYW8DyeCegABnsu2vZni/CdvU6uiS1Hv6qM1GyYDm9KWgovIP9rQCDSGaz
208d57IWVGxx7ODFkm3gN5nxnSBOFVHytuW1J7FBRnEsehRroECQQDXHFOv82JuXDcz
209z3+4c74IEURdOHcbycxlppmK9kFqm5lsUdydnnGW+mvwDk0APOB7Wg7vyFyr393e
210dpmBDCzNAkEAyv6tVbTKUYhSjW+QhabJo896/EqQEYUmtMXxk4cQnKeR/Ao84Rkf
211EqD5IykMUfUI0jJU4DGX+gWZ10a7kNbHYQJAVFCuHNFxS4Cpwo0aqtnzKoZaHY/8
212X9ABZfafSHCtw3Op92M+7ikkrOELXdS9KdKyyqbKJAKNEHF3LbOfB44WIQJAA2N4
2139UNNVUsXRbElEnYUS529CdUczo4QdVgQjkvk5RiPAUwSdBd9Q0xYnFOlFwEmIowg
214ipWJWe0aAlP18ZcEQQJBAL+5lekZ/GUdQoZ4HAsN5a9syrzavJ9VvU1KOOPorPZK
215nMRZbbQgP+aSB7yl6K0gaLaZ8XaK0pjxNBh6ASqg9f4=
216-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400217"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700218
Alex Gaynore7f51982016-09-11 11:48:14 -0400219client_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000220MIICIjCCAYugAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
221BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
222VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMDQx
223M1oXDTM3MDYwNzAwMDQxM1owFjEUMBIGA1UEAwwLdWdseSBjbGllbnQwgZ8wDQYJ
224KoZIhvcNAQEBBQADgY0AMIGJAoGBAMBmH9JG02bme0xPipvpjMSlOugyWrauf4at
225EdGJn7GQLD8IY2Fu0+Kvv9DFpSPboFKZCsfDVsYoRs+xaJbtt1dJ6ymX7EqKS7gb
2268q+eeZZ14keqyJd5Rm2q6swQtw9ADD3E8cS6GqpQm+8SgxOycISoYz7sO1ugJFqN
227jId+W4BFAgMBAAGjNjA0MB0GA1UdDgQWBBSDVXctXiHxSQwJJOdUCRKNyH4ErjAT
228BgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQAMqcHyweaCOZNN
229dWQQOsBKQlL5wqVVZwucHPWqobjxpULKy9gS2ha2zbgkXcB/BnBOSwe0Fm+MJV0T
230NbnTghcGJNpEH7VKn4xSLvIGZmnZZWgxeIB16z4GhpkK2fShBJ+6GKZjsgjT0lSH
231JRgjHbWutZfZvbSHXr9n7PIphG1Ojg==
Rick Dean94e46fd2009-07-18 14:51:24 -0500232-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400233"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500234
Alex Gaynore7f51982016-09-11 11:48:14 -0400235client_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500236MIICXgIBAAKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2rn+GrRHRiZ+xkCw/CGNh
237btPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xKiku4G/KvnnmWdeJHqsiX
238eUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7DtboCRajYyHfluARQIDAQAB
239AoGATkZ+NceY5Glqyl4mD06SdcKfV65814vg2EL7V9t8+/mi9rYL8KztSXGlQWPX
240zuHgtRoMl78yQ4ZJYOBVo+nsx8KZNRCEBlE19bamSbQLCeQMenWnpeYyQUZ908gF
241h6L9qsFVJepgA9RDgAjyDoS5CaWCdCCPCH2lDkdcqC54SVUCQQDseuduc4wi8h4t
242V8AahUn9fn9gYfhoNuM0gdguTA0nPLVWz4hy1yJiWYQe0H7NLNNTmCKiLQaJpAbb
243TC6vE8C7AkEA0Ee8CMJUc20BnGEmxwgWcVuqFWaKCo8jTH1X38FlATUsyR3krjW2
244dL3yDD9NwHxsYP7nTKp/U8MV7U9IBn4y/wJBAJl7H0/BcLeRmuJk7IqJ7b635iYB
245D/9beFUw3MUXmQXZUfyYz39xf6CDZsu1GEdEC5haykeln3Of4M9d/4Kj+FcCQQCY
246si6xwT7GzMDkk/ko684AV3KPc/h6G0yGtFIrMg7J3uExpR/VdH2KgwMkZXisSMvw
247JJEQjOMCVsEJlRk54WWjAkEAzoZNH6UhDdBK5F38rVt/y4SEHgbSfJHIAmPS32Kq
248f6GGcfNpip0Uk7q7udTKuX7Q/buZi/C4YW7u3VKAquv9NA==
249-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400250""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400251
Alex Gaynore7f51982016-09-11 11:48:14 -0400252cleartextCertificatePEM = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000253MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400254BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
Paul Kehrera40898b2017-06-11 16:30:58 -1000255ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
256WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
257BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
258bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
259bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
260LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
261onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
262LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
263yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
264aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
265Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
266R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
267gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
268lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400269-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400270"""
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400271
Alex Gaynore7f51982016-09-11 11:48:14 -0400272cleartextPrivateKeyPEM = normalize_privatekey_pem(b"""\
Jean-Paul Calderoned50d2042011-05-04 17:00:49 -0400273-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400274MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
275jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
2763claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
277AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
278yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
2796JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
280BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
281u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
282PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
283I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
284ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
2856AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
286cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
287-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400288""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400289
Alex Gaynore7f51982016-09-11 11:48:14 -0400290cleartextCertificateRequestPEM = b"""-----BEGIN CERTIFICATE REQUEST-----
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -0400291MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
292EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
293ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
294BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
295E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
296xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
297gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
298Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
299oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
300-----END CERTIFICATE REQUEST-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400301"""
Rick Dean5b7b6372009-04-01 11:34:06 -0500302
Alex Gaynore7f51982016-09-11 11:48:14 -0400303encryptedPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400304Proc-Type: 4,ENCRYPTED
305DEK-Info: DES-EDE3-CBC,9573604A18579E9E
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400306
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400307SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
308a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
3098+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
310mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
311+00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
312fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
313tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
314rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
315gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
316o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
3177SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
318MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
31911n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
320-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400321"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400322
Alex Gaynore7f51982016-09-11 11:48:14 -0400323encryptedPrivateKeyPEMPassphrase = b"foobar"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400324
Cory Benfield6492f7c2015-10-27 16:57:58 +0900325
Alex Gaynore7f51982016-09-11 11:48:14 -0400326cleartextPublicKeyPEM = b"""-----BEGIN PUBLIC KEY-----
Cory Benfield6492f7c2015-10-27 16:57:58 +0900327MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxszlc+b71LvlLS0ypt/l
328gT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZOtPclNY823Q4pErMTSWC
32990qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLjBuUIkQzEKEFV+8taiRV+
330ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPrUQqYQUEiTmVhh4FBUKZ5
331XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV215k4TeHMFYE5RG0KYAS
3328Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6HXRpQCyASzEG7bgtROLhL
333ywIDAQAB
334-----END PUBLIC KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400335"""
Cory Benfield6492f7c2015-10-27 16:57:58 +0900336
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400337# Some PKCS#7 stuff. Generated with the openssl command line:
338#
339# openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
340#
341# with a certificate and key (but the key should be irrelevant) in s.pem
Alex Gaynore7f51982016-09-11 11:48:14 -0400342pkcs7Data = b"""\
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400343-----BEGIN PKCS7-----
344MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
345BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
346A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
347MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
348cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
349A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
350HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
351SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
352zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
353LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
354A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
35565w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
356Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
357Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
358bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
359VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
360/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
361Ho4EzbYCOaEAMQA=
362-----END PKCS7-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400363"""
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400364
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700365pkcs7DataASN1 = base64.b64decode(b"""
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700366MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
367BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
368A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
369MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
370cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
371A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
372HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
373SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
374zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
375LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
376A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
37765w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
378Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
379Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
380bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
381VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
382/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
383Ho4EzbYCOaEAMQA=
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700384""")
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700385
Alex Gaynore7f51982016-09-11 11:48:14 -0400386crlData = b"""\
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -0500387-----BEGIN X509 CRL-----
388MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
389SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
390D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
391MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
392MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
3934dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
3940yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
395vrzEeLDRiiPl92dyyWmu
396-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400397"""
Jean-Paul Calderonee890db32010-08-22 16:55:15 -0400398
Alex Gaynore7f51982016-09-11 11:48:14 -0400399crlDataUnsupportedExtension = b"""\
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400400-----BEGIN X509 CRL-----
401MIIGRzCCBS8CAQIwDQYJKoZIhvcNAQELBQAwJzELMAkGA1UEBhMCVVMxGDAWBgNV
402BAMMD2NyeXB0b2dyYXBoeS5pbxgPMjAxNTAxMDEwMDAwMDBaGA8yMDE2MDEwMTAw
403MDAwMFowggTOMBQCAQAYDzIwMTUwMTAxMDAwMDAwWjByAgEBGA8yMDE1MDEwMTAw
404MDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAn
405MQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQD
406CgEAMHICAQIYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAw
407MDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlw
408dG9ncmFwaHkuaW8wCgYDVR0VBAMKAQEwcgIBAxgPMjAxNTAxMDEwMDAwMDBaMFww
409GAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTArpCkwJzELMAkGA1UE
410BhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNVHRUEAwoBAjByAgEE
411GA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQG
412A1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5
413LmlvMAoGA1UdFQQDCgEDMHICAQUYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQR
414GA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgw
415FgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQQwcgIBBhgPMjAxNTAx
416MDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTAr
417pCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNV
418HRUEAwoBBTByAgEHGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAx
419MDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwP
420Y3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEGMHICAQgYDzIwMTUwMTAxMDAwMDAw
421WjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJ
422BgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQgw
423cgIBCRgPMjAxNTAxMDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAw
424WjA0BgNVHR0ELTArpCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dy
425YXBoeS5pbzAKBgNVHRUEAwoBCTByAgEKGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNV
426HRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJV
427UzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEKMC4CAQsYDzIw
428MTUwMTAxMDAwMDAwWjAYMAoGA1UdFQQDCgEBMAoGAyoDBAQDCgEAMA0GCSqGSIb3
429DQEBCwUAA4IBAQBTaloHlPaCZzYee8LxkWej5meiqxQVNWFoVdjesroa+f1FRrH+
430drRU60Nq97KCKf7f9GNN/J3ZIlQmYhmuDqh12f+XLpotoj1ZRfBz2hjFCkJlv+2c
431oWWGNHgA70ndFoVtcmX088SYpX8E3ARATivS4q2h9WlwV6rO93mhg3HGIe3JpcK4
4327BcW6Poi/ut/zsDOkVbI00SqaujRpdmdCTht82MH3ztjyDkI9KYaD/YEweKSrWOz
433SdEILd164bfBeLuplVI+xpmTEMVNpXBlSXl7+xIw9Vk7p7Q1Pa3k/SvhOldYCm6y
434C1xAg/AAq6w78yzYt18j5Mj0s6eeHi1YpHKw
435-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400436"""
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400437
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400438
439# A broken RSA private key which can be used to test the error path through
440# PKey.check.
Alex Gaynore7f51982016-09-11 11:48:14 -0400441inconsistentPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400442MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
4435kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
444OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
445zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
446nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
447HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
448oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
449-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400450"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400451
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400452# certificate with NULL bytes in subjectAltName and common name
453
Alex Gaynore7f51982016-09-11 11:48:14 -0400454nulbyteSubjectAltNamePEM = b"""-----BEGIN CERTIFICATE-----
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400455MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
456DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
457eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
458RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
459ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
460NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
461DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
462ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
463ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
464hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
465BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
466pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
467vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
468KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
469oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
47008LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
471HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
472BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
473Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
474bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
475AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
476i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
477HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
478kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
479VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
480RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
Alex Gaynore7f51982016-09-11 11:48:14 -0400481-----END CERTIFICATE-----"""
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400482
Alex Gaynore7f51982016-09-11 11:48:14 -0400483large_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Colleen Murphye09399b2016-03-01 17:40:49 -0800484MIIJYgIBAAKCAg4AtRua8eIeevRfsj+fkcHr1vmse7Kgb+oX1ssJAvCb1R7JQMnH
485hNDjDP6b3vEkZuPUzlDHymP+cNkXvvi4wJ4miVbO3+SeU4Sh+jmsHeHzGIXat9xW
4869PFtuPM5FQq8zvkY8aDeRYmYwN9JKu4/neMBCBqostYlTEWg+bSytO/qWnyHTHKh
487g0GfaDdqUQPsGQw+J0MgaYIjQOCVASHAPlzbDQLCtuOb587rwTLkZA2GwoHB/LyJ
488BwT0HHgBaiObE12Vs6wi2en0Uu11CiwEuK1KIBcZ2XbE6eApaZa6VH9ysEmUxPt7
489TqyZ4E2oMIYaLPNRxuvozdwTlj1svI1k1FrkaXGc5MTjbgigPMKjIb0T7b/4GNzt
490DhP1LvAeUMnrEi3hJJrcJPXHPqS8/RiytR9xQQW6Sdh4LaA3f9MQm3WSevWage3G
491P8YcCLssOVKsArDjuA52NF5LmYuAeUzXprm4ITDi2oO+0iFBpFW6VPEK4A9vO0Yk
492M/6Wt6tG8zyWhaSH1zFUTwfQ9Yvjyt5w1lrUaAJuoTpwbMVZaDJaEhjOaXU0dyPQ
493jOsePDOQcU6dkeTWsQ3LsHPEEug/X6819TLG5mb3V7bvV9nPFBfTJSCEG794kr90
494XgZfIN71FrdByxLerlbuJI21pPs/nZi9SXi9jAWeiS45/azUxMsyYgJArui+gjq7
495sV1pWiBm6/orAgMBAAECggINQp5L6Yu+oIXBqcSjgq8tfF9M5hd30pLuf/EheHZf
496LA7uAqn2fVGFI2OInIJhXIOT5OxsAXO0xXfltzawZxIFpOFMqajj4F7aYjvSpw9V
497J4EdSiJ/zgv8y1qUdbwEZbHVThRZjoSlrtSzilonBoHZAE0mHtqMz7iRFSk1zz6t
498GunRrvo/lROPentf3TsvHquVNUYI5yaapyO1S7xJhecMIIYSb8nbsHI54FBDGNas
4996mFmpPwI/47/6HTwOEWupnn3NicsjrHzUInOUpaMig4cRR+aP5bjqg/ty8xI8AoN
500evEmCytiWTc+Rvbp1ieN+1jpjN18PjUk80/W7qioHUDt4ieLic8uxWH2VD9SCEnX
501Mpi9tA/FqoZ+2A/3m1OfrY6jiZVE2g+asi9lCK7QVWL39eK82H4rPvtp0/dyo1/i
502ZZz68TXg+m8IgEZcp88hngbkuoTTzpGE73QuPKhGA1uMIimDdqPPB5WP76q+03Oi
503IRR5DfZnqPERed49by0enJ7tKa/gFPZizOV8ALKr0Dp+vfAkxGDLPLBLd2A3//tw
504xg0Q/wltihHSBujv4nYlDXdc5oYyMYZ+Lhc/VuOghHfBq3tgEQ1ECM/ofqXEIdy7
505nVcpZn3Eeq8Jl5CrqxE1ee3NxlzsJHn99yGQpr7mOhW/psJF3XNz80Meg3L4m1T8
506sMBK0GbaassuJhdzb5whAoIBBw48sx1b1WR4XxQc5O/HjHva+l16i2pjUnOUTcDF
507RWmSbIhBm2QQ2rVhO8+fak0tkl6ZnMWW4i0U/X5LOEBbC7+IS8bO3j3Revi+Vw5x
508j96LMlIe9XEub5i/saEWgiz7maCvfzLFU08e1OpT4qPDpP293V400ubA6R7WQTCv
509pBkskGwHeu0l/TuKkVqBFFUTu7KEbps8Gjg7MkJaFriAOv1zis/umK8pVS3ZAM6e
5108w5jfpRccn8Xzta2fRwTB5kCmfxdDsY0oYGxPLRAbW72bORoLGuyyPp/ojeGwoik
511JX9RttErc6FjyZtks370Pa8UL5QskyhMbDhrZW2jFD+RXYM1BrvmZRjbAoIBBwy4
512iFJpuDfytJfz1MWtaL5DqEL/kmiZYAXl6hifNhGu5GAipVIIGsDqEYW4i+VC15aa
5137kOCwz/I5zsB3vSDW96IRs4wXtqEZSibc2W/bqfVi+xcvPPl1ZhQ2EAwa4D/x035
514kyf20ffWOU+1yf2cnijzqs3IzlveUm+meLw5s3Rc+iG7DPWWeCoe1hVwANI1euNc
515pqKwKY905yFyjOje2OgiEU2kS4YME4zGeBys8yo7E42hNnN2EPK6xkkUqzdudLLQ
5168OUlKRTc8AbIf3XG1rpA4VUpTv3hhxGGwCRy6If8zgZQsNYchgNztRGk72Gcb8Dm
517vFSEN3ZtwxU64G3YZzntdcr2WPzxAoIBBw30g6Fgdb/gmVnOpL0//T0ePNDKIMPs
518jVJLaRduhoZgB1Bb9qPUPX0SzRzLZtg1tkZSDjBDoHmOHJfhxUaXt+FLCPPbrE4t
519+nq9n/nBaMM779w9ClqhqLOyGrwKoxjSmhi+TVEHyIxCbXMvPHVHfX9WzxjbcGrN
520ZvRaEVZWo+QlIX8yqdSwqxLk1WtAIRzvlcj7NKum8xBxPed6BNFep/PtgIAmoLT5
521L8wb7EWb2iUdc2KbZ4OaY51lDScqpATgXu3WjXfM+Q52G0mX6Wyd0cjlL711Zrjb
522yLbiueZT94lgIHHRRKtKc8CEqcjkQV5OzABS3P/gQSfgZXBdLKjOpTnKDUq7IBeH
523AoIBBweAOEIAPLQg1QRUrr3xRrYKRwlakgZDii9wJt1l5AgBTICzbTA1vzDJ1JM5
524AqSpCV6w9JWyYVcXK+HLdKBRZLaPPNEQDJ5lOxD6uMziWGl2rg8tj+1xNMWfxiPz
525aTCjoe4EoBUMoTq2gwzRcM2usEQNikXVhnj9Wzaivsaeb4bJ3GRPW5DkrO6JSEtT
526w+gvyMqQM2Hy5k7E7BT46sXVwaj/jZxuqGnebRixXtnp0WixdRIqYWUr1UqLf6hQ
527G7WP2BgoxCMaCmNW8+HMD/xuxucEotoIhZ+GgJKBFoNnjl3BX+qxYdSe9RbL/5Tr
5284It6Jxtj8uETJXEbv9Cg6v1agWPS9YY8RLTBAoIBBwrU2AsAUts6h1LgGLKK3UWZ
529oLH5E+4o+7HqSGRcRodVeN9NBXIYdHHOLeEG6YNGJiJ3bFP5ZQEu9iDsyoFVKJ9O
530Mw/y6dKZuxOCZ+X8FopSROg3yWfdOpAm6cnQZp3WqLNX4n/Q6WvKojfyEiPphjwT
5310ymrUJELXLWJmjUyPoAk6HgC0Gs28ZnEXbyhx7CSbZNFyCU/PNUDZwto3GisIPD3
532le7YjqHugezmjMGlA0sDw5aCXjfbl74vowRFYMO6e3ItApfSRgNV86CDoX74WI/5
533AYU/QVM4wGt8XGT2KwDFJaxYGKsGDMWmXY04dS+WPuetCbouWUusyFwRb9SzFave
534vYeU7Ab/
Alex Gaynore7f51982016-09-11 11:48:14 -0400535-----END RSA PRIVATE KEY-----"""
Colleen Murphye09399b2016-03-01 17:40:49 -0800536
Paul Kehrer72d968b2016-07-29 15:31:04 +0800537ec_private_key_pem = b"""-----BEGIN PRIVATE KEY-----
538MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgYirTZSx+5O8Y6tlG
539cka6W6btJiocdrdolfcukSoTEk+hRANCAAQkvPNu7Pa1GcsWU4v7ptNfqCJVq8Cx
540zo0MUVPQgwJ3aJtNM1QMOQUayCrRwfklg+D/rFSUwEUqtZh7fJDiFqz3
541-----END PRIVATE KEY-----
542"""
543
Paul Kehrer59d26252017-07-20 10:45:54 +0200544ec_root_key_pem = b"""-----BEGIN EC PRIVATE KEY-----
545MIGlAgEBBDEAz/HOBFPYLB0jLWeTpJn4Yc4m/C4mdWymVHBjOmnwiPHKT326iYN/
546ZhmSs+RM94RsoAcGBSuBBAAioWQDYgAEwE5vDdla/nLpWAPAQ0yFGqwLuw4BcN2r
547U+sKab5EAEHzLeceRa8ffncYdCXNoVsBcdob1y66CFZMEWLetPTmGapyWkBAs6/L
5488kUlkU9OsE+7IVo4QQJkgV5gM+Dim1XE
549-----END EC PRIVATE KEY-----
550"""
551
552ec_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
553MIICLTCCAbKgAwIBAgIMWW/hwTl6ufz6/WkCMAoGCCqGSM49BAMDMFgxGDAWBgNV
554BAMTD1Rlc3RpbmcgUm9vdCBDQTEQMA4GA1UEChMHVGVzdGluZzEQMA4GA1UEBxMH
555Q2hpY2FnbzELMAkGA1UECBMCSUwxCzAJBgNVBAYTAlVTMCAXDTE3MDcxOTIyNDgz
556M1oYDzk5OTkxMjMxMjM1OTU5WjBYMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0Ex
557EDAOBgNVBAoTB1Rlc3RpbmcxEDAOBgNVBAcTB0NoaWNhZ28xCzAJBgNVBAgTAklM
558MQswCQYDVQQGEwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABMBObw3ZWv5y6VgD
559wENMhRqsC7sOAXDdq1PrCmm+RABB8y3nHkWvH353GHQlzaFbAXHaG9cuughWTBFi
5603rT05hmqclpAQLOvy/JFJZFPTrBPuyFaOEECZIFeYDPg4ptVxKNDMEEwDwYDVR0T
561AQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwQAMB0GA1UdDgQWBBSoTrF0H2m8RDzB
562MnY2KReEPfz7ZjAKBggqhkjOPQQDAwNpADBmAjEA3+G1oVCxGjYX4iUN93QYcNHe
563e3fJQJwX9+KsHRut6qNZDUbvRbtO1YIAwB4UJZjwAjEAtXCPURS5A4McZHnSwgTi
564Td8GMrwKz0557OxxtKN6uVVy4ACFMqEw0zN/KJI1vxc9
565-----END CERTIFICATE-----"""
566
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400567
Alex Chanc6077062016-11-18 13:53:39 +0000568@pytest.fixture
569def x509_data():
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400570 """
Alex Chanc6077062016-11-18 13:53:39 +0000571 Create a new private key and start a certificate request (for a test
572 to finish in one way or another).
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400573 """
Alex Chanc6077062016-11-18 13:53:39 +0000574 # Basic setup stuff to generate a certificate
575 pkey = PKey()
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400576 pkey.generate_key(TYPE_RSA, 512)
Alex Chanc6077062016-11-18 13:53:39 +0000577 req = X509Req()
578 req.set_pubkey(pkey)
579 # Authority good you have.
580 req.get_subject().commonName = "Yoda root CA"
581 x509 = X509()
582 subject = x509.get_subject()
583 subject.commonName = req.get_subject().commonName
584 x509.set_issuer(subject)
585 x509.set_pubkey(pkey)
586 now = datetime.now()
587 expire = datetime.now() + timedelta(days=100)
588 x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
589 x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
590 yield pkey, x509
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400591
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400592
Alex Chanc6077062016-11-18 13:53:39 +0000593class TestX509Ext(object):
594 """
595 Tests for `OpenSSL.crypto.X509Extension`.
596 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -0800597
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400598 def test_str(self):
599 """
Alex Chanc6077062016-11-18 13:53:39 +0000600 The string representation of `X509Extension` instances as
601 returned by `str` includes stuff.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400602 """
603 # This isn't necessarily the best string representation. Perhaps it
604 # will be changed/improved in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000605 assert (
606 str(X509Extension(b'basicConstraints', True, b'CA:false')) ==
607 'CA:FALSE'
608 )
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400609
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400610 def test_type(self):
611 """
Alex Chanc6077062016-11-18 13:53:39 +0000612 `X509Extension` and `X509ExtensionType` refer to the same type object
613 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400614 """
Alex Chanc6077062016-11-18 13:53:39 +0000615 assert X509Extension is X509ExtensionType
616 assert is_consistent_type(
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400617 X509Extension,
Alex Gaynore7f51982016-09-11 11:48:14 -0400618 'X509Extension', b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400619
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500620 def test_construction(self):
621 """
Alex Chanc6077062016-11-18 13:53:39 +0000622 `X509Extension` accepts an extension type name, a critical flag,
623 and an extension value and returns an `X509ExtensionType` instance.
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500624 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400625 basic = X509Extension(b'basicConstraints', True, b'CA:true')
Alex Chanc6077062016-11-18 13:53:39 +0000626 assert isinstance(basic, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500627
Alex Chanc6077062016-11-18 13:53:39 +0000628 comment = X509Extension(b'nsComment', False, b'pyOpenSSL unit test')
629 assert isinstance(comment, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500630
Alex Chanc6077062016-11-18 13:53:39 +0000631 @pytest.mark.parametrize('type_name, critical, value', [
632 (b'thisIsMadeUp', False, b'hi'),
633 (b'basicConstraints', False, b'blah blah'),
Jean-Paul Calderone391585f2008-12-31 14:36:31 -0500634
Jean-Paul Calderone2ee1e7c2008-12-31 14:58:38 -0500635 # Exercise a weird one (an extension which uses the r2i method). This
636 # exercises the codepath that requires a non-NULL ctx to be passed to
637 # X509V3_EXT_nconf. It can't work now because we provide no
638 # configuration database. It might be made to work in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000639 (b'proxyCertInfo', True,
640 b'language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')
641 ])
642 def test_invalid_extension(self, type_name, critical, value):
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500643 """
Alex Chanc6077062016-11-18 13:53:39 +0000644 `X509Extension` raises something if it is passed a bad
645 extension name or value.
646 """
647 with pytest.raises(Error):
648 X509Extension(type_name, critical, value)
649
650 @pytest.mark.parametrize('critical_flag', [True, False])
651 def test_get_critical(self, critical_flag):
652 """
653 `X509ExtensionType.get_critical` returns the value of the
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500654 extension's critical flag.
655 """
Alex Chanc6077062016-11-18 13:53:39 +0000656 ext = X509Extension(b'basicConstraints', critical_flag, b'CA:true')
657 assert ext.get_critical() == critical_flag
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500658
Alex Chanc6077062016-11-18 13:53:39 +0000659 @pytest.mark.parametrize('short_name, value', [
660 (b'basicConstraints', b'CA:true'),
661 (b'nsComment', b'foo bar'),
662 ])
663 def test_get_short_name(self, short_name, value):
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500664 """
Alex Chanc6077062016-11-18 13:53:39 +0000665 `X509ExtensionType.get_short_name` returns a string giving the
Alex Gaynor31287502015-09-05 16:11:27 -0400666 short type name of the extension.
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500667 """
Alex Chanc6077062016-11-18 13:53:39 +0000668 ext = X509Extension(short_name, True, value)
669 assert ext.get_short_name() == short_name
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500670
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400671 def test_get_data(self):
672 """
Alex Chanc6077062016-11-18 13:53:39 +0000673 `X509Extension.get_data` returns a string giving the data of
Alex Gaynor31287502015-09-05 16:11:27 -0400674 the extension.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400675 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400676 ext = X509Extension(b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400677 # Expect to get back the DER encoded form of CA:true.
Alex Chanc6077062016-11-18 13:53:39 +0000678 assert ext.get_data() == b'0\x03\x01\x01\xff'
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400679
Alex Chanc6077062016-11-18 13:53:39 +0000680 def test_unused_subject(self, x509_data):
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400681 """
Alex Chanc6077062016-11-18 13:53:39 +0000682 The `subject` parameter to `X509Extension` may be provided for an
683 extension which does not use it and is ignored in this case.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400684 """
Alex Chanc6077062016-11-18 13:53:39 +0000685 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400686 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000687 b'basicConstraints', False, b'CA:TRUE', subject=x509)
688 x509.add_extensions([ext1])
689 x509.sign(pkey, 'sha1')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400690 # This is a little lame. Can we think of a better way?
Alex Chanc6077062016-11-18 13:53:39 +0000691 text = dump_certificate(FILETYPE_TEXT, x509)
692 assert b'X509v3 Basic Constraints:' in text
693 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400694
Alex Chanc6077062016-11-18 13:53:39 +0000695 def test_subject(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400696 """
Alex Chanc6077062016-11-18 13:53:39 +0000697 If an extension requires a subject, the `subject` parameter to
698 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400699 """
Alex Chanc6077062016-11-18 13:53:39 +0000700 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400701 ext3 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000702 b'subjectKeyIdentifier', False, b'hash', subject=x509)
703 x509.add_extensions([ext3])
704 x509.sign(pkey, 'sha1')
705 text = dump_certificate(FILETYPE_TEXT, x509)
706 assert b'X509v3 Subject Key Identifier:' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400707
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400708 def test_missing_subject(self):
709 """
Alex Chanc6077062016-11-18 13:53:39 +0000710 If an extension requires a subject and the `subject` parameter
Alex Gaynor31287502015-09-05 16:11:27 -0400711 is given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400712 """
Alex Chanc6077062016-11-18 13:53:39 +0000713 with pytest.raises(Error):
714 X509Extension(b'subjectKeyIdentifier', False, b'hash')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400715
Alex Chanc6077062016-11-18 13:53:39 +0000716 @pytest.mark.parametrize('bad_obj', [
717 True,
718 object(),
719 "hello",
720 [],
721 ])
722 def test_invalid_subject(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400723 """
Alex Chanc6077062016-11-18 13:53:39 +0000724 If the `subject` parameter is given a value which is not an
725 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400726 """
Alex Chanc6077062016-11-18 13:53:39 +0000727 with pytest.raises(TypeError):
728 X509Extension(
729 'basicConstraints', False, 'CA:TRUE', subject=bad_obj)
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400730
Alex Chanc6077062016-11-18 13:53:39 +0000731 def test_unused_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400732 """
Alex Chanc6077062016-11-18 13:53:39 +0000733 The `issuer` parameter to `X509Extension` may be provided for an
734 extension which does not use it and is ignored in this case.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400735 """
Alex Chanc6077062016-11-18 13:53:39 +0000736 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400737 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000738 b'basicConstraints', False, b'CA:TRUE', issuer=x509)
739 x509.add_extensions([ext1])
740 x509.sign(pkey, 'sha1')
741 text = dump_certificate(FILETYPE_TEXT, x509)
742 assert b'X509v3 Basic Constraints:' in text
743 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400744
Alex Chanc6077062016-11-18 13:53:39 +0000745 def test_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400746 """
Alex Chanc6077062016-11-18 13:53:39 +0000747 If an extension requires an issuer, the `issuer` parameter to
748 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400749 """
Alex Chanc6077062016-11-18 13:53:39 +0000750 pkey, x509 = x509_data
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400751 ext2 = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -0400752 b'authorityKeyIdentifier', False, b'issuer:always',
Alex Chanc6077062016-11-18 13:53:39 +0000753 issuer=x509)
754 x509.add_extensions([ext2])
755 x509.sign(pkey, 'sha1')
756 text = dump_certificate(FILETYPE_TEXT, x509)
757 assert b'X509v3 Authority Key Identifier:' in text
758 assert b'DirName:/CN=Yoda root CA' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400759
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400760 def test_missing_issuer(self):
761 """
Alex Chanc6077062016-11-18 13:53:39 +0000762 If an extension requires an issue and the `issuer` parameter is
763 given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400764 """
Alex Chanc6077062016-11-18 13:53:39 +0000765 with pytest.raises(Error):
766 X509Extension(
767 b'authorityKeyIdentifier',
768 False, b'keyid:always,issuer:always')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400769
Alex Chanc6077062016-11-18 13:53:39 +0000770 @pytest.mark.parametrize('bad_obj', [
771 True,
772 object(),
773 "hello",
774 [],
775 ])
776 def test_invalid_issuer(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400777 """
Alex Chanc6077062016-11-18 13:53:39 +0000778 If the `issuer` parameter is given a value which is not an
779 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400780 """
Alex Chanc6077062016-11-18 13:53:39 +0000781 with pytest.raises(TypeError):
782 X509Extension(
783 'basicConstraints', False, 'keyid:always,issuer:always',
784 issuer=bad_obj)
Rick Dean47262da2009-07-08 16:17:17 -0500785
786
Paul Kehrer72d968b2016-07-29 15:31:04 +0800787class TestPKey(object):
788 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +0100789 Tests for `OpenSSL.crypto.PKey`.
Paul Kehrer72d968b2016-07-29 15:31:04 +0800790 """
791
792 def test_convert_from_cryptography_private_key(self):
793 """
794 PKey.from_cryptography_key creates a proper private PKey.
795 """
796 key = serialization.load_pem_private_key(
797 intermediate_key_pem, None, backend
798 )
799 pkey = PKey.from_cryptography_key(key)
800
801 assert isinstance(pkey, PKey)
802 assert pkey.bits() == key.key_size
803 assert pkey._only_public is False
804 assert pkey._initialized is True
805
806 def test_convert_from_cryptography_public_key(self):
807 """
808 PKey.from_cryptography_key creates a proper public PKey.
809 """
810 key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
811 pkey = PKey.from_cryptography_key(key)
812
813 assert isinstance(pkey, PKey)
814 assert pkey.bits() == key.key_size
815 assert pkey._only_public is True
816 assert pkey._initialized is True
817
818 def test_convert_from_cryptography_unsupported_type(self):
819 """
820 PKey.from_cryptography_key raises TypeError with an unsupported type.
821 """
822 key = serialization.load_pem_private_key(
823 ec_private_key_pem, None, backend
824 )
825 with pytest.raises(TypeError):
826 PKey.from_cryptography_key(key)
827
828 def test_convert_public_pkey_to_cryptography_key(self):
829 """
830 PKey.to_cryptography_key creates a proper cryptography public key.
831 """
832 pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
833 key = pkey.to_cryptography_key()
834
835 assert isinstance(key, rsa.RSAPublicKey)
836 assert pkey.bits() == key.key_size
837
838 def test_convert_private_pkey_to_cryptography_key(self):
839 """
840 PKey.to_cryptography_key creates a proper cryptography private key.
841 """
842 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
843 key = pkey.to_cryptography_key()
844
845 assert isinstance(key, rsa.RSAPrivateKey)
846 assert pkey.bits() == key.key_size
847
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400848 def test_type(self):
849 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000850 `PKey` and `PKeyType` refer to the same type object and can be used to
851 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400852 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000853 assert PKey is PKeyType
854 assert is_consistent_type(PKey, 'PKey')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400855
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500856 def test_construction(self):
857 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000858 `PKey` takes no arguments and returns a new `PKey` instance.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500859 """
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500860 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000861 assert isinstance(key, PKey)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500862
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500863 def test_pregeneration(self):
864 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000865 `PKey.bits` and `PKey.type` return `0` before the key is generated.
866 `PKey.check` raises `TypeError` before the key is generated.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500867 """
868 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000869 assert key.type() == 0
870 assert key.bits() == 0
871 with pytest.raises(TypeError):
872 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500873
Alex Chan9e2a9932017-01-25 14:29:19 +0000874 def test_failed_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500875 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000876 `PKey.generate_key` takes two arguments, the first giving the key type
877 as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
878 bits to generate. If an invalid type is specified or generation fails,
879 `Error` is raised. If an invalid number of bits is specified,
880 `ValueError` or `Error` is raised.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500881 """
882 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000883 with pytest.raises(TypeError):
884 key.generate_key("foo", "bar")
885 with pytest.raises(Error):
886 key.generate_key(-1, 0)
Jean-Paul Calderoneab82db72008-03-06 00:09:31 -0500887
Alex Chan9e2a9932017-01-25 14:29:19 +0000888 with pytest.raises(ValueError):
889 key.generate_key(TYPE_RSA, -1)
890 with pytest.raises(ValueError):
891 key.generate_key(TYPE_RSA, 0)
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500892
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400893 with pytest.raises(TypeError):
894 key.generate_key(TYPE_RSA, object())
895
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500896 # XXX RSA generation for small values of bits is fairly buggy in a wide
897 # range of OpenSSL versions. I need to figure out what the safe lower
898 # bound for a reasonable number of OpenSSL versions is and explicitly
899 # check for that in the wrapper. The failure behavior is typically an
900 # infinite loop inside OpenSSL.
901
Alex Chan9e2a9932017-01-25 14:29:19 +0000902 # with pytest.raises(Error):
903 # key.generate_key(TYPE_RSA, 2)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500904
905 # XXX DSA generation seems happy with any number of bits. The DSS
906 # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
907 # generator doesn't seem to care about the upper limit at all. For
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500908 # the lower limit, it uses 512 if anything smaller is specified.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500909 # So, it doesn't seem possible to make generate_key fail for
910 # TYPE_DSA with a bits argument which is at least an int.
911
Alex Chan9e2a9932017-01-25 14:29:19 +0000912 # with pytest.raises(Error):
913 # key.generate_key(TYPE_DSA, -7)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500914
Alex Chan9e2a9932017-01-25 14:29:19 +0000915 def test_rsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500916 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000917 `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
918 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500919 """
Alex Gaynor6e9f9762018-05-12 07:44:37 -0400920 bits = 512
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500921 key = PKey()
922 key.generate_key(TYPE_RSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000923 assert key.type() == TYPE_RSA
924 assert key.bits() == bits
925 assert key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500926
Alex Chan9e2a9932017-01-25 14:29:19 +0000927 def test_dsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500928 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000929 `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
930 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500931 """
932 # 512 is a magic number. The DSS (Digital Signature Standard)
933 # allows a minimum of 512 bits for DSA. DSA_generate_parameters
934 # will silently promote any value below 512 to 512.
935 bits = 512
936 key = PKey()
937 key.generate_key(TYPE_DSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000938 assert key.type() == TYPE_DSA
939 assert key.bits() == bits
940 with pytest.raises(TypeError):
941 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500942
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500943 def test_regeneration(self):
944 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000945 `PKey.generate_key` can be called multiple times on the same key to
946 generate new keys.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500947 """
948 key = PKey()
949 for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
Alex Gaynor7f636492015-09-04 13:26:52 -0400950 key.generate_key(type, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000951 assert key.type() == type
952 assert key.bits() == bits
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500953
Alex Chan9e2a9932017-01-25 14:29:19 +0000954 def test_inconsistent_key(self):
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400955 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000956 `PKey.check` returns `Error` if the key is not consistent.
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400957 """
958 key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
Alex Chan9e2a9932017-01-25 14:29:19 +0000959 with pytest.raises(Error):
960 key.check()
Jean-Paul Calderonee81020e2011-06-12 21:48:57 -0400961
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400962 def test_check_public_key(self):
963 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000964 `PKey.check` raises `TypeError` if only the public part of the key
965 is available.
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400966 """
967 # A trick to get a public-only key
968 key = PKey()
969 key.generate_key(TYPE_RSA, 512)
970 cert = X509()
971 cert.set_pubkey(key)
972 pub = cert.get_pubkey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000973 with pytest.raises(TypeError):
974 pub.check()
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400975
976
Alex Chan9e2a9932017-01-25 14:29:19 +0000977def x509_name(**attrs):
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500978 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000979 Return a new X509Name with the given attributes.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500980 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000981 # XXX There's no other way to get a new X509Name yet.
982 name = X509().get_subject()
983 attrs = list(attrs.items())
Alex Gaynoraceb3e22015-09-05 12:00:22 -0400984
Alex Chan9e2a9932017-01-25 14:29:19 +0000985 # Make the order stable - order matters!
986 def key(attr):
987 return attr[1]
988 attrs.sort(key=key)
989 for k, v in attrs:
990 setattr(name, k, v)
991 return name
Alex Gaynor85b49702015-09-05 16:30:59 -0400992
Alex Chan9e2a9932017-01-25 14:29:19 +0000993
994class TestX509Name(object):
995 """
996 Unit tests for `OpenSSL.crypto.X509Name`.
997 """
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -0500998
Rick Deane15b1472009-07-09 15:53:42 -0500999 def test_type(self):
1000 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001001 The type of X509Name objects is `X509NameType`.
Rick Deane15b1472009-07-09 15:53:42 -05001002 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001003 assert X509Name is X509NameType
1004 assert X509NameType.__name__ == 'X509Name'
1005 assert isinstance(X509NameType, type)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001006
Alex Chan9e2a9932017-01-25 14:29:19 +00001007 name = x509_name()
1008 assert isinstance(name, X509NameType)
Rick Deane15b1472009-07-09 15:53:42 -05001009
Alex Chan9e2a9932017-01-25 14:29:19 +00001010 def test_only_string_attributes(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001011 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001012 Attempting to set a non-`str` attribute name on an `X509Name` instance
1013 causes `TypeError` to be raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001014 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001015 name = x509_name()
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001016 # Beyond these cases, you may also think that unicode should be
Alex Gaynor31287502015-09-05 16:11:27 -04001017 # rejected. Sorry, you're wrong. unicode is automatically converted
1018 # to str outside of the control of X509Name, so there's no way to
1019 # reject it.
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -08001020
Alex Gaynor31287502015-09-05 16:11:27 -04001021 # Also, this used to test str subclasses, but that test is less
1022 # relevant now that the implementation is in Python instead of C. Also
1023 # PyPy automatically converts str subclasses to str when they are
1024 # passed to setattr, so we can't test it on PyPy. Apparently CPython
1025 # does this sometimes as well.
Alex Chan9e2a9932017-01-25 14:29:19 +00001026 with pytest.raises(TypeError):
1027 setattr(name, None, "hello")
1028 with pytest.raises(TypeError):
1029 setattr(name, 30, "hello")
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001030
Alex Chan9e2a9932017-01-25 14:29:19 +00001031 def test_set_invalid_attribute(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001032 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001033 Attempting to set any attribute name on an `X509Name` instance for
1034 which no corresponding NID is defined causes `AttributeError` to be
1035 raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001036 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001037 name = x509_name()
1038 with pytest.raises(AttributeError):
1039 setattr(name, "no such thing", None)
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001040
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001041 def test_attributes(self):
1042 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001043 `X509Name` instances have attributes for each standard (?)
1044 X509Name field.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001045 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001046 name = x509_name()
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001047 name.commonName = "foo"
Alex Gaynor37726112016-07-04 09:51:32 -04001048 assert name.commonName == "foo"
1049 assert name.CN == "foo"
1050
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001051 name.CN = "baz"
Alex Gaynor37726112016-07-04 09:51:32 -04001052 assert name.commonName == "baz"
1053 assert name.CN == "baz"
1054
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001055 name.commonName = "bar"
Alex Gaynor37726112016-07-04 09:51:32 -04001056 assert name.commonName == "bar"
1057 assert name.CN == "bar"
1058
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001059 name.CN = "quux"
Alex Gaynor37726112016-07-04 09:51:32 -04001060 assert name.commonName == "quux"
1061 assert name.CN == "quux"
1062
1063 assert name.OU is None
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001064
Alex Gaynor7778e792016-07-03 23:38:48 -04001065 with pytest.raises(AttributeError):
1066 name.foobar
1067
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001068 def test_copy(self):
1069 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001070 `X509Name` creates a new `X509Name` instance with all the same
1071 attributes as an existing `X509Name` instance when called with one.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001072 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001073 name = x509_name(commonName="foo", emailAddress="bar@example.com")
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001074
1075 copy = X509Name(name)
Alex Chan9e2a9932017-01-25 14:29:19 +00001076 assert copy.commonName == "foo"
1077 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001078
1079 # Mutate the copy and ensure the original is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001080 copy.commonName = "baz"
Alex Chan9e2a9932017-01-25 14:29:19 +00001081 assert name.commonName == "foo"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001082
1083 # Mutate the original and ensure the copy is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001084 name.emailAddress = "quux@example.com"
Alex Chan9e2a9932017-01-25 14:29:19 +00001085 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001086
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001087 def test_repr(self):
1088 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001089 `repr` passed an `X509Name` instance should return a string containing
1090 a description of the type and the NIDs which have been set on it.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001091 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001092 name = x509_name(commonName="foo", emailAddress="bar")
1093 assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001094
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001095 def test_comparison(self):
1096 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001097 `X509Name` instances should compare based on their NIDs.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001098 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001099 def _equality(a, b, assert_true, assert_false):
1100 assert_true(a == b)
1101 assert_false(a != b)
1102 assert_true(b == a)
1103 assert_false(b != a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001104
Alex Chan9e2a9932017-01-25 14:29:19 +00001105 def assert_true(x):
1106 assert x
1107
1108 def assert_false(x):
1109 assert not x
1110
1111 def assert_equal(a, b):
1112 _equality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001113
1114 # Instances compare equal to themselves.
Alex Chan9e2a9932017-01-25 14:29:19 +00001115 name = x509_name()
1116 assert_equal(name, name)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001117
1118 # Empty instances should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001119 assert_equal(x509_name(), x509_name())
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001120
1121 # Instances with equal NIDs should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001122 assert_equal(x509_name(commonName="foo"),
1123 x509_name(commonName="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001124
1125 # Instance with equal NIDs set using different aliases should compare
1126 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001127 assert_equal(x509_name(commonName="foo"),
1128 x509_name(CN="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001129
1130 # Instances with more than one NID with the same values should compare
1131 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001132 assert_equal(x509_name(CN="foo", organizationalUnitName="bar"),
1133 x509_name(commonName="foo", OU="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001134
Alex Chan9e2a9932017-01-25 14:29:19 +00001135 def assert_not_equal(a, b):
1136 _equality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001137
1138 # Instances with different values for the same NID should not compare
1139 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001140 assert_not_equal(x509_name(CN="foo"),
1141 x509_name(CN="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001142
1143 # Instances with different NIDs should not compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001144 assert_not_equal(x509_name(CN="foo"),
1145 x509_name(OU="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001146
Alex Chan9e2a9932017-01-25 14:29:19 +00001147 assert_not_equal(x509_name(), object())
Alex Gaynor7778e792016-07-03 23:38:48 -04001148
Alex Chan9e2a9932017-01-25 14:29:19 +00001149 def _inequality(a, b, assert_true, assert_false):
1150 assert_true(a < b)
1151 assert_true(a <= b)
1152 assert_true(b > a)
1153 assert_true(b >= a)
1154 assert_false(a > b)
1155 assert_false(a >= b)
1156 assert_false(b < a)
1157 assert_false(b <= a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001158
Alex Chan9e2a9932017-01-25 14:29:19 +00001159 def assert_less_than(a, b):
1160 _inequality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001161
1162 # An X509Name with a NID with a value which sorts less than the value
1163 # of the same NID on another X509Name compares less than the other
1164 # X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001165 assert_less_than(x509_name(CN="abc"),
1166 x509_name(CN="def"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001167
Alex Chan9e2a9932017-01-25 14:29:19 +00001168 def assert_greater_than(a, b):
1169 _inequality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001170
1171 # An X509Name with a NID with a value which sorts greater than the
1172 # value of the same NID on another X509Name compares greater than the
1173 # other X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001174 assert_greater_than(x509_name(CN="def"),
1175 x509_name(CN="abc"))
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001176
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001177 def test_hash(self):
1178 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001179 `X509Name.hash` returns an integer hash based on the value of the name.
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001180 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001181 a = x509_name(CN="foo")
1182 b = x509_name(CN="foo")
1183 assert a.hash() == b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001184 a.CN = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001185 assert a.hash() != b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001186
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001187 def test_der(self):
1188 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001189 `X509Name.der` returns the DER encoded form of the name.
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001190 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001191 a = x509_name(CN="foo", C="US")
1192 assert (a.der() ==
1193 b'0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
1194 b'1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo')
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001195
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001196 def test_get_components(self):
1197 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001198 `X509Name.get_components` returns a `list` of two-tuples of `str`
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001199 giving the NIDs and associated values which make up the name.
1200 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001201 a = x509_name()
1202 assert a.get_components() == []
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001203 a.CN = "foo"
Alex Chan9e2a9932017-01-25 14:29:19 +00001204 assert a.get_components() == [(b"CN", b"foo")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001205 a.organizationalUnitName = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001206 assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001207
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001208 def test_load_nul_byte_attribute(self):
1209 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001210 An `X509Name` from an `X509` instance loaded from a file can have a
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001211 NUL byte in the value of one of its attributes.
1212 """
1213 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1214 subject = cert.get_subject()
Alex Chan9e2a9932017-01-25 14:29:19 +00001215 assert "null.python.org\x00example.org" == subject.commonName
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001216
Romuald Brunet4183beb2019-01-21 19:38:33 +01001217 def test_load_nul_byte_components(self):
1218 """
1219 An `X509Name` from an `X509` instance loaded from a file can have a
1220 NUL byte in the value of its components
1221 """
1222 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1223 subject = cert.get_subject()
1224 components = subject.get_components()
1225 ccn = [value for name, value in components if name == b'CN']
1226 assert ccn[0] == b'null.python.org\x00example.org'
1227
Alex Chan9e2a9932017-01-25 14:29:19 +00001228 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001229 """
1230 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001231 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001232 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001233 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001234 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001235 with pytest.raises(Error):
1236 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001237
1238
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001239class _PKeyInteractionTestsMixin:
1240 """
1241 Tests which involve another thing and a PKey.
1242 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001243
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001244 def signable(self):
1245 """
Alex Chanfb078d82017-04-20 11:16:15 +01001246 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001247 """
1248 raise NotImplementedError()
1249
Alex Chanb00ede22017-01-30 07:24:40 +00001250 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001251 """
Alex Chanb00ede22017-01-30 07:24:40 +00001252 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001253 """
1254 request = self.signable()
1255 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001256 with pytest.raises(ValueError):
1257 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001258
Alex Chanb00ede22017-01-30 07:24:40 +00001259 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001260 """
Alex Chanb00ede22017-01-30 07:24:40 +00001261 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1262 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001263 """
1264 request = self.signable()
1265 key = PKey()
1266 key.generate_key(TYPE_RSA, 512)
1267 request.set_pubkey(key)
1268 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001269 with pytest.raises(ValueError):
1270 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001271
Alex Chanb00ede22017-01-30 07:24:40 +00001272 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001273 """
Alex Chanb00ede22017-01-30 07:24:40 +00001274 `X509Req.sign` raises `ValueError` when passed a digest name which is
1275 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001276 """
1277 request = self.signable()
1278 key = PKey()
1279 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001280 with pytest.raises(ValueError):
1281 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001282
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001283 def test_sign(self):
1284 """
Alex Chanb00ede22017-01-30 07:24:40 +00001285 `X509Req.sign` succeeds when passed a private key object and a
1286 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001287 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001288 """
1289 request = self.signable()
1290 key = PKey()
1291 key.generate_key(TYPE_RSA, 512)
1292 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001293 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001294 # If the type has a verify method, cover that too.
1295 if getattr(request, 'verify', None) is not None:
1296 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001297 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001298 # Make another key that won't verify.
1299 key = PKey()
1300 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001301 with pytest.raises(Error):
1302 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001303
1304
Alex Chanb00ede22017-01-30 07:24:40 +00001305class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001306 """
Alex Chanb00ede22017-01-30 07:24:40 +00001307 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001308 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001309
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001310 def signable(self):
1311 """
Alex Chanb00ede22017-01-30 07:24:40 +00001312 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001313 """
1314 return X509Req()
1315
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001316 def test_type(self):
1317 """
Alex Chanb00ede22017-01-30 07:24:40 +00001318 `X509Req` and `X509ReqType` refer to the same type object and can be
1319 used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001320 """
Alex Chanb00ede22017-01-30 07:24:40 +00001321 assert X509Req is X509ReqType
1322 assert is_consistent_type(X509Req, 'X509Req')
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001323
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001324 def test_construction(self):
1325 """
Alex Chanb00ede22017-01-30 07:24:40 +00001326 `X509Req` takes no arguments and returns an `X509ReqType` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001327 """
1328 request = X509Req()
Alex Gaynor31287502015-09-05 16:11:27 -04001329 assert isinstance(request, X509ReqType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001330
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001331 def test_version(self):
1332 """
Alex Chanb00ede22017-01-30 07:24:40 +00001333 `X509Req.set_version` sets the X.509 version of the certificate
1334 request. `X509Req.get_version` returns the X.509 version of the
1335 certificate request. The initial value of the version is 0.
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001336 """
1337 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001338 assert request.get_version() == 0
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001339 request.set_version(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001340 assert request.get_version() == 1
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001341 request.set_version(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001342 assert request.get_version() == 3
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001343
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001344 def test_version_wrong_args(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001345 """
Alex Chanb00ede22017-01-30 07:24:40 +00001346 `X509Req.set_version` raises `TypeError` if called with a non-`int`
1347 argument.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001348 """
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001349 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001350 with pytest.raises(TypeError):
1351 request.set_version("foo")
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001352
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001353 def test_get_subject(self):
1354 """
Alex Chanb00ede22017-01-30 07:24:40 +00001355 `X509Req.get_subject` returns an `X509Name` for the subject of the
1356 request and which is valid even after the request object is
1357 otherwise dead.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001358 """
1359 request = X509Req()
1360 subject = request.get_subject()
Alex Gaynor31287502015-09-05 16:11:27 -04001361 assert isinstance(subject, X509NameType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001362 subject.commonName = "foo"
Alex Chanb00ede22017-01-30 07:24:40 +00001363 assert request.get_subject().commonName == "foo"
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001364 del request
1365 subject.commonName = "bar"
Alex Chanb00ede22017-01-30 07:24:40 +00001366 assert subject.commonName == "bar"
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001367
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001368 def test_add_extensions(self):
1369 """
Alex Chanb00ede22017-01-30 07:24:40 +00001370 `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
1371 and adds them to the X509 request.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001372 """
1373 request = X509Req()
1374 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001375 X509Extension(b'basicConstraints', True, b'CA:false')])
Stephen Holsappleca545b72014-01-28 21:43:25 -08001376 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001377 assert len(exts) == 1
1378 assert exts[0].get_short_name() == b'basicConstraints'
1379 assert exts[0].get_critical() == 1
1380 assert exts[0].get_data() == b'0\x00'
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001381
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001382 def test_get_extensions(self):
1383 """
Alex Chanb00ede22017-01-30 07:24:40 +00001384 `X509Req.get_extensions` returns a `list` of extensions added to this
1385 X509 request.
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001386 """
1387 request = X509Req()
1388 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001389 assert exts == []
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001390 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001391 X509Extension(b'basicConstraints', True, b'CA:true'),
1392 X509Extension(b'keyUsage', False, b'digitalSignature')])
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001393 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001394 assert len(exts) == 2
1395 assert exts[0].get_short_name() == b'basicConstraints'
1396 assert exts[0].get_critical() == 1
1397 assert exts[0].get_data() == b'0\x03\x01\x01\xff'
1398 assert exts[1].get_short_name() == b'keyUsage'
1399 assert exts[1].get_critical() == 0
1400 assert exts[1].get_data() == b'\x03\x02\x07\x80'
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001401
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001402 def test_add_extensions_wrong_args(self):
1403 """
Alex Chanb00ede22017-01-30 07:24:40 +00001404 `X509Req.add_extensions` raises `TypeError` if called with a
1405 non-`list`. Or it raises `ValueError` if called with a `list`
1406 containing objects other than `X509Extension` instances.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001407 """
1408 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001409 with pytest.raises(TypeError):
1410 request.add_extensions(object())
1411 with pytest.raises(ValueError):
1412 request.add_extensions([object()])
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001413
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001414 def test_verify_wrong_args(self):
1415 """
Alex Chanb00ede22017-01-30 07:24:40 +00001416 `X509Req.verify` raises `TypeError` if passed anything other than a
1417 `PKey` instance as its single argument.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001418 """
1419 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001420 with pytest.raises(TypeError):
1421 request.verify(object())
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001422
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001423 def test_verify_uninitialized_key(self):
1424 """
Alex Chanb00ede22017-01-30 07:24:40 +00001425 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1426 `OpenSSL.crypto.PKey` which contains no key data.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001427 """
1428 request = X509Req()
1429 pkey = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001430 with pytest.raises(Error):
1431 request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001432
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001433 def test_verify_wrong_key(self):
1434 """
Alex Chanb00ede22017-01-30 07:24:40 +00001435 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1436 `OpenSSL.crypto.PKey` which does not represent the public part of the
Alex Gaynor31287502015-09-05 16:11:27 -04001437 key which signed the request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001438 """
1439 request = X509Req()
1440 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001441 request.sign(pkey, GOOD_DIGEST)
Alex Chanb00ede22017-01-30 07:24:40 +00001442 another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
1443 with pytest.raises(Error):
1444 request.verify(another_pkey)
1445
1446 def test_verify_success(self):
1447 """
1448 `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
1449 which represents the public part of the key which signed the request.
1450 """
1451 request = X509Req()
1452 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
1453 request.sign(pkey, GOOD_DIGEST)
1454 assert request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001455
Paul Kehrer41c10242017-06-29 18:24:17 -05001456 def test_convert_from_cryptography(self):
1457 crypto_req = x509.load_pem_x509_csr(
1458 cleartextCertificateRequestPEM, backend
1459 )
1460 req = X509Req.from_cryptography(crypto_req)
1461 assert isinstance(req, X509Req)
1462
1463 def test_convert_from_cryptography_unsupported_type(self):
1464 with pytest.raises(TypeError):
1465 X509Req.from_cryptography(object())
1466
1467 def test_convert_to_cryptography_key(self):
1468 req = load_certificate_request(
1469 FILETYPE_PEM, cleartextCertificateRequestPEM
1470 )
1471 crypto_req = req.to_cryptography()
1472 assert isinstance(crypto_req, x509.CertificateSigningRequest)
1473
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001474
Alex Chanb00ede22017-01-30 07:24:40 +00001475class TestX509(_PKeyInteractionTestsMixin):
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001476 """
Alex Chanb00ede22017-01-30 07:24:40 +00001477 Tests for `OpenSSL.crypto.X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001478 """
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001479 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Jean-Paul Calderone8114b452008-03-25 15:27:59 -04001480
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001481 extpem = """
1482-----BEGIN CERTIFICATE-----
1483MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
1484BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
1485eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
1486MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
1487aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
1488hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
1489Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
1490zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
1491hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
1492TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
149303HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
1494MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
1495b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
1496MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
1497uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
1498WpOdIpB8KksUTCzV591Nr1wd
1499-----END CERTIFICATE-----
1500 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001501
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001502 def signable(self):
1503 """
Alex Chanb00ede22017-01-30 07:24:40 +00001504 Create and return a new `X509`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001505 """
1506 return X509()
1507
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001508 def test_type(self):
1509 """
Alex Chanb00ede22017-01-30 07:24:40 +00001510 `X509` and `X509Type` refer to the same type object and can be used to
1511 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001512 """
Alex Chanb00ede22017-01-30 07:24:40 +00001513 assert X509 is X509Type
1514 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001515
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001516 def test_construction(self):
1517 """
Alex Chanb00ede22017-01-30 07:24:40 +00001518 `X509` takes no arguments and returns an instance of `X509Type`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001519 """
1520 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001521 assert isinstance(certificate, X509Type)
1522 assert type(X509Type).__name__ == 'type'
1523 assert type(certificate).__name__ == 'X509'
1524 assert type(certificate) == X509Type
1525 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001526
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001527 def test_set_version_wrong_args(self):
1528 """
Alex Chanb00ede22017-01-30 07:24:40 +00001529 `X509.set_version` raises `TypeError` if invoked with an argument
1530 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001531 """
1532 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001533 with pytest.raises(TypeError):
1534 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001535
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001536 def test_version(self):
1537 """
Alex Chanb00ede22017-01-30 07:24:40 +00001538 `X509.set_version` sets the certificate version number.
1539 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001540 """
1541 cert = X509()
1542 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001543 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001544
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001545 def test_serial_number(self):
1546 """
Alex Chanb00ede22017-01-30 07:24:40 +00001547 The serial number of an `X509` can be retrieved and
1548 modified with `X509.get_serial_number` and
1549 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001550 """
1551 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001552 with pytest.raises(TypeError):
1553 certificate.set_serial_number("1")
1554 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001555 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001556 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001557 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001558 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001559 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001560 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001561 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001562 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001563
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001564 def _setBoundTest(self, which):
1565 """
Alex Chanb00ede22017-01-30 07:24:40 +00001566 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001567 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1568 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001569 """
1570 certificate = X509()
1571 set = getattr(certificate, 'set_not' + which)
1572 get = getattr(certificate, 'get_not' + which)
1573
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001574 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001575 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001576
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001577 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001578 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001579 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001580 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001581
1582 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001583 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001584 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001585 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001586
1587 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001588 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001589 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001590 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001591
1592 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001593 with pytest.raises(ValueError):
1594 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001595
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001596 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001597 with pytest.raises(TypeError):
1598 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001599 with pytest.raises(TypeError):
1600 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001601 with pytest.raises(TypeError):
1602 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001603
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001604 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001605
1606 def test_set_notBefore(self):
1607 """
Alex Chanb00ede22017-01-30 07:24:40 +00001608 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001609 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1610 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001611 """
1612 self._setBoundTest("Before")
1613
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001614 def test_set_notAfter(self):
1615 """
Alex Chanb00ede22017-01-30 07:24:40 +00001616 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001617 GENERALIZEDTIME and sets the end of the certificate's validity period
1618 to it.
1619 """
1620 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001621
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001622 def test_get_notBefore(self):
1623 """
Alex Chanb00ede22017-01-30 07:24:40 +00001624 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001625 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001626 internally.
1627 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001628 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001629 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001630
Rick Dean38a05c82009-07-18 01:41:30 -05001631 def test_get_notAfter(self):
1632 """
Alex Chanb00ede22017-01-30 07:24:40 +00001633 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001634 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001635 internally.
1636 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001637 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001638 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001639
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001640 def test_gmtime_adj_notBefore_wrong_args(self):
1641 """
Alex Chanb00ede22017-01-30 07:24:40 +00001642 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1643 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001644 """
1645 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001646 with pytest.raises(TypeError):
1647 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001648
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001649 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001650 def test_gmtime_adj_notBefore(self):
1651 """
Alex Chanb00ede22017-01-30 07:24:40 +00001652 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1653 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001654 """
1655 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001656 not_before_min = (
1657 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1658 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001659 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001660 not_before = datetime.strptime(
1661 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1662 )
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001663 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001664 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001665
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001666 def test_gmtime_adj_notAfter_wrong_args(self):
1667 """
Alex Chanb00ede22017-01-30 07:24:40 +00001668 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1669 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001670 """
1671 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001672 with pytest.raises(TypeError):
1673 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001674
Alex Gaynor642de6f2017-07-24 00:57:38 -04001675 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001676 def test_gmtime_adj_notAfter(self):
1677 """
Alex Chanb00ede22017-01-30 07:24:40 +00001678 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001679 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001680 """
1681 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001682 not_after_min = (
1683 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1684 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001685 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001686 not_after = datetime.strptime(
1687 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1688 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001689 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001690 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001691
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001692 def test_has_expired(self):
1693 """
Alex Chanb00ede22017-01-30 07:24:40 +00001694 `X509.has_expired` returns `True` if the certificate's not-after time
1695 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001696 """
1697 cert = X509()
1698 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001699 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001700
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001701 def test_has_not_expired(self):
1702 """
Alex Chanb00ede22017-01-30 07:24:40 +00001703 `X509.has_expired` returns `False` if the certificate's not-after time
1704 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001705 """
1706 cert = X509()
1707 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001708 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001709
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001710 def test_root_has_not_expired(self):
1711 """
Alex Chanb00ede22017-01-30 07:24:40 +00001712 `X509.has_expired` returns `False` if the certificate's not-after time
1713 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001714 """
1715 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001716 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001717
Rick Dean38a05c82009-07-18 01:41:30 -05001718 def test_digest(self):
1719 """
Alex Chanb00ede22017-01-30 07:24:40 +00001720 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001721 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001722 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001723 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001724 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001725 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1726 # actually matters to the assertion (ie, another arbitrary, good
1727 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001728 # Digest verified with the command:
1729 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001730 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001731 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001732
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001733 def _extcert(self, pkey, extensions):
1734 cert = X509()
1735 cert.set_pubkey(pkey)
1736 cert.get_subject().commonName = "Unit Tests"
1737 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001738 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001739 cert.set_notBefore(when)
1740 cert.set_notAfter(when)
1741
1742 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001743 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001744 return load_certificate(
1745 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1746
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001747 def test_extension_count(self):
1748 """
Alex Chanb00ede22017-01-30 07:24:40 +00001749 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001750 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001751 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001752 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001753 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1754 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001755 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001756 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001757
1758 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001759 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001760 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001761
1762 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001763 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001764 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001765
1766 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001767 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001768 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001769
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001770 def test_get_extension(self):
1771 """
Alex Chanb00ede22017-01-30 07:24:40 +00001772 `X509.get_extension` takes an integer and returns an
1773 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001774 """
1775 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001776 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1777 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001778 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001779 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001780
1781 cert = self._extcert(pkey, [ca, key, subjectAltName])
1782
1783 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001784 assert isinstance(ext, X509Extension)
1785 assert ext.get_critical()
1786 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001787
1788 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001789 assert isinstance(ext, X509Extension)
1790 assert ext.get_critical()
1791 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001792
1793 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001794 assert isinstance(ext, X509Extension)
1795 assert not ext.get_critical()
1796 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001797
Alex Chanb00ede22017-01-30 07:24:40 +00001798 with pytest.raises(IndexError):
1799 cert.get_extension(-1)
1800 with pytest.raises(IndexError):
1801 cert.get_extension(4)
1802 with pytest.raises(TypeError):
1803 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001804
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001805 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001806 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001807 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001808 bytes and this value is reflected in the string representation of the
1809 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001810 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001811 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001812
1813 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001814 assert ext.get_short_name() == b'subjectAltName'
1815 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001816 b"DNS:altnull.python.org\x00example.com, "
1817 b"email:null@python.org\x00user@example.org, "
1818 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001819 b"IP Address:192.0.2.1, IP Address:2001:DB8:0:0:0:0:0:1\n" ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001820 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001821
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001822 def test_invalid_digest_algorithm(self):
1823 """
Alex Chanb00ede22017-01-30 07:24:40 +00001824 `X509.digest` raises `ValueError` if called with an unrecognized hash
1825 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001826 """
1827 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001828 with pytest.raises(ValueError):
1829 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001830
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001831 def test_get_subject(self):
1832 """
Alex Chanb00ede22017-01-30 07:24:40 +00001833 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001834 """
1835 cert = load_certificate(FILETYPE_PEM, self.pemData)
1836 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001837 assert isinstance(subj, X509Name)
1838 assert (
1839 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001840 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1841 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001842
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001843 def test_set_subject_wrong_args(self):
1844 """
Alex Chanb00ede22017-01-30 07:24:40 +00001845 `X509.set_subject` raises a `TypeError` if called with an argument not
1846 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001847 """
1848 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001849 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001850 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001851
1852 def test_set_subject(self):
1853 """
Alex Chanb00ede22017-01-30 07:24:40 +00001854 `X509.set_subject` changes the subject of the certificate to the one
1855 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001856 """
1857 cert = X509()
1858 name = cert.get_subject()
1859 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001860 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001861 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001862 assert (
1863 cert.get_subject().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001864 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001865
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001866 def test_get_issuer(self):
1867 """
Alex Chanb00ede22017-01-30 07:24:40 +00001868 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001869 """
1870 cert = load_certificate(FILETYPE_PEM, self.pemData)
1871 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001872 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001873 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001874 assert (
1875 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001876 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1877 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001878
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001879 def test_set_issuer_wrong_args(self):
1880 """
Alex Chanb00ede22017-01-30 07:24:40 +00001881 `X509.set_issuer` raises a `TypeError` if called with an argument not
1882 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001883 """
1884 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001885 with pytest.raises(TypeError):
1886 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001887
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001888 def test_set_issuer(self):
1889 """
Alex Chanb00ede22017-01-30 07:24:40 +00001890 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001891 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001892 """
1893 cert = X509()
1894 name = cert.get_issuer()
1895 name.C = 'AU'
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001896 name.OU = 'Unit Tests'
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001897 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001898 assert (
1899 cert.get_issuer().get_components() ==
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001900 [(b'C', b'AU'), (b'OU', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001901
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001902 def test_get_pubkey_uninitialized(self):
1903 """
Alex Chanb00ede22017-01-30 07:24:40 +00001904 When called on a certificate with no public key, `X509.get_pubkey`
1905 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001906 """
1907 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001908 with pytest.raises(Error):
1909 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001910
Alex Gaynor7778e792016-07-03 23:38:48 -04001911 def test_set_pubkey_wrong_type(self):
1912 """
Alex Chanb00ede22017-01-30 07:24:40 +00001913 `X509.set_pubkey` raises `TypeError` when given an object of the
1914 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001915 """
1916 cert = X509()
1917 with pytest.raises(TypeError):
1918 cert.set_pubkey(object())
1919
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001920 def test_subject_name_hash(self):
1921 """
Alex Chanb00ede22017-01-30 07:24:40 +00001922 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001923 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001924 """
1925 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001926 assert cert.subject_name_hash() in [
1927 3350047874, # OpenSSL 0.9.8, MD5
1928 3278919224, # OpenSSL 1.0.0, SHA1
1929 ]
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001930
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001931 def test_get_signature_algorithm(self):
1932 """
Alex Chanb00ede22017-01-30 07:24:40 +00001933 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001934 the algorithm used to sign the certificate.
1935 """
1936 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001937 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001938
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001939 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001940 """
Alex Chanb00ede22017-01-30 07:24:40 +00001941 `X509.get_signature_algorithm` raises `ValueError` if the signature
1942 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001943 """
1944 # This certificate has been modified to indicate a bogus OID in the
1945 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001946 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001947-----BEGIN CERTIFICATE-----
1948MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1949EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1950cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1951MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1952EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1953CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1954AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1955+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1956hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1957BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1958FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1959dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1960aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1961MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1962jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1963PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1964tgI5
1965-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001966"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001967 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001968 with pytest.raises(ValueError):
1969 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001970
Alex Gaynor37726112016-07-04 09:51:32 -04001971 def test_sign_bad_pubkey_type(self):
1972 """
Alex Chanb00ede22017-01-30 07:24:40 +00001973 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001974 """
1975 cert = X509()
1976 with pytest.raises(TypeError):
1977 cert.sign(object(), b"sha256")
1978
Alex Gaynor9939ba12017-06-25 16:28:24 -04001979 def test_convert_from_cryptography(self):
1980 crypto_cert = x509.load_pem_x509_certificate(
1981 intermediate_cert_pem, backend
1982 )
1983 cert = X509.from_cryptography(crypto_cert)
1984
1985 assert isinstance(cert, X509)
1986 assert cert.get_version() == crypto_cert.version.value
1987
1988 def test_convert_from_cryptography_unsupported_type(self):
1989 with pytest.raises(TypeError):
1990 X509.from_cryptography(object())
1991
1992 def test_convert_to_cryptography_key(self):
1993 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1994 crypto_cert = cert.to_cryptography()
1995
1996 assert isinstance(crypto_cert, x509.Certificate)
1997 assert crypto_cert.version.value == cert.get_version()
1998
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001999
Alex Chan9e2a9932017-01-25 14:29:19 +00002000class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002001 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002002 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002003 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002004
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002005 def test_type(self):
2006 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002007 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002008 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002009 assert X509Store is X509StoreType
2010 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002011
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002012 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002013 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002014 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002015 """
2016 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002017 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002018 store.add_cert(cert)
2019
Alex Chanfb078d82017-04-20 11:16:15 +01002020 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2021 def test_add_cert_wrong_args(self, cert):
2022 """
2023 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2024 as its first argument.
2025 """
2026 store = X509Store()
2027 with pytest.raises(TypeError):
2028 store.add_cert(cert)
2029
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002030 def test_add_cert_accepts_duplicate(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002031 """
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002032 `X509Store.add_cert` doesn't raise `OpenSSL.crypto.Error` if an attempt
2033 is made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002034 """
2035 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2036 store = X509Store()
2037 store.add_cert(cert)
Paul Kehrer0e6c5532018-08-23 10:52:15 -05002038 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002039
2040
Alex Chanb00ede22017-01-30 07:24:40 +00002041class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002042 """
Alex Chanb00ede22017-01-30 07:24:40 +00002043 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002044 """
2045 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2046
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002047 def test_type(self):
2048 """
Alex Chanb00ede22017-01-30 07:24:40 +00002049 `PKCS12Type` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002050 """
Alex Chanb00ede22017-01-30 07:24:40 +00002051 assert PKCS12 is PKCS12Type
2052 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002053
Rick Deanf94096c2009-07-18 14:23:06 -05002054 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002055 """
Alex Chanb00ede22017-01-30 07:24:40 +00002056 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2057 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002058 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002059 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002060 assert None is p12.get_certificate()
2061 assert None is p12.get_privatekey()
2062 assert None is p12.get_ca_certificates()
2063 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002064
2065 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002066 """
Alex Chanb00ede22017-01-30 07:24:40 +00002067 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2068 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2069 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002070 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002071 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002072 for bad_arg in [3, PKey(), X509]:
2073 with pytest.raises(TypeError):
2074 p12.set_certificate(bad_arg)
2075 for bad_arg in [3, 'legbone', X509()]:
2076 with pytest.raises(TypeError):
2077 p12.set_privatekey(bad_arg)
2078 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2079 with pytest.raises(TypeError):
2080 p12.set_ca_certificates(bad_arg)
2081 for bad_arg in [6, ('foo', 'bar')]:
2082 with pytest.raises(TypeError):
2083 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002084
2085 def test_key_only(self):
2086 """
Alex Chanb00ede22017-01-30 07:24:40 +00002087 A `PKCS12` with only a private key can be exported using
2088 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002089 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002090 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002091 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002092 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002093 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002094 assert None is p12.get_certificate()
2095 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002096 try:
2097 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2098 except Error:
2099 # Some versions of OpenSSL will throw an exception
2100 # for this nearly useless PKCS12 we tried to generate:
2101 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2102 return
Rick Dean623ee362009-07-17 12:22:16 -05002103 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002104 assert None is p12.get_ca_certificates()
2105 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002106
2107 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2108 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002109 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002110
2111 def test_cert_only(self):
2112 """
Alex Chanb00ede22017-01-30 07:24:40 +00002113 A `PKCS12` with only a certificate can be exported using
2114 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002115 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002116 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002117 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002118 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002119 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002120 assert cert == p12.get_certificate()
2121 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002122 try:
2123 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2124 except Error:
2125 # Some versions of OpenSSL will throw an exception
2126 # for this nearly useless PKCS12 we tried to generate:
2127 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2128 return
Rick Dean623ee362009-07-17 12:22:16 -05002129 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002130 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002131
2132 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002133 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002134
2135 # Oh ho. It puts the certificate into the ca certificates list, in
2136 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2137 # that to check to see if it reconstructed the certificate we expected
2138 # it to. At some point, hopefully this will change so that
2139 # p12.get_certificate() is actually what returns the loaded
2140 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002141 assert (
2142 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002143 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002144
Alex Gaynor31287502015-09-05 16:11:27 -04002145 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2146 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002147 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002148 Generate a PKCS12 object with components from PEM. Verify that the set
2149 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002150 """
Rick Deanf94096c2009-07-18 14:23:06 -05002151 p12 = PKCS12()
2152 if cert_pem:
2153 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002154 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002155 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002156 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002157 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002158 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002159 ret = p12.set_ca_certificates(
2160 (load_certificate(FILETYPE_PEM, ca_pem),)
2161 )
Alex Chanb00ede22017-01-30 07:24:40 +00002162 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002163 if friendly_name:
2164 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002165 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002166 return p12
2167
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002168 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002169 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002170 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002171 Use openssl program to confirm three components are recoverable from a
2172 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002173 """
2174 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002175 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002176 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2177 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002178 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002179 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002180 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002181 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2182 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002183 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002184 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002185 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002186 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2187 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002188 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002189
Stephen Holsapple38482622014-04-05 20:29:34 -07002190 def verify_pkcs12_container(self, p12):
2191 """
2192 Verify that the PKCS#12 container contains the correct client
2193 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002194
2195 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002196 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002197 """
2198 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2199 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002200 assert (
2201 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002202 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002203
Rick Deanf94096c2009-07-18 14:23:06 -05002204 def test_load_pkcs12(self):
2205 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002206 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002207 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002208 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002209 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002210 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002211 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002212 pem,
2213 b"pkcs12",
2214 b"-export",
2215 b"-clcerts",
2216 b"-passout",
2217 b"pass:" + passwd
2218 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002219 p12 = load_pkcs12(p12_str, passphrase=passwd)
2220 self.verify_pkcs12_container(p12)
2221
Abraham Martinc5484ba2015-03-25 15:33:05 +00002222 def test_load_pkcs12_text_passphrase(self):
2223 """
2224 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002225 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002226 Using text as passphrase instead of bytes. DeprecationWarning expected.
2227 """
2228 pem = client_key_pem + client_cert_pem
2229 passwd = b"whatever"
2230 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2231 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002232 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002233 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002234 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002235 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002236 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002237 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002238 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002239
Abraham Martinc5484ba2015-03-25 15:33:05 +00002240 self.verify_pkcs12_container(p12)
2241
Stephen Holsapple38482622014-04-05 20:29:34 -07002242 def test_load_pkcs12_no_passphrase(self):
2243 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002244 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002245 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002246 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002247 """
2248 pem = client_key_pem + client_cert_pem
2249 p12_str = _runopenssl(
2250 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2251 p12 = load_pkcs12(p12_str)
2252 self.verify_pkcs12_container(p12)
2253
Stephen Holsapple38482622014-04-05 20:29:34 -07002254 def _dump_and_load(self, dump_passphrase, load_passphrase):
2255 """
2256 A helper method to dump and load a PKCS12 object.
2257 """
2258 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2259 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2260 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2261
Stephen Holsapple38482622014-04-05 20:29:34 -07002262 def test_load_pkcs12_null_passphrase_load_empty(self):
2263 """
2264 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002265 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002266 extracted and examined.
2267 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002268 self.verify_pkcs12_container(
2269 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002270
Stephen Holsapple38482622014-04-05 20:29:34 -07002271 def test_load_pkcs12_null_passphrase_load_null(self):
2272 """
2273 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002274 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002275 extracted and examined.
2276 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002277 self.verify_pkcs12_container(
2278 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002279
Stephen Holsapple38482622014-04-05 20:29:34 -07002280 def test_load_pkcs12_empty_passphrase_load_empty(self):
2281 """
2282 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002283 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002284 extracted and examined.
2285 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002286 self.verify_pkcs12_container(
2287 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002288
Stephen Holsapple38482622014-04-05 20:29:34 -07002289 def test_load_pkcs12_empty_passphrase_load_null(self):
2290 """
2291 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002292 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002293 extracted and examined.
2294 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002295 self.verify_pkcs12_container(
2296 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002297
Rick Deanee568302009-07-24 09:56:29 -05002298 def test_load_pkcs12_garbage(self):
2299 """
Alex Chanb00ede22017-01-30 07:24:40 +00002300 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002301 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002302 """
2303 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002304 with pytest.raises(Error) as err:
2305 load_pkcs12(b'fruit loops', passwd)
2306 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2307 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002308
Rick Deanf94096c2009-07-18 14:23:06 -05002309 def test_replace(self):
2310 """
Alex Chanb00ede22017-01-30 07:24:40 +00002311 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2312 cluster. `PKCS12.set_privatekey` replaces the private key.
2313 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002314 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002315 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2316 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2317 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002318 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002319 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002320 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002321 assert 1 == len(p12.get_ca_certificates())
2322 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002323 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002324 assert 2 == len(p12.get_ca_certificates())
2325 assert client_cert == p12.get_ca_certificates()[0]
2326 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002327
Rick Deanf94096c2009-07-18 14:23:06 -05002328 def test_friendly_name(self):
2329 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002330 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002331 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2332 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002333 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002334 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002335 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002336 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002337 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002338 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002339 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002340 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002341 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002342 # We would use the openssl program to confirm the friendly
2343 # name, but it is not possible. The pkcs12 command
2344 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002345 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002346 self.check_recovery(
2347 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2348 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002349
Rick Deanf94096c2009-07-18 14:23:06 -05002350 def test_various_empty_passphrases(self):
2351 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002352 Test that missing, None, and '' passphrases are identical for PKCS12
2353 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002354 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002355 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002356 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002357 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2358 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2359 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2360 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2361 self.check_recovery(
2362 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2363 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002364
Rick Deanf94096c2009-07-18 14:23:06 -05002365 def test_removing_ca_cert(self):
2366 """
Alex Chanb00ede22017-01-30 07:24:40 +00002367 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2368 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002369 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002370 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2371 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002372 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002373
Rick Deanf94096c2009-07-18 14:23:06 -05002374 def test_export_without_mac(self):
2375 """
Alex Chanb00ede22017-01-30 07:24:40 +00002376 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002377 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002378 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002379 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002380 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002381 self.check_recovery(
2382 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002383 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002384
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002385 def test_load_without_mac(self):
2386 """
2387 Loading a PKCS12 without a MAC does something other than crash.
2388 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002389 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002390 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2391 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002392 try:
2393 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2394 # The person who generated this PCKS12 should be flogged,
2395 # or better yet we should have a means to determine
2396 # whether a PCKS12 had a MAC that was verified.
2397 # Anyway, libopenssl chooses to allow it, so the
2398 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002399 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002400 except Error:
2401 # Failing here with an exception is preferred as some openssl
2402 # versions do.
2403 pass
Rick Dean623ee362009-07-17 12:22:16 -05002404
Rick Dean25bcc1f2009-07-20 11:53:13 -05002405 def test_zero_len_list_for_ca(self):
2406 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002407 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002408 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002409 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002410 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002411 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002412 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002413 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2414 self.check_recovery(
2415 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2416 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002417
Rick Deanf94096c2009-07-18 14:23:06 -05002418 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002419 """
Alex Chanb00ede22017-01-30 07:24:40 +00002420 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002421 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002422 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002423 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002424 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002425 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002426
Abraham Martinc5484ba2015-03-25 15:33:05 +00002427 def test_export_without_bytes(self):
2428 """
Alex Chanb00ede22017-01-30 07:24:40 +00002429 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002430 """
2431 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2432
Alex Chanb00ede22017-01-30 07:24:40 +00002433 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002434 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002435 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002436 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002437 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002438 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002439 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002440 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002441 dumped_p12,
2442 key=server_key_pem,
2443 cert=server_cert_pem,
2444 passwd=b"randomtext"
2445 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002446
Rick Deanf94096c2009-07-18 14:23:06 -05002447 def test_key_cert_mismatch(self):
2448 """
Alex Chanb00ede22017-01-30 07:24:40 +00002449 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002450 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002451 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002452 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002453 with pytest.raises(Error):
2454 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002455
2456
Rick Dean4c9ad612009-07-17 15:05:22 -05002457def _runopenssl(pem, *args):
2458 """
2459 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002460 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002461 """
Alex Gaynor6cbc69a2017-07-25 09:07:04 -04002462 proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002463 proc.stdin.write(pem)
2464 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002465 output = proc.stdout.read()
2466 proc.stdout.close()
2467 proc.wait()
2468 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002469
2470
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002471class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002472 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002473 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002474 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002475 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002476 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002477 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002478 """
2479 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002480
2481 assert True is key._only_public
2482 assert 2048 == key.bits()
2483 assert TYPE_RSA == key.type()
2484
2485 def test_invalid_type(self):
2486 """
2487 load_publickey doesn't support FILETYPE_TEXT.
2488 """
2489 with pytest.raises(ValueError):
2490 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2491
2492 def test_invalid_key_format(self):
2493 """
2494 load_publickey explodes on incorrect keys.
2495 """
2496 with pytest.raises(Error):
2497 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2498
2499 def test_tolerates_unicode_strings(self):
2500 """
2501 load_publickey works with text strings, not just bytes.
2502 """
2503 serialized = cleartextPublicKeyPEM.decode('ascii')
2504 key = load_publickey(FILETYPE_PEM, serialized)
2505 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2506
2507 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002508
2509
Alex Chanb00ede22017-01-30 07:24:40 +00002510class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002511 """
Alex Chanb00ede22017-01-30 07:24:40 +00002512 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002513 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002514
2515 def test_load_privatekey_invalid_format(self):
2516 """
Alex Chanb00ede22017-01-30 07:24:40 +00002517 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002518 """
Alex Chanb00ede22017-01-30 07:24:40 +00002519 with pytest.raises(ValueError):
2520 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002521
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002522 def test_load_privatekey_invalid_passphrase_type(self):
2523 """
Alex Chanb00ede22017-01-30 07:24:40 +00002524 `load_privatekey` raises `TypeError` if passed a passphrase that is
2525 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002526 """
Alex Chanb00ede22017-01-30 07:24:40 +00002527 with pytest.raises(TypeError):
2528 load_privatekey(
2529 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002530
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002531 def test_load_privatekey_wrongPassphrase(self):
2532 """
Alex Chanb00ede22017-01-30 07:24:40 +00002533 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2534 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002535 """
Alex Chanb00ede22017-01-30 07:24:40 +00002536 with pytest.raises(Error) as err:
2537 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2538 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002539
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002540 def test_load_privatekey_passphraseWrongType(self):
2541 """
Alex Chanb00ede22017-01-30 07:24:40 +00002542 `load_privatekey` raises `ValueError` when it is passeda passphrase
2543 with a private key encoded in a format, that doesn't support
2544 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002545 """
2546 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2547 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002548 with pytest.raises(ValueError):
2549 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002550
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002551 def test_load_privatekey_passphrase(self):
2552 """
Alex Chanb00ede22017-01-30 07:24:40 +00002553 `load_privatekey` can create a `PKey` object from an encrypted PEM
2554 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002555 """
2556 key = load_privatekey(
2557 FILETYPE_PEM, encryptedPrivateKeyPEM,
2558 encryptedPrivateKeyPEMPassphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002559 assert isinstance(key, PKeyType)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002560
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002561 def test_load_privatekey_passphrase_exception(self):
2562 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002563 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002564 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002565 """
2566 def cb(ignored):
2567 raise ArithmeticError
2568
Alex Gaynor791212d2015-09-05 15:46:08 -04002569 with pytest.raises(ArithmeticError):
2570 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002571
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002572 def test_load_privatekey_wrongPassphraseCallback(self):
2573 """
Alex Chanb00ede22017-01-30 07:24:40 +00002574 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002575 is passed an encrypted PEM and a passphrase callback which returns an
2576 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002577 """
2578 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002579
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002580 def cb(*a):
2581 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002582 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002583 with pytest.raises(Error) as err:
2584 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2585 assert called
2586 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002587
2588 def test_load_privatekey_passphraseCallback(self):
2589 """
Alex Chanb00ede22017-01-30 07:24:40 +00002590 `load_privatekey` can create a `PKey` object from an encrypted PEM
2591 string if given a passphrase callback which returns the correct
2592 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002593 """
2594 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002595
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002596 def cb(writing):
2597 called.append(writing)
2598 return encryptedPrivateKeyPEMPassphrase
2599 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002600 assert isinstance(key, PKeyType)
2601 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002602
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002603 def test_load_privatekey_passphrase_wrong_return_type(self):
2604 """
Alex Chanb00ede22017-01-30 07:24:40 +00002605 `load_privatekey` raises `ValueError` if the passphrase callback
2606 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002607 """
Alex Chanb00ede22017-01-30 07:24:40 +00002608 with pytest.raises(ValueError):
2609 load_privatekey(
2610 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002611
Alex Chanfb078d82017-04-20 11:16:15 +01002612 def test_dump_privatekey_wrong_args(self):
2613 """
2614 `dump_privatekey` raises `TypeError` if called with a `cipher`
2615 argument but no `passphrase` argument.
2616 """
2617 key = PKey()
2618 key.generate_key(TYPE_RSA, 512)
2619 with pytest.raises(TypeError):
2620 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2621
Paul Kehrercded9932017-06-29 18:43:42 -05002622 def test_dump_privatekey_not_rsa_key(self):
2623 """
2624 `dump_privatekey` raises `TypeError` if called with a key that is
2625 not RSA.
2626 """
2627 key = PKey()
2628 key.generate_key(TYPE_DSA, 512)
2629 with pytest.raises(TypeError):
2630 dump_privatekey(FILETYPE_TEXT, key)
2631
2632 def test_dump_privatekey_invalid_pkey(self):
2633 with pytest.raises(TypeError):
2634 dump_privatekey(FILETYPE_TEXT, object())
2635
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002636 def test_dump_privatekey_unknown_cipher(self):
2637 """
Alex Chanb00ede22017-01-30 07:24:40 +00002638 `dump_privatekey` raises `ValueError` if called with an unrecognized
2639 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002640 """
2641 key = PKey()
2642 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002643 with pytest.raises(ValueError):
2644 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002645
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002646 def test_dump_privatekey_invalid_passphrase_type(self):
2647 """
Alex Chanb00ede22017-01-30 07:24:40 +00002648 `dump_privatekey` raises `TypeError` if called with a passphrase which
2649 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002650 """
2651 key = PKey()
2652 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002653 with pytest.raises(TypeError):
2654 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002655
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002656 def test_dump_privatekey_invalid_filetype(self):
2657 """
Alex Chanb00ede22017-01-30 07:24:40 +00002658 `dump_privatekey` raises `ValueError` if called with an unrecognized
2659 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002660 """
2661 key = PKey()
2662 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002663 with pytest.raises(ValueError):
2664 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002665
Alex Chanb00ede22017-01-30 07:24:40 +00002666 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002667 """
Alex Chanb00ede22017-01-30 07:24:40 +00002668 `crypto.load_privatekey` should raise an error when the passphrase
2669 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002670 """
2671 def cb(ignored):
2672 return "a" * 1025
2673
Alex Gaynor791212d2015-09-05 15:46:08 -04002674 with pytest.raises(ValueError):
2675 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002676
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002677 def test_dump_privatekey_passphrase(self):
2678 """
Alex Chanb00ede22017-01-30 07:24:40 +00002679 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002680 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002681 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002682 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002683 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002684 assert isinstance(pem, binary_type)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002685 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002686 assert isinstance(loadedKey, PKeyType)
2687 assert loadedKey.type() == key.type()
2688 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002689
Alex Chanb00ede22017-01-30 07:24:40 +00002690 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002691 """
Alex Chanb00ede22017-01-30 07:24:40 +00002692 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2693 with a private key encoded in a format, that doesn't support
2694 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002695 """
2696 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002697 with pytest.raises(ValueError):
2698 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002699
Rick Dean5b7b6372009-04-01 11:34:06 -05002700 def test_dump_certificate(self):
2701 """
Alex Chanb00ede22017-01-30 07:24:40 +00002702 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002703 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002704 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002705 cert = load_certificate(FILETYPE_PEM, pemData)
2706 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002707 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002708 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002709 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002710 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002711 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2712 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002713 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002714 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002715 good_text = _runopenssl(
2716 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002717 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002718
Alex Gaynor37726112016-07-04 09:51:32 -04002719 def test_dump_certificate_bad_type(self):
2720 """
Alex Chanb00ede22017-01-30 07:24:40 +00002721 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002722 a bad type.
2723 """
2724 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2725 with pytest.raises(ValueError):
2726 dump_certificate(object(), cert)
2727
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002728 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002729 """
Alex Chanb00ede22017-01-30 07:24:40 +00002730 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002731 """
2732 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002733 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002734 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002735 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002736
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002737 def test_dump_privatekey_asn1(self):
2738 """
Alex Chanb00ede22017-01-30 07:24:40 +00002739 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002740 """
2741 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2742 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2743
Rick Dean5b7b6372009-04-01 11:34:06 -05002744 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002745 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002746 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002747 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002748 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2749 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002750 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002751
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002752 def test_dump_privatekey_text(self):
2753 """
Alex Chanb00ede22017-01-30 07:24:40 +00002754 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002755 """
2756 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2757 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2758
Rick Dean5b7b6372009-04-01 11:34:06 -05002759 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002760 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002761 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002762
Cory Benfield6492f7c2015-10-27 16:57:58 +09002763 def test_dump_publickey_pem(self):
2764 """
Cory Benfield11c10192015-10-27 17:23:03 +09002765 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002766 """
2767 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2768 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002769 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002770
2771 def test_dump_publickey_asn1(self):
2772 """
Cory Benfield11c10192015-10-27 17:23:03 +09002773 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002774 """
2775 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2776 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2777 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2778 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002779 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002780
Cory Benfielde02c7d82015-10-27 17:34:49 +09002781 def test_dump_publickey_invalid_type(self):
2782 """
2783 dump_publickey doesn't support FILETYPE_TEXT.
2784 """
2785 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2786
2787 with pytest.raises(ValueError):
2788 dump_publickey(FILETYPE_TEXT, key)
2789
Rick Dean5b7b6372009-04-01 11:34:06 -05002790 def test_dump_certificate_request(self):
2791 """
Alex Chanb00ede22017-01-30 07:24:40 +00002792 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002793 """
Alex Gaynor31287502015-09-05 16:11:27 -04002794 req = load_certificate_request(
2795 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002796 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002797 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002798 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002799 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002800 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002801 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2802 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002803 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002804 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002805 good_text = _runopenssl(
2806 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002807 assert dumped_text == good_text
2808 with pytest.raises(ValueError):
2809 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002810
Alex Chanb00ede22017-01-30 07:24:40 +00002811 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002812 """
Alex Chanb00ede22017-01-30 07:24:40 +00002813 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002814 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002815 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002816 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002817 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002818
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002819 def cb(writing):
2820 called.append(writing)
2821 return passphrase
2822 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002823 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002824 assert isinstance(pem, binary_type)
2825 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002826 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002827 assert isinstance(loadedKey, PKeyType)
2828 assert loadedKey.type() == key.type()
2829 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002830
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002831 def test_dump_privatekey_passphrase_exception(self):
2832 """
Alex Chanb00ede22017-01-30 07:24:40 +00002833 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002834 by the passphrase callback.
2835 """
2836 def cb(ignored):
2837 raise ArithmeticError
2838
2839 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002840 with pytest.raises(ArithmeticError):
2841 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002842
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002843 def test_dump_privatekey_passphraseCallbackLength(self):
2844 """
Alex Chanb00ede22017-01-30 07:24:40 +00002845 `crypto.dump_privatekey` should raise an error when the passphrase
2846 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002847 """
2848 def cb(ignored):
2849 return "a" * 1025
2850
2851 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002852 with pytest.raises(ValueError):
2853 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002854
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002855 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002856 """
Alex Chanb00ede22017-01-30 07:24:40 +00002857 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2858 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002859 """
2860 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002861 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002862
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002863 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002864 """
Alex Chanb00ede22017-01-30 07:24:40 +00002865 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2866 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002867 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002868 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002869 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002870
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002871 def test_load_pkcs7_data_invalid(self):
2872 """
Alex Chanb00ede22017-01-30 07:24:40 +00002873 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002874 """
Alex Chanb00ede22017-01-30 07:24:40 +00002875 with pytest.raises(Error):
2876 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002877
Alex Gaynor09a386e2016-07-03 09:32:44 -04002878 def test_load_pkcs7_type_invalid(self):
2879 """
Alex Chanb00ede22017-01-30 07:24:40 +00002880 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002881 """
2882 with pytest.raises(ValueError):
2883 load_pkcs7_data(object(), b"foo")
2884
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002885
Alex Chan9e2a9932017-01-25 14:29:19 +00002886class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002887 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002888 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002889 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002890
Alex Chan9e2a9932017-01-25 14:29:19 +00002891 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002892 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002893 If the file type passed to `load_certificate_request` is neither
2894 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002895 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002896 with pytest.raises(ValueError):
2897 load_certificate_request(object(), b"")
2898 with pytest.raises(ValueError):
2899 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002900
Alex Gaynor37726112016-07-04 09:51:32 -04002901 def test_bad_certificate(self):
2902 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002903 If the bytes passed to `load_certificate` are not a valid certificate,
2904 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002905 """
2906 with pytest.raises(Error):
2907 load_certificate(FILETYPE_ASN1, b"lol")
2908
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002909
Alex Chanb00ede22017-01-30 07:24:40 +00002910class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002911 """
Alex Chanb00ede22017-01-30 07:24:40 +00002912 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002913 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002914
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002915 def test_type(self):
2916 """
Alex Chanb00ede22017-01-30 07:24:40 +00002917 `PKCS7` is a type object.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002918 """
Alex Chanb00ede22017-01-30 07:24:40 +00002919 assert isinstance(PKCS7, type)
2920 assert PKCS7Type.__name__ == 'PKCS7'
2921 assert PKCS7 is PKCS7Type
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002922
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002923 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002924 """
Alex Chanb00ede22017-01-30 07:24:40 +00002925 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2926 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002927 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002928 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002929 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002930
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002931 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002932 """
Alex Chanb00ede22017-01-30 07:24:40 +00002933 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2934 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002935 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002936 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002937 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002938
Alex Chanb00ede22017-01-30 07:24:40 +00002939 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002940 """
Alex Chanb00ede22017-01-30 07:24:40 +00002941 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002942 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002943 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002944 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002945 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002946
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002947 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002948 """
Alex Chanb00ede22017-01-30 07:24:40 +00002949 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2950 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002951 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002952 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002953 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002954
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002955 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002956 """
Alex Chanb00ede22017-01-30 07:24:40 +00002957 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002958 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002959 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002960 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002961 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002962
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002963 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002964 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002965 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002966 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002967 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002968 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002969 with pytest.raises(AttributeError):
2970 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002971
2972
Alex Chanb00ede22017-01-30 07:24:40 +00002973class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002974 """
Alex Chanb00ede22017-01-30 07:24:40 +00002975 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002976 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002977
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002978 def signable(self):
2979 """
Alex Chanb00ede22017-01-30 07:24:40 +00002980 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002981 """
2982 return NetscapeSPKI()
2983
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002984 def test_type(self):
2985 """
Alex Chanb00ede22017-01-30 07:24:40 +00002986 `NetscapeSPKI` and `NetscapeSPKIType` refer to the same type object
2987 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002988 """
Alex Chanb00ede22017-01-30 07:24:40 +00002989 assert NetscapeSPKI is NetscapeSPKIType
2990 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002991
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002992 def test_construction(self):
2993 """
Alex Chanb00ede22017-01-30 07:24:40 +00002994 `NetscapeSPKI` returns an instance of `NetscapeSPKIType`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002995 """
2996 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002997 assert isinstance(nspki, NetscapeSPKIType)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002998
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002999 def test_invalid_attribute(self):
3000 """
Alex Chanb00ede22017-01-30 07:24:40 +00003001 Accessing a non-existent attribute of a `NetscapeSPKI` instance
3002 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04003003 """
3004 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00003005 with pytest.raises(AttributeError):
3006 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04003007
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003008 def test_b64_encode(self):
3009 """
Alex Chanb00ede22017-01-30 07:24:40 +00003010 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003011 """
3012 nspki = NetscapeSPKI()
3013 blob = nspki.b64_encode()
Alex Chanb00ede22017-01-30 07:24:40 +00003014 assert isinstance(blob, binary_type)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003015
3016
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003017class TestRevoked(object):
3018 """
Alex Chandeec9342016-12-19 22:00:38 +00003019 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003020 """
3021 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
3022 """
3023 The get_reason method on the Revoked class checks to see if the
3024 extension is NID_crl_reason and should skip it otherwise. This test
3025 loads a CRL with extensions it should ignore.
3026 """
3027 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3028 revoked = crl.get_revoked()
3029 reason = revoked[1].get_reason()
3030 assert reason == b'Unspecified'
3031
3032 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3033 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3034 revoked = crl.get_revoked()
3035 revoked[1].set_reason(None)
3036 reason = revoked[1].get_reason()
3037 assert reason is None
3038
Rick Dean536ba022009-07-24 23:57:27 -05003039 def test_construction(self):
3040 """
Alex Chandeec9342016-12-19 22:00:38 +00003041 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3042 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003043 """
3044 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003045 assert isinstance(revoked, Revoked)
3046 assert type(revoked) == Revoked
3047 assert revoked.get_serial() == b'00'
3048 assert revoked.get_rev_date() is None
3049 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003050
Rick Dean536ba022009-07-24 23:57:27 -05003051 def test_serial(self):
3052 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003053 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003054 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003055 """
3056 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003057 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003058 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003059 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003060 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003061
Alex Gaynore7f51982016-09-11 11:48:14 -04003062 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003063 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003064 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003065
Alex Chandeec9342016-12-19 22:00:38 +00003066 with pytest.raises(ValueError):
3067 revoked.set_serial(b'pqrst')
3068 with pytest.raises(TypeError):
3069 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003070
Rick Dean536ba022009-07-24 23:57:27 -05003071 def test_date(self):
3072 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003073 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003074 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003075 """
3076 revoked = Revoked()
3077 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003078 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003079
Alex Gaynore7f51982016-09-11 11:48:14 -04003080 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003081 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003082 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003083 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003084 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003085
Rick Dean6385faf2009-07-26 00:07:47 -05003086 def test_reason(self):
3087 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003088 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003089 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3090 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003091 """
3092 revoked = Revoked()
3093 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003094 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003095 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003096 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003097 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003098 assert (
3099 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003100 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003101 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003102
3103 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003104 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003105
Alex Chanfb078d82017-04-20 11:16:15 +01003106 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3107 def test_set_reason_wrong_args(self, reason):
3108 """
3109 `Revoked.set_reason` raises `TypeError` if called with an argument
3110 which is neither `None` nor a byte string.
3111 """
3112 revoked = Revoked()
3113 with pytest.raises(TypeError):
3114 revoked.set_reason(reason)
3115
Alex Chandeec9342016-12-19 22:00:38 +00003116 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003117 """
Alex Chandeec9342016-12-19 22:00:38 +00003118 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3119 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003120 """
3121 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003122 with pytest.raises(ValueError):
3123 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003124
3125
Alex Chan7be83a52017-01-24 15:19:29 +00003126class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003127 """
Alex Chan7be83a52017-01-24 15:19:29 +00003128 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003129 """
3130 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3131 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3132
Dan Sully44e767a2016-06-04 18:05:27 -07003133 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3134 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3135 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3136 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3137 intermediate_server_cert = load_certificate(
3138 FILETYPE_PEM, intermediate_server_cert_pem)
3139 intermediate_server_key = load_privatekey(
3140 FILETYPE_PEM, intermediate_server_key_pem)
3141
Rick Dean536ba022009-07-24 23:57:27 -05003142 def test_construction(self):
3143 """
Alex Chan7be83a52017-01-24 15:19:29 +00003144 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003145 that it is empty
3146 """
3147 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003148 assert isinstance(crl, CRL)
3149 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003150
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003151 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003152 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003153 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003154 """
3155 crl = CRL()
3156 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003157 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003158 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003159 revoked.set_serial(b'3ab')
3160 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003161 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003162 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003163
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003164 def test_export_pem(self):
3165 """
3166 If not passed a format, ``CRL.export`` returns a "PEM" format string
3167 representing a serial number, a revoked reason, and certificate issuer
3168 information.
3169 """
Rick Dean536ba022009-07-24 23:57:27 -05003170 # PEM format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003171 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003172 self.cert, self.pkey, days=20, digest=b"sha256"
3173 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003174 crl = x509.load_pem_x509_crl(dumped_crl, backend)
3175 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3176 assert revoked is not None
3177 assert crl.issuer == x509.Name([
3178 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3179 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3180 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3181 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3182 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3183 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003184
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003185 def test_export_der(self):
3186 """
3187 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3188 "DER" format string representing a serial number, a revoked reason, and
3189 certificate issuer information.
3190 """
3191 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003192
3193 # DER format
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003194 dumped_crl = self._get_crl().export(
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003195 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3196 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003197 crl = x509.load_der_x509_crl(dumped_crl, backend)
3198 revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
3199 assert revoked is not None
3200 assert crl.issuer == x509.Name([
3201 x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
3202 x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
3203 x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
3204 x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
3205 x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
3206 ])
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003207
Alex Gaynore466bc92017-07-06 23:43:47 -04003208 # Flaky because we compare the output of running commands which sometimes
3209 # varies by 1 second
3210 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003211 def test_export_text(self):
3212 """
3213 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3214 text format string like the one produced by the openssl command line
3215 tool.
3216 """
3217 crl = self._get_crl()
3218
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003219 dumped_crl = crl.export(
3220 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3221 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003222 text = _runopenssl(
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003223 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER",
3224 b"-nameopt", b""
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003225 )
Rick Dean536ba022009-07-24 23:57:27 -05003226
3227 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003228 dumped_text = crl.export(
3229 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3230 )
Alex Chan7be83a52017-01-24 15:19:29 +00003231 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003232
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003233 def test_export_custom_digest(self):
3234 """
3235 If passed the name of a digest function, ``CRL.export`` uses a
3236 signature algorithm based on that digest function.
3237 """
3238 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003239 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003240 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003241 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003242
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003243 def test_export_md5_digest(self):
3244 """
3245 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3246 not emit a deprecation warning.
3247 """
3248 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003249 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003250 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003251 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003252 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3253 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003254 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003255
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003256 def test_export_default_digest(self):
3257 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003258 If not passed the name of a digest function, ``CRL.export`` raises a
3259 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003260 """
3261 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003262 with pytest.raises(TypeError):
3263 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003264
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003265 def test_export_invalid(self):
3266 """
Alex Chan7be83a52017-01-24 15:19:29 +00003267 If `CRL.export` is used with an uninitialized `X509` instance,
3268 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003269 """
3270 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003271 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003272 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003273
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003274 def test_add_revoked_keyword(self):
3275 """
Alex Chan7be83a52017-01-24 15:19:29 +00003276 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003277 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003278 """
3279 crl = CRL()
3280 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003281 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003282 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003283 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003284 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003285
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003286 def test_export_wrong_args(self):
3287 """
Alex Chan7be83a52017-01-24 15:19:29 +00003288 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003289 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003290 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003291 """
3292 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003293 with pytest.raises(TypeError):
3294 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3295 with pytest.raises(TypeError):
3296 crl.export(self.cert, None, FILETYPE_PEM, 10)
3297 with pytest.raises(TypeError):
3298 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003299 with pytest.raises(TypeError):
3300 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003301
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003302 def test_export_unknown_filetype(self):
3303 """
Alex Chan7be83a52017-01-24 15:19:29 +00003304 Calling `OpenSSL.CRL.export` with a file type other than
3305 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3306 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003307 """
3308 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003309 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003310 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003311
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003312 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003313 """
Alex Chan7be83a52017-01-24 15:19:29 +00003314 Calling `OpenSSL.CRL.export` with an unsupported digest results
3315 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003316 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003317 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003318 with pytest.raises(ValueError):
3319 crl.export(
3320 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003321
Rick Dean536ba022009-07-24 23:57:27 -05003322 def test_get_revoked(self):
3323 """
Alex Chan7be83a52017-01-24 15:19:29 +00003324 Use python to create a simple CRL with two revocations. Get back the
3325 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003326 """
3327 crl = CRL()
3328
3329 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003330 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003331 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003332 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003333 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003334 revoked.set_serial(b'100')
3335 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003336 crl.add_revoked(revoked)
3337
3338 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003339 assert len(revs) == 2
3340 assert type(revs[0]) == Revoked
3341 assert type(revs[1]) == Revoked
3342 assert revs[0].get_serial() == b'03AB'
3343 assert revs[1].get_serial() == b'0100'
3344 assert revs[0].get_rev_date() == now
3345 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003346
Rick Dean536ba022009-07-24 23:57:27 -05003347 def test_load_crl(self):
3348 """
Alex Chan7be83a52017-01-24 15:19:29 +00003349 Load a known CRL and inspect its revocations. Both EM and DER formats
3350 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003351 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003352 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003353 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003354 assert len(revs) == 2
3355 assert revs[0].get_serial() == b'03AB'
3356 assert revs[0].get_reason() is None
3357 assert revs[1].get_serial() == b'0100'
3358 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003359
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003360 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003361 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003362 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003363 assert len(revs) == 2
3364 assert revs[0].get_serial() == b'03AB'
3365 assert revs[0].get_reason() is None
3366 assert revs[1].get_serial() == b'0100'
3367 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003368
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003369 def test_load_crl_bad_filetype(self):
3370 """
Alex Chan7be83a52017-01-24 15:19:29 +00003371 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3372 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003373 """
Alex Chan7be83a52017-01-24 15:19:29 +00003374 with pytest.raises(ValueError):
3375 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003376
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003377 def test_load_crl_bad_data(self):
3378 """
Alex Chan7be83a52017-01-24 15:19:29 +00003379 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3380 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003381 """
Alex Chan7be83a52017-01-24 15:19:29 +00003382 with pytest.raises(Error):
3383 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003384
Dan Sully44e767a2016-06-04 18:05:27 -07003385 def test_get_issuer(self):
3386 """
Alex Chan7be83a52017-01-24 15:19:29 +00003387 Load a known CRL and assert its issuer's common name is what we expect
3388 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003389 """
3390 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003391 assert isinstance(crl.get_issuer(), X509Name)
3392 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003393
Dominic Chenf05b2122015-10-13 16:32:35 +00003394 def test_dump_crl(self):
3395 """
3396 The dumped CRL matches the original input.
3397 """
3398 crl = load_crl(FILETYPE_PEM, crlData)
3399 buf = dump_crl(FILETYPE_PEM, crl)
3400 assert buf == crlData
3401
Dan Sully44e767a2016-06-04 18:05:27 -07003402 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3403 """
3404 Create a CRL.
3405
3406 :param list[X509] certs: A list of certificates to revoke.
3407 :rtype: CRL
3408 """
3409 crl = CRL()
3410 for cert in certs:
3411 revoked = Revoked()
3412 # FIXME: This string splicing is an unfortunate implementation
3413 # detail that has been reported in
3414 # https://github.com/pyca/pyopenssl/issues/258
3415 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3416 revoked.set_serial(serial)
3417 revoked.set_reason(b'unspecified')
3418 revoked.set_rev_date(b'20140601000000Z')
3419 crl.add_revoked(revoked)
3420 crl.set_version(1)
3421 crl.set_lastUpdate(b'20140601000000Z')
3422 crl.set_nextUpdate(b'20180601000000Z')
3423 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3424 return crl
3425
3426 def test_verify_with_revoked(self):
3427 """
Alex Chan7be83a52017-01-24 15:19:29 +00003428 `verify_certificate` raises error when an intermediate certificate is
3429 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003430 """
3431 store = X509Store()
3432 store.add_cert(self.root_cert)
3433 store.add_cert(self.intermediate_cert)
3434 root_crl = self._make_test_crl(
3435 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3436 intermediate_crl = self._make_test_crl(
3437 self.intermediate_cert, self.intermediate_key, certs=[])
3438 store.add_crl(root_crl)
3439 store.add_crl(intermediate_crl)
3440 store.set_flags(
3441 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3442 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003443 with pytest.raises(X509StoreContextError) as err:
3444 store_ctx.verify_certificate()
3445 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003446
3447 def test_verify_with_missing_crl(self):
3448 """
Alex Chan7be83a52017-01-24 15:19:29 +00003449 `verify_certificate` raises error when an intermediate certificate's
3450 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003451 """
3452 store = X509Store()
3453 store.add_cert(self.root_cert)
3454 store.add_cert(self.intermediate_cert)
3455 root_crl = self._make_test_crl(
3456 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3457 store.add_crl(root_crl)
3458 store.set_flags(
3459 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3460 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003461 with pytest.raises(X509StoreContextError) as err:
3462 store_ctx.verify_certificate()
3463 assert err.value.args[0][2] == 'unable to get certificate CRL'
3464 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003465
Paul Kehrer41c10242017-06-29 18:24:17 -05003466 def test_convert_from_cryptography(self):
3467 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3468 crl = CRL.from_cryptography(crypto_crl)
3469 assert isinstance(crl, CRL)
3470
3471 def test_convert_from_cryptography_unsupported_type(self):
3472 with pytest.raises(TypeError):
3473 CRL.from_cryptography(object())
3474
3475 def test_convert_to_cryptography_key(self):
3476 crl = load_crl(FILETYPE_PEM, crlData)
3477 crypto_crl = crl.to_cryptography()
3478 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3479
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003480
Alex Chan7be83a52017-01-24 15:19:29 +00003481class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003482 """
Alex Chan7be83a52017-01-24 15:19:29 +00003483 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003484 """
3485 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3486 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003487 intermediate_server_cert = load_certificate(
3488 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003489
3490 def test_valid(self):
3491 """
Alex Chan7be83a52017-01-24 15:19:29 +00003492 `verify_certificate` returns ``None`` when called with a certificate
3493 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003494 """
3495 store = X509Store()
3496 store.add_cert(self.root_cert)
3497 store.add_cert(self.intermediate_cert)
3498 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003499 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003500
3501 def test_reuse(self):
3502 """
Alex Chan7be83a52017-01-24 15:19:29 +00003503 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003504 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003505 """
3506 store = X509Store()
3507 store.add_cert(self.root_cert)
3508 store.add_cert(self.intermediate_cert)
3509 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003510 assert store_ctx.verify_certificate() is None
3511 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003512
3513 def test_trusted_self_signed(self):
3514 """
Alex Chan7be83a52017-01-24 15:19:29 +00003515 `verify_certificate` returns ``None`` when called with a self-signed
3516 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003517 """
3518 store = X509Store()
3519 store.add_cert(self.root_cert)
3520 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003521 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003522
3523 def test_untrusted_self_signed(self):
3524 """
Alex Chan7be83a52017-01-24 15:19:29 +00003525 `verify_certificate` raises error when a self-signed certificate is
3526 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003527 """
3528 store = X509Store()
3529 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003530 with pytest.raises(X509StoreContextError) as exc:
3531 store_ctx.verify_certificate()
3532
3533 assert exc.value.args[0][2] == 'self signed certificate'
3534 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003535
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003536 def test_invalid_chain_no_root(self):
3537 """
Alex Chan7be83a52017-01-24 15:19:29 +00003538 `verify_certificate` raises error when a root certificate is missing
3539 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003540 """
3541 store = X509Store()
3542 store.add_cert(self.intermediate_cert)
3543 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003544
3545 with pytest.raises(X509StoreContextError) as exc:
3546 store_ctx.verify_certificate()
3547
3548 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3549 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003550
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003551 def test_invalid_chain_no_intermediate(self):
3552 """
Alex Chan7be83a52017-01-24 15:19:29 +00003553 `verify_certificate` raises error when an intermediate certificate is
3554 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003555 """
3556 store = X509Store()
3557 store.add_cert(self.root_cert)
3558 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003559
Alex Gaynor85b49702015-09-05 16:30:59 -04003560 with pytest.raises(X509StoreContextError) as exc:
3561 store_ctx.verify_certificate()
3562
3563 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3564 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003565
Stephen Holsapple46a09252015-02-12 14:45:43 -08003566 def test_modification_pre_verify(self):
3567 """
Alex Chan7be83a52017-01-24 15:19:29 +00003568 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003569 instantiation.
3570 """
3571 store_bad = X509Store()
3572 store_bad.add_cert(self.intermediate_cert)
3573 store_good = X509Store()
3574 store_good.add_cert(self.root_cert)
3575 store_good.add_cert(self.intermediate_cert)
3576 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003577
3578 with pytest.raises(X509StoreContextError) as exc:
3579 store_ctx.verify_certificate()
3580
3581 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3582 assert exc.value.certificate.get_subject().CN == 'intermediate'
3583
Stephen Holsapple46a09252015-02-12 14:45:43 -08003584 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003585 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003586
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003587 def test_verify_with_time(self):
3588 """
3589 `verify_certificate` raises error when the verification time is
3590 set at notAfter.
3591 """
3592 store = X509Store()
3593 store.add_cert(self.root_cert)
3594 store.add_cert(self.intermediate_cert)
3595
3596 expire_time = self.intermediate_server_cert.get_notAfter()
3597 expire_datetime = datetime.strptime(
3598 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3599 )
3600 store.set_time(expire_datetime)
3601
3602 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3603 with pytest.raises(X509StoreContextError) as exc:
3604 store_ctx.verify_certificate()
3605
3606 assert exc.value.args[0][2] == 'certificate has expired'
3607
Stephen Holsapple46a09252015-02-12 14:45:43 -08003608
Alex Chan7be83a52017-01-24 15:19:29 +00003609class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003610 """
Alex Chan7be83a52017-01-24 15:19:29 +00003611 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003612 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003613
James Yonan7c2e5d32010-02-27 05:45:50 -07003614 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003615 """
Alex Chan7be83a52017-01-24 15:19:29 +00003616 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003617 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003618 content = (
3619 b"It was a bright cold day in April, and the clocks were striking "
3620 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3621 b"effort to escape the vile wind, slipped quickly through the "
3622 b"glass doors of Victory Mansions, though not quickly enough to "
3623 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003624
3625 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003626 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003627 # verify the content with this cert
3628 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3629 # certificate unrelated to priv_key, used to trigger an error
3630 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003631
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003632 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003633 sig = sign(priv_key, content, digest)
3634
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003635 # Verify the signature of content, will throw an exception if
3636 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003637 verify(good_cert, sig, content, digest)
3638
3639 # This should fail because the certificate doesn't match the
3640 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003641 with pytest.raises(Error):
3642 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003643
3644 # This should fail because we've "tainted" the content after
3645 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003646 with pytest.raises(Error):
3647 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003648
3649 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003650 with pytest.raises(ValueError):
3651 sign(priv_key, content, "strange-digest")
3652 with pytest.raises(ValueError):
3653 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003654
Abraham Martinc5484ba2015-03-25 15:33:05 +00003655 def test_sign_verify_with_text(self):
3656 """
Alex Chan7be83a52017-01-24 15:19:29 +00003657 `sign` generates a cryptographic signature which
3658 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003659 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003660 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003661 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003662 b"It was a bright cold day in April, and the clocks were striking "
3663 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3664 b"effort to escape the vile wind, slipped quickly through the "
3665 b"glass doors of Victory Mansions, though not quickly enough to "
3666 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003667 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003668
3669 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3670 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3671 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003672 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003673 simplefilter("always")
3674 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003675 assert (
3676 "{0} for data is no longer accepted, use bytes".format(
3677 WARNING_TYPE_EXPECTED
3678 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003679
Alex Chan7be83a52017-01-24 15:19:29 +00003680 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003681 simplefilter("always")
3682 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003683 assert (
3684 "{0} for data is no longer accepted, use bytes".format(
3685 WARNING_TYPE_EXPECTED
3686 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003687
Paul Kehrer59d26252017-07-20 10:45:54 +02003688 def test_sign_verify_ecdsa(self):
3689 """
3690 `sign` generates a cryptographic signature which `verify` can check.
3691 ECDSA Signatures in the X9.62 format may have variable length,
3692 different from the length of the private key.
3693 """
3694 content = (
3695 b"It was a bright cold day in April, and the clocks were striking "
3696 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3697 b"effort to escape the vile wind, slipped quickly through the "
3698 b"glass doors of Victory Mansions, though not quickly enough to "
3699 b"prevent a swirl of gritty dust from entering along with him."
3700 ).decode("ascii")
3701 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3702 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3703 sig = sign(priv_key, content, "sha1")
3704 verify(cert, sig, content, "sha1")
3705
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003706 def test_sign_nulls(self):
3707 """
Alex Chan7be83a52017-01-24 15:19:29 +00003708 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003709 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003710 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003711 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3712 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3713 sig = sign(priv_key, content, "sha1")
3714 verify(good_cert, sig, content, "sha1")
3715
Colleen Murphye09399b2016-03-01 17:40:49 -08003716 def test_sign_with_large_key(self):
3717 """
Alex Chan7be83a52017-01-24 15:19:29 +00003718 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003719 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003720 content = (
3721 b"It was a bright cold day in April, and the clocks were striking "
3722 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3723 b"effort to escape the vile wind, slipped quickly through the "
3724 b"glass doors of Victory Mansions, though not quickly enough to "
3725 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003726
3727 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3728 sign(priv_key, content, "sha1")
3729
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003730
Alex Chan63ef9bc2016-12-19 12:02:06 +00003731class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003732 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003733 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3734 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003735 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003736
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003737 def test_set(self):
3738 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003739 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003740 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003741 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003742
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003743 def test_a_curve(self):
3744 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003745 `get_elliptic_curve` can be used to retrieve a particular supported
3746 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003747 """
3748 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003749 curve = next(iter(curves))
3750 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003751
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003752 def test_not_a_curve(self):
3753 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003754 `get_elliptic_curve` raises `ValueError` if called with a name which
3755 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003756 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003757 with pytest.raises(ValueError):
3758 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003759
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003760 def test_repr(self):
3761 """
3762 The string representation of a curve object includes simply states the
3763 object is a curve and what its name is.
3764 """
3765 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003766 curve = next(iter(curves))
3767 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003768
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003769 def test_to_EC_KEY(self):
3770 """
3771 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003772 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003773 """
3774 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003775 curve = next(iter(curves))
3776 # It's not easy to assert anything about this object. However, see
3777 # leakcheck/crypto.py for a test that demonstrates it at least does
3778 # not leak memory.
3779 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003780
3781
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003782class EllipticCurveFactory(object):
3783 """
3784 A helper to get the names of two curves.
3785 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003786
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003787 def __init__(self):
3788 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003789 self.curve_name = next(curves).name
3790 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003791
3792
Alex Chan63ef9bc2016-12-19 12:02:06 +00003793class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003794 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003795 Tests `_EllipticCurve`'s implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003796 """
3797 curve_factory = EllipticCurveFactory()
3798
3799 if curve_factory.curve_name is None:
3800 skip = "There are no curves available there can be no curve objects."
3801
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003802 def anInstance(self):
3803 """
3804 Get the curve object for an arbitrary curve supported by the system.
3805 """
3806 return get_elliptic_curve(self.curve_factory.curve_name)
3807
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003808 def anotherInstance(self):
3809 """
3810 Get the curve object for an arbitrary curve supported by the system -
3811 but not the one returned by C{anInstance}.
3812 """
3813 return get_elliptic_curve(self.curve_factory.another_curve_name)
3814
3815
Alex Chan63ef9bc2016-12-19 12:02:06 +00003816class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003817 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003818 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3819 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003820 """
3821 curve_factory = EllipticCurveFactory()
3822
3823 if curve_factory.curve_name is None:
3824 skip = "There are no curves available there can be no curve objects."
3825
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003826 def test_contains(self):
3827 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003828 The ``in`` operator reports that a `set` containing a curve does
3829 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003830 """
3831 curve = get_elliptic_curve(self.curve_factory.curve_name)
3832 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003833 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003834
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003835 def test_does_not_contain(self):
3836 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003837 The ``in`` operator reports that a `set` not containing a curve
3838 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003839 """
3840 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003841 curves = set([
3842 get_elliptic_curve(self.curve_factory.another_curve_name)
3843 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003844 assert curve not in curves