blob: 2e102c9638eedde4b5086b96b2f75ad921154ba8 [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
11import os
12import re
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -040013from subprocess import PIPE, Popen
Rick Dean47262da2009-07-08 16:17:17 -050014from datetime import datetime, timedelta
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -050015
Alex Gaynor791212d2015-09-05 15:46:08 -040016import pytest
17
Alex Gaynore7f51982016-09-11 11:48:14 -040018from six import binary_type
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050019
Alex Gaynor9939ba12017-06-25 16:28:24 -040020from cryptography import x509
Paul Kehrer72d968b2016-07-29 15:31:04 +080021from cryptography.hazmat.backends.openssl.backend import backend
22from cryptography.hazmat.primitives import serialization
23from cryptography.hazmat.primitives.asymmetric import rsa
24
Alex Gaynore466bc92017-07-06 23:43:47 -040025import flaky
26
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -050027from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
Jean-Paul Calderone78381d22008-03-06 23:35:22 -050028from OpenSSL.crypto import X509, X509Type, X509Name, X509NameType
Alex Gaynor31287502015-09-05 16:11:27 -040029from OpenSSL.crypto import (
Dan Sully44e767a2016-06-04 18:05:27 -070030 X509Store,
31 X509StoreFlags,
32 X509StoreType,
33 X509StoreContext,
34 X509StoreContextError
Alex Gaynor31287502015-09-05 16:11:27 -040035)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070036from OpenSSL.crypto import X509Req, X509ReqType
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -050037from OpenSSL.crypto import X509Extension, X509ExtensionType
Rick Dean5b7b6372009-04-01 11:34:06 -050038from OpenSSL.crypto import load_certificate, load_privatekey
Cory Benfield6492f7c2015-10-27 16:57:58 +090039from OpenSSL.crypto import load_publickey, dump_publickey
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -040040from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
Jean-Paul Calderone71919862009-04-01 13:01:19 -040041from OpenSSL.crypto import dump_certificate, load_certificate_request
42from OpenSSL.crypto import dump_certificate_request, dump_privatekey
Alex Chanb00ede22017-01-30 07:24:40 +000043from OpenSSL.crypto import PKCS7, PKCS7Type, load_pkcs7_data
Jean-Paul Calderone9178ee62010-01-25 17:55:30 -050044from OpenSSL.crypto import PKCS12, PKCS12Type, load_pkcs12
Dominic Chenf05b2122015-10-13 16:32:35 +000045from OpenSSL.crypto import CRL, Revoked, dump_crl, load_crl
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -040046from OpenSSL.crypto import NetscapeSPKI, NetscapeSPKIType
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040047from OpenSSL.crypto import (
48 sign, verify, get_elliptic_curve, get_elliptic_curves)
Alex Chan63ef9bc2016-12-19 12:02:06 +000049from OpenSSL._util import native
Hynek Schlawackf0e66852015-10-16 20:18:38 +020050
Alex Chanb00ede22017-01-30 07:24:40 +000051from .util import EqualityTestsMixin, is_consistent_type, WARNING_TYPE_EXPECTED
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040052
Alex Gaynoraceb3e22015-09-05 12:00:22 -040053
Jean-Paul Calderone9da338d2011-05-04 11:40:54 -040054def normalize_privatekey_pem(pem):
55 return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
56
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040057
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050058GOOD_CIPHER = "blowfish"
59BAD_CIPHER = "zippers"
60
Anthony Alba2ce737f2015-12-04 11:04:56 +080061GOOD_DIGEST = "SHA1"
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050062BAD_DIGEST = "monkeys"
63
Paul Kehrera40898b2017-06-11 16:30:58 -100064old_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
Rick Dean94e46fd2009-07-18 14:51:24 -050065MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
66BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
67ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
68NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
69MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
70ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
71urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
722xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
731dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
74FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
75VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
76BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
77b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
78AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
79hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
80w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
81-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -040082"""
Rick Dean94e46fd2009-07-18 14:51:24 -050083
Paul Kehrera40898b2017-06-11 16:30:58 -100084root_cert_pem = b"""-----BEGIN CERTIFICATE-----
85MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
86BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
87ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
88WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
89BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
90bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
91bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
92LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
93onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
94LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
95yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
96aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
97Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
98R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
99gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
100lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
101-----END CERTIFICATE-----
102"""
103
Alex Gaynore7f51982016-09-11 11:48:14 -0400104root_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500105MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
106jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
1073claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
108AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
109yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
1106JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
111BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
112u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
113PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
114I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
115ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
1166AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
117cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
118-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400119"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500120
Alex Gaynore7f51982016-09-11 11:48:14 -0400121intermediate_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700122MIICVzCCAcCgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQENBQAw
123WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
124DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTQw
125ODI4MDIwNDA4WhcNMjQwODI1MDIwNDA4WjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
126dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
127MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIGfMA0GCSqGSIb3DQEB
128AQUAA4GNADCBiQKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmK
129FGIbljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT
13021H2qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwID
131AQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDQUAA4GBAPIWSkLX
132QRMApOjjyC+tMxumT5e2pMqChHmxobQK4NMdrf2VCx+cRT6EmY8sK3/Xl/X8UBQ+
1339n5zXb1ZwhW/sTWgUvmOceJ4/XVs9FkdWOOn1J0XBch9ZIiFe/s5ASIgG7fUdcUF
1349mAWS6FK2ca3xIh5kIupCXOFa0dPvlw/YUFT
135-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400136"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700137
Alex Gaynore7f51982016-09-11 11:48:14 -0400138intermediate_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700139MIICWwIBAAKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmKFGIb
140ljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT21H2
141qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwIDAQAB
142AoGAfSZVV80pSeOKHTYfbGdNY/jHdU9eFUa/33YWriXU+77EhpIItJjkRRgivIfo
143rhFJpBSGmDLblaqepm8emsXMeH4+2QzOYIf0QGGP6E6scjTt1PLqdqKfVJ1a2REN
144147cujNcmFJb/5VQHHMpaPTgttEjlzuww4+BCDPsVRABWrkCQQD3loH36nLoQTtf
145+kQq0T6Bs9/UWkTAGo0ND81ALj0F8Ie1oeZg6RNT96RxZ3aVuFTESTv6/TbjWywO
146wdzlmV1vAkEA38rTJ6PTwaJlw5OttdDzAXGPB9tDmzh9oSi7cHwQQXizYd8MBYx4
147sjHUKD3dCQnb1dxJFhd3BT5HsnkRMbVZXQJAbXduH17ZTzcIOXc9jHDXYiFVZV5D
14852vV0WCbLzVCZc3jMrtSUKa8lPN5EWrdU3UchWybyG0MR5mX8S5lrF4SoQJAIyUD
149DBKaSqpqONCUUx1BTFS9FYrFjzbL4+c1qHCTTPTblt8kUCrDOZjBrKAqeiTmNSum
150/qUot9YUBF8m6BuGsQJATHHmdFy/fG1VLkyBp49CAa8tN3Z5r/CgTznI4DfMTf4C
151NbRHn2UmYlwQBa+L5lg9phewNe8aEwpPyPLoV85U8Q==
152-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400153"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700154
Alex Gaynore7f51982016-09-11 11:48:14 -0400155server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000156MIICJDCCAY2gAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
157BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
158VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMTA1
159N1oXDTM3MDYwNzAwMTA1N1owGDEWMBQGA1UEAwwNbG92ZWx5IHNlcnZlcjCBnzAN
160BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvqb4brndXS2kEL84qXbZXE6LYK+UrhNi
16170sdIM/24NVN7tXkPlOXqrMWhFHHml+aeSpPkH5b1vKnY1TcULmEubnNICtvjmZ5
162SGMQn+J+RmBs1SMd0EgY/0wBBQdlrlYp2QYgm8YC+zxTNSqWvhMFZAgHbj6Un5SS
163T8JGBqytjB0CAwEAAaM2MDQwHQYDVR0OBBYEFINVdy1eIfFJDAkk51QJEo3IfgSu
164MBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4GBAGki1K6WgHHJ
165qC6aY2EowjaWOXLO6jUZIhGk7BA7vMRfNug429AOZ4m5F6OQhzmJmlw67Jyu2FeI
166h0VtBuQoHPtjqZXF59oX6hMMmGLMs9pV0UA3fJs5MYA4/V5ZcQy0Ie0QoJNejLzE
1676V1Qz1rRTYLUyEcpI7ZCmBg2KQQI8YZI
Rick Dean94e46fd2009-07-18 14:51:24 -0500168-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400169"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500170
Alex Gaynore7f51982016-09-11 11:48:14 -0400171server_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500172MIICWwIBAAKBgQC+pvhuud1dLaQQvzipdtlcTotgr5SuE2LvSx0gz/bg1U3u1eQ+
173U5eqsxaEUceaX5p5Kk+QflvW8qdjVNxQuYS5uc0gK2+OZnlIYxCf4n5GYGzVIx3Q
174SBj/TAEFB2WuVinZBiCbxgL7PFM1Kpa+EwVkCAduPpSflJJPwkYGrK2MHQIDAQAB
175AoGAbwuZ0AR6JveahBaczjfnSpiFHf+mve2UxoQdpyr6ROJ4zg/PLW5K/KXrC48G
176j6f3tXMrfKHcpEoZrQWUfYBRCUsGD5DCazEhD8zlxEHahIsqpwA0WWssJA2VOLEN
177j6DuV2pCFbw67rfTBkTSo32ahfXxEKev5KswZk0JIzH3ooECQQDgzS9AI89h0gs8
178Dt+1m11Rzqo3vZML7ZIyGApUzVan+a7hbc33nbGRkAXjHaUBJO31it/H6dTO+uwX
179msWwNG5ZAkEA2RyFKs5xR5USTFaKLWCgpH/ydV96KPOpBND7TKQx62snDenFNNbn
180FwwOhpahld+vqhYk+pfuWWUpQciE+Bu7ZQJASjfT4sQv4qbbKK/scePicnDdx9th
1814e1EeB9xwb+tXXXUo/6Bor/AcUNwfiQ6Zt9PZOK9sR3lMZSsP7rMi7kzuQJABie6
1821sXXjFH7nNJvRG4S39cIxq8YRYTy68II/dlB2QzGpKxV/POCxbJ/zu0CU79tuYK7
183NaeNCFfH3aeTrX0LyQJAMBWjWmeKM2G2sCExheeQK0ROnaBC8itCECD4Jsve4nqf
184r50+LF74iLXFwqysVCebPKMOpDWp/qQ1BbJQIPs7/A==
185-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400186""")
Rick Dean94e46fd2009-07-18 14:51:24 -0500187
Alex Gaynore7f51982016-09-11 11:48:14 -0400188intermediate_server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700189MIICWDCCAcGgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQENBQAw
190ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
191CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
192biBEaWVnbzAeFw0xNDA4MjgwMjEwNDhaFw0yNDA4MjUwMjEwNDhaMG4xHTAbBgNV
193BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
194CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
195biBEaWVnbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqpJZygd+w1faLOr1
196iOAmbBhx5SZWcTCZ/ZjHQTJM7GuPT624QkqsixFghRKdDROwpwnAP7gMRukLqiy4
197+kRuGT5OfyGggL95i2xqA+zehjj08lSTlvGHpePJgCyTavIy5+Ljsj4DKnKyuhxm
198biXTRrH83NDgixVkObTEmh/OVK0CAwEAATANBgkqhkiG9w0BAQ0FAAOBgQBa0Npw
199UkzjaYEo1OUE1sTI6Mm4riTIHMak4/nswKh9hYup//WVOlr/RBSBtZ7Q/BwbjobN
2003bfAtV7eSAqBsfxYXyof7G1ALANQERkq3+oyLP1iVt08W1WOUlIMPhdCF/QuCwy6
201x9MJLhUCGLJPM+O2rAPWVD9wCmvq10ALsiH3yA==
202-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400203"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700204
Alex Gaynore7f51982016-09-11 11:48:14 -0400205intermediate_server_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700206MIICXAIBAAKBgQCqklnKB37DV9os6vWI4CZsGHHlJlZxMJn9mMdBMkzsa49PrbhC
207SqyLEWCFEp0NE7CnCcA/uAxG6QuqLLj6RG4ZPk5/IaCAv3mLbGoD7N6GOPTyVJOW
2088Yel48mALJNq8jLn4uOyPgMqcrK6HGZuJdNGsfzc0OCLFWQ5tMSaH85UrQIDAQAB
209AoGAIQ594j5zna3/9WaPsTgnmhlesVctt4AAx/n827DA4ayyuHFlXUuVhtoWR5Pk
2105ezj9mtYW8DyeCegABnsu2vZni/CdvU6uiS1Hv6qM1GyYDm9KWgovIP9rQCDSGaz
211d57IWVGxx7ODFkm3gN5nxnSBOFVHytuW1J7FBRnEsehRroECQQDXHFOv82JuXDcz
212z3+4c74IEURdOHcbycxlppmK9kFqm5lsUdydnnGW+mvwDk0APOB7Wg7vyFyr393e
213dpmBDCzNAkEAyv6tVbTKUYhSjW+QhabJo896/EqQEYUmtMXxk4cQnKeR/Ao84Rkf
214EqD5IykMUfUI0jJU4DGX+gWZ10a7kNbHYQJAVFCuHNFxS4Cpwo0aqtnzKoZaHY/8
215X9ABZfafSHCtw3Op92M+7ikkrOELXdS9KdKyyqbKJAKNEHF3LbOfB44WIQJAA2N4
2169UNNVUsXRbElEnYUS529CdUczo4QdVgQjkvk5RiPAUwSdBd9Q0xYnFOlFwEmIowg
217ipWJWe0aAlP18ZcEQQJBAL+5lekZ/GUdQoZ4HAsN5a9syrzavJ9VvU1KOOPorPZK
218nMRZbbQgP+aSB7yl6K0gaLaZ8XaK0pjxNBh6ASqg9f4=
219-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400220"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700221
Alex Gaynore7f51982016-09-11 11:48:14 -0400222client_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000223MIICIjCCAYugAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
224BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
225VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMDQx
226M1oXDTM3MDYwNzAwMDQxM1owFjEUMBIGA1UEAwwLdWdseSBjbGllbnQwgZ8wDQYJ
227KoZIhvcNAQEBBQADgY0AMIGJAoGBAMBmH9JG02bme0xPipvpjMSlOugyWrauf4at
228EdGJn7GQLD8IY2Fu0+Kvv9DFpSPboFKZCsfDVsYoRs+xaJbtt1dJ6ymX7EqKS7gb
2298q+eeZZ14keqyJd5Rm2q6swQtw9ADD3E8cS6GqpQm+8SgxOycISoYz7sO1ugJFqN
230jId+W4BFAgMBAAGjNjA0MB0GA1UdDgQWBBSDVXctXiHxSQwJJOdUCRKNyH4ErjAT
231BgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQAMqcHyweaCOZNN
232dWQQOsBKQlL5wqVVZwucHPWqobjxpULKy9gS2ha2zbgkXcB/BnBOSwe0Fm+MJV0T
233NbnTghcGJNpEH7VKn4xSLvIGZmnZZWgxeIB16z4GhpkK2fShBJ+6GKZjsgjT0lSH
234JRgjHbWutZfZvbSHXr9n7PIphG1Ojg==
Rick Dean94e46fd2009-07-18 14:51:24 -0500235-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400236"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500237
Alex Gaynore7f51982016-09-11 11:48:14 -0400238client_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500239MIICXgIBAAKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2rn+GrRHRiZ+xkCw/CGNh
240btPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xKiku4G/KvnnmWdeJHqsiX
241eUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7DtboCRajYyHfluARQIDAQAB
242AoGATkZ+NceY5Glqyl4mD06SdcKfV65814vg2EL7V9t8+/mi9rYL8KztSXGlQWPX
243zuHgtRoMl78yQ4ZJYOBVo+nsx8KZNRCEBlE19bamSbQLCeQMenWnpeYyQUZ908gF
244h6L9qsFVJepgA9RDgAjyDoS5CaWCdCCPCH2lDkdcqC54SVUCQQDseuduc4wi8h4t
245V8AahUn9fn9gYfhoNuM0gdguTA0nPLVWz4hy1yJiWYQe0H7NLNNTmCKiLQaJpAbb
246TC6vE8C7AkEA0Ee8CMJUc20BnGEmxwgWcVuqFWaKCo8jTH1X38FlATUsyR3krjW2
247dL3yDD9NwHxsYP7nTKp/U8MV7U9IBn4y/wJBAJl7H0/BcLeRmuJk7IqJ7b635iYB
248D/9beFUw3MUXmQXZUfyYz39xf6CDZsu1GEdEC5haykeln3Of4M9d/4Kj+FcCQQCY
249si6xwT7GzMDkk/ko684AV3KPc/h6G0yGtFIrMg7J3uExpR/VdH2KgwMkZXisSMvw
250JJEQjOMCVsEJlRk54WWjAkEAzoZNH6UhDdBK5F38rVt/y4SEHgbSfJHIAmPS32Kq
251f6GGcfNpip0Uk7q7udTKuX7Q/buZi/C4YW7u3VKAquv9NA==
252-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400253""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400254
Alex Gaynore7f51982016-09-11 11:48:14 -0400255cleartextCertificatePEM = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000256MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400257BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
Paul Kehrera40898b2017-06-11 16:30:58 -1000258ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
259WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
260BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
261bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
262bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
263LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
264onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
265LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
266yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
267aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
268Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
269R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
270gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
271lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400272-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400273"""
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400274
Alex Gaynore7f51982016-09-11 11:48:14 -0400275cleartextPrivateKeyPEM = normalize_privatekey_pem(b"""\
Jean-Paul Calderoned50d2042011-05-04 17:00:49 -0400276-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400277MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
278jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
2793claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
280AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
281yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
2826JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
283BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
284u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
285PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
286I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
287ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
2886AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
289cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
290-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400291""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400292
Alex Gaynore7f51982016-09-11 11:48:14 -0400293cleartextCertificateRequestPEM = b"""-----BEGIN CERTIFICATE REQUEST-----
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -0400294MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
295EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
296ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
297BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
298E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
299xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
300gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
301Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
302oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
303-----END CERTIFICATE REQUEST-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400304"""
Rick Dean5b7b6372009-04-01 11:34:06 -0500305
Alex Gaynore7f51982016-09-11 11:48:14 -0400306encryptedPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400307Proc-Type: 4,ENCRYPTED
308DEK-Info: DES-EDE3-CBC,9573604A18579E9E
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400309
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400310SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
311a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
3128+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
313mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
314+00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
315fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
316tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
317rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
318gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
319o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
3207SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
321MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
32211n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
323-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400324"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400325
Alex Gaynore7f51982016-09-11 11:48:14 -0400326encryptedPrivateKeyPEMPassphrase = b"foobar"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400327
Cory Benfield6492f7c2015-10-27 16:57:58 +0900328
Alex Gaynore7f51982016-09-11 11:48:14 -0400329cleartextPublicKeyPEM = b"""-----BEGIN PUBLIC KEY-----
Cory Benfield6492f7c2015-10-27 16:57:58 +0900330MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxszlc+b71LvlLS0ypt/l
331gT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZOtPclNY823Q4pErMTSWC
33290qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLjBuUIkQzEKEFV+8taiRV+
333ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPrUQqYQUEiTmVhh4FBUKZ5
334XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV215k4TeHMFYE5RG0KYAS
3358Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6HXRpQCyASzEG7bgtROLhL
336ywIDAQAB
337-----END PUBLIC KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400338"""
Cory Benfield6492f7c2015-10-27 16:57:58 +0900339
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400340# Some PKCS#7 stuff. Generated with the openssl command line:
341#
342# openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
343#
344# with a certificate and key (but the key should be irrelevant) in s.pem
Alex Gaynore7f51982016-09-11 11:48:14 -0400345pkcs7Data = b"""\
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400346-----BEGIN PKCS7-----
347MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
348BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
349A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
350MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
351cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
352A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
353HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
354SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
355zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
356LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
357A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
35865w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
359Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
360Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
361bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
362VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
363/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
364Ho4EzbYCOaEAMQA=
365-----END PKCS7-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400366"""
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400367
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700368pkcs7DataASN1 = base64.b64decode(b"""
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700369MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
370BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
371A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
372MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
373cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
374A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
375HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
376SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
377zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
378LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
379A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
38065w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
381Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
382Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
383bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
384VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
385/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
386Ho4EzbYCOaEAMQA=
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700387""")
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700388
Alex Gaynore7f51982016-09-11 11:48:14 -0400389crlData = b"""\
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -0500390-----BEGIN X509 CRL-----
391MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
392SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
393D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
394MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
395MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
3964dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
3970yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
398vrzEeLDRiiPl92dyyWmu
399-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400400"""
Jean-Paul Calderonee890db32010-08-22 16:55:15 -0400401
Alex Gaynore7f51982016-09-11 11:48:14 -0400402crlDataUnsupportedExtension = b"""\
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400403-----BEGIN X509 CRL-----
404MIIGRzCCBS8CAQIwDQYJKoZIhvcNAQELBQAwJzELMAkGA1UEBhMCVVMxGDAWBgNV
405BAMMD2NyeXB0b2dyYXBoeS5pbxgPMjAxNTAxMDEwMDAwMDBaGA8yMDE2MDEwMTAw
406MDAwMFowggTOMBQCAQAYDzIwMTUwMTAxMDAwMDAwWjByAgEBGA8yMDE1MDEwMTAw
407MDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAn
408MQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQD
409CgEAMHICAQIYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAw
410MDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlw
411dG9ncmFwaHkuaW8wCgYDVR0VBAMKAQEwcgIBAxgPMjAxNTAxMDEwMDAwMDBaMFww
412GAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTArpCkwJzELMAkGA1UE
413BhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNVHRUEAwoBAjByAgEE
414GA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQG
415A1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5
416LmlvMAoGA1UdFQQDCgEDMHICAQUYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQR
417GA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgw
418FgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQQwcgIBBhgPMjAxNTAx
419MDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTAr
420pCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNV
421HRUEAwoBBTByAgEHGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAx
422MDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwP
423Y3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEGMHICAQgYDzIwMTUwMTAxMDAwMDAw
424WjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJ
425BgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQgw
426cgIBCRgPMjAxNTAxMDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAw
427WjA0BgNVHR0ELTArpCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dy
428YXBoeS5pbzAKBgNVHRUEAwoBCTByAgEKGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNV
429HRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJV
430UzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEKMC4CAQsYDzIw
431MTUwMTAxMDAwMDAwWjAYMAoGA1UdFQQDCgEBMAoGAyoDBAQDCgEAMA0GCSqGSIb3
432DQEBCwUAA4IBAQBTaloHlPaCZzYee8LxkWej5meiqxQVNWFoVdjesroa+f1FRrH+
433drRU60Nq97KCKf7f9GNN/J3ZIlQmYhmuDqh12f+XLpotoj1ZRfBz2hjFCkJlv+2c
434oWWGNHgA70ndFoVtcmX088SYpX8E3ARATivS4q2h9WlwV6rO93mhg3HGIe3JpcK4
4357BcW6Poi/ut/zsDOkVbI00SqaujRpdmdCTht82MH3ztjyDkI9KYaD/YEweKSrWOz
436SdEILd164bfBeLuplVI+xpmTEMVNpXBlSXl7+xIw9Vk7p7Q1Pa3k/SvhOldYCm6y
437C1xAg/AAq6w78yzYt18j5Mj0s6eeHi1YpHKw
438-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400439"""
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400440
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400441
442# A broken RSA private key which can be used to test the error path through
443# PKey.check.
Alex Gaynore7f51982016-09-11 11:48:14 -0400444inconsistentPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400445MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
4465kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
447OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
448zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
449nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
450HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
451oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
452-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400453"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400454
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400455# certificate with NULL bytes in subjectAltName and common name
456
Alex Gaynore7f51982016-09-11 11:48:14 -0400457nulbyteSubjectAltNamePEM = b"""-----BEGIN CERTIFICATE-----
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400458MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
459DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
460eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
461RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
462ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
463NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
464DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
465ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
466ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
467hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
468BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
469pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
470vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
471KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
472oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
47308LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
474HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
475BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
476Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
477bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
478AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
479i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
480HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
481kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
482VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
483RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
Alex Gaynore7f51982016-09-11 11:48:14 -0400484-----END CERTIFICATE-----"""
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400485
Alex Gaynore7f51982016-09-11 11:48:14 -0400486large_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Colleen Murphye09399b2016-03-01 17:40:49 -0800487MIIJYgIBAAKCAg4AtRua8eIeevRfsj+fkcHr1vmse7Kgb+oX1ssJAvCb1R7JQMnH
488hNDjDP6b3vEkZuPUzlDHymP+cNkXvvi4wJ4miVbO3+SeU4Sh+jmsHeHzGIXat9xW
4899PFtuPM5FQq8zvkY8aDeRYmYwN9JKu4/neMBCBqostYlTEWg+bSytO/qWnyHTHKh
490g0GfaDdqUQPsGQw+J0MgaYIjQOCVASHAPlzbDQLCtuOb587rwTLkZA2GwoHB/LyJ
491BwT0HHgBaiObE12Vs6wi2en0Uu11CiwEuK1KIBcZ2XbE6eApaZa6VH9ysEmUxPt7
492TqyZ4E2oMIYaLPNRxuvozdwTlj1svI1k1FrkaXGc5MTjbgigPMKjIb0T7b/4GNzt
493DhP1LvAeUMnrEi3hJJrcJPXHPqS8/RiytR9xQQW6Sdh4LaA3f9MQm3WSevWage3G
494P8YcCLssOVKsArDjuA52NF5LmYuAeUzXprm4ITDi2oO+0iFBpFW6VPEK4A9vO0Yk
495M/6Wt6tG8zyWhaSH1zFUTwfQ9Yvjyt5w1lrUaAJuoTpwbMVZaDJaEhjOaXU0dyPQ
496jOsePDOQcU6dkeTWsQ3LsHPEEug/X6819TLG5mb3V7bvV9nPFBfTJSCEG794kr90
497XgZfIN71FrdByxLerlbuJI21pPs/nZi9SXi9jAWeiS45/azUxMsyYgJArui+gjq7
498sV1pWiBm6/orAgMBAAECggINQp5L6Yu+oIXBqcSjgq8tfF9M5hd30pLuf/EheHZf
499LA7uAqn2fVGFI2OInIJhXIOT5OxsAXO0xXfltzawZxIFpOFMqajj4F7aYjvSpw9V
500J4EdSiJ/zgv8y1qUdbwEZbHVThRZjoSlrtSzilonBoHZAE0mHtqMz7iRFSk1zz6t
501GunRrvo/lROPentf3TsvHquVNUYI5yaapyO1S7xJhecMIIYSb8nbsHI54FBDGNas
5026mFmpPwI/47/6HTwOEWupnn3NicsjrHzUInOUpaMig4cRR+aP5bjqg/ty8xI8AoN
503evEmCytiWTc+Rvbp1ieN+1jpjN18PjUk80/W7qioHUDt4ieLic8uxWH2VD9SCEnX
504Mpi9tA/FqoZ+2A/3m1OfrY6jiZVE2g+asi9lCK7QVWL39eK82H4rPvtp0/dyo1/i
505ZZz68TXg+m8IgEZcp88hngbkuoTTzpGE73QuPKhGA1uMIimDdqPPB5WP76q+03Oi
506IRR5DfZnqPERed49by0enJ7tKa/gFPZizOV8ALKr0Dp+vfAkxGDLPLBLd2A3//tw
507xg0Q/wltihHSBujv4nYlDXdc5oYyMYZ+Lhc/VuOghHfBq3tgEQ1ECM/ofqXEIdy7
508nVcpZn3Eeq8Jl5CrqxE1ee3NxlzsJHn99yGQpr7mOhW/psJF3XNz80Meg3L4m1T8
509sMBK0GbaassuJhdzb5whAoIBBw48sx1b1WR4XxQc5O/HjHva+l16i2pjUnOUTcDF
510RWmSbIhBm2QQ2rVhO8+fak0tkl6ZnMWW4i0U/X5LOEBbC7+IS8bO3j3Revi+Vw5x
511j96LMlIe9XEub5i/saEWgiz7maCvfzLFU08e1OpT4qPDpP293V400ubA6R7WQTCv
512pBkskGwHeu0l/TuKkVqBFFUTu7KEbps8Gjg7MkJaFriAOv1zis/umK8pVS3ZAM6e
5138w5jfpRccn8Xzta2fRwTB5kCmfxdDsY0oYGxPLRAbW72bORoLGuyyPp/ojeGwoik
514JX9RttErc6FjyZtks370Pa8UL5QskyhMbDhrZW2jFD+RXYM1BrvmZRjbAoIBBwy4
515iFJpuDfytJfz1MWtaL5DqEL/kmiZYAXl6hifNhGu5GAipVIIGsDqEYW4i+VC15aa
5167kOCwz/I5zsB3vSDW96IRs4wXtqEZSibc2W/bqfVi+xcvPPl1ZhQ2EAwa4D/x035
517kyf20ffWOU+1yf2cnijzqs3IzlveUm+meLw5s3Rc+iG7DPWWeCoe1hVwANI1euNc
518pqKwKY905yFyjOje2OgiEU2kS4YME4zGeBys8yo7E42hNnN2EPK6xkkUqzdudLLQ
5198OUlKRTc8AbIf3XG1rpA4VUpTv3hhxGGwCRy6If8zgZQsNYchgNztRGk72Gcb8Dm
520vFSEN3ZtwxU64G3YZzntdcr2WPzxAoIBBw30g6Fgdb/gmVnOpL0//T0ePNDKIMPs
521jVJLaRduhoZgB1Bb9qPUPX0SzRzLZtg1tkZSDjBDoHmOHJfhxUaXt+FLCPPbrE4t
522+nq9n/nBaMM779w9ClqhqLOyGrwKoxjSmhi+TVEHyIxCbXMvPHVHfX9WzxjbcGrN
523ZvRaEVZWo+QlIX8yqdSwqxLk1WtAIRzvlcj7NKum8xBxPed6BNFep/PtgIAmoLT5
524L8wb7EWb2iUdc2KbZ4OaY51lDScqpATgXu3WjXfM+Q52G0mX6Wyd0cjlL711Zrjb
525yLbiueZT94lgIHHRRKtKc8CEqcjkQV5OzABS3P/gQSfgZXBdLKjOpTnKDUq7IBeH
526AoIBBweAOEIAPLQg1QRUrr3xRrYKRwlakgZDii9wJt1l5AgBTICzbTA1vzDJ1JM5
527AqSpCV6w9JWyYVcXK+HLdKBRZLaPPNEQDJ5lOxD6uMziWGl2rg8tj+1xNMWfxiPz
528aTCjoe4EoBUMoTq2gwzRcM2usEQNikXVhnj9Wzaivsaeb4bJ3GRPW5DkrO6JSEtT
529w+gvyMqQM2Hy5k7E7BT46sXVwaj/jZxuqGnebRixXtnp0WixdRIqYWUr1UqLf6hQ
530G7WP2BgoxCMaCmNW8+HMD/xuxucEotoIhZ+GgJKBFoNnjl3BX+qxYdSe9RbL/5Tr
5314It6Jxtj8uETJXEbv9Cg6v1agWPS9YY8RLTBAoIBBwrU2AsAUts6h1LgGLKK3UWZ
532oLH5E+4o+7HqSGRcRodVeN9NBXIYdHHOLeEG6YNGJiJ3bFP5ZQEu9iDsyoFVKJ9O
533Mw/y6dKZuxOCZ+X8FopSROg3yWfdOpAm6cnQZp3WqLNX4n/Q6WvKojfyEiPphjwT
5340ymrUJELXLWJmjUyPoAk6HgC0Gs28ZnEXbyhx7CSbZNFyCU/PNUDZwto3GisIPD3
535le7YjqHugezmjMGlA0sDw5aCXjfbl74vowRFYMO6e3ItApfSRgNV86CDoX74WI/5
536AYU/QVM4wGt8XGT2KwDFJaxYGKsGDMWmXY04dS+WPuetCbouWUusyFwRb9SzFave
537vYeU7Ab/
Alex Gaynore7f51982016-09-11 11:48:14 -0400538-----END RSA PRIVATE KEY-----"""
Colleen Murphye09399b2016-03-01 17:40:49 -0800539
Paul Kehrer72d968b2016-07-29 15:31:04 +0800540ec_private_key_pem = b"""-----BEGIN PRIVATE KEY-----
541MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgYirTZSx+5O8Y6tlG
542cka6W6btJiocdrdolfcukSoTEk+hRANCAAQkvPNu7Pa1GcsWU4v7ptNfqCJVq8Cx
543zo0MUVPQgwJ3aJtNM1QMOQUayCrRwfklg+D/rFSUwEUqtZh7fJDiFqz3
544-----END PRIVATE KEY-----
545"""
546
Paul Kehrer59d26252017-07-20 10:45:54 +0200547ec_root_key_pem = b"""-----BEGIN EC PRIVATE KEY-----
548MIGlAgEBBDEAz/HOBFPYLB0jLWeTpJn4Yc4m/C4mdWymVHBjOmnwiPHKT326iYN/
549ZhmSs+RM94RsoAcGBSuBBAAioWQDYgAEwE5vDdla/nLpWAPAQ0yFGqwLuw4BcN2r
550U+sKab5EAEHzLeceRa8ffncYdCXNoVsBcdob1y66CFZMEWLetPTmGapyWkBAs6/L
5518kUlkU9OsE+7IVo4QQJkgV5gM+Dim1XE
552-----END EC PRIVATE KEY-----
553"""
554
555ec_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
556MIICLTCCAbKgAwIBAgIMWW/hwTl6ufz6/WkCMAoGCCqGSM49BAMDMFgxGDAWBgNV
557BAMTD1Rlc3RpbmcgUm9vdCBDQTEQMA4GA1UEChMHVGVzdGluZzEQMA4GA1UEBxMH
558Q2hpY2FnbzELMAkGA1UECBMCSUwxCzAJBgNVBAYTAlVTMCAXDTE3MDcxOTIyNDgz
559M1oYDzk5OTkxMjMxMjM1OTU5WjBYMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0Ex
560EDAOBgNVBAoTB1Rlc3RpbmcxEDAOBgNVBAcTB0NoaWNhZ28xCzAJBgNVBAgTAklM
561MQswCQYDVQQGEwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABMBObw3ZWv5y6VgD
562wENMhRqsC7sOAXDdq1PrCmm+RABB8y3nHkWvH353GHQlzaFbAXHaG9cuughWTBFi
5633rT05hmqclpAQLOvy/JFJZFPTrBPuyFaOEECZIFeYDPg4ptVxKNDMEEwDwYDVR0T
564AQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwQAMB0GA1UdDgQWBBSoTrF0H2m8RDzB
565MnY2KReEPfz7ZjAKBggqhkjOPQQDAwNpADBmAjEA3+G1oVCxGjYX4iUN93QYcNHe
566e3fJQJwX9+KsHRut6qNZDUbvRbtO1YIAwB4UJZjwAjEAtXCPURS5A4McZHnSwgTi
567Td8GMrwKz0557OxxtKN6uVVy4ACFMqEw0zN/KJI1vxc9
568-----END CERTIFICATE-----"""
569
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400570
Alex Chanc6077062016-11-18 13:53:39 +0000571@pytest.fixture
572def x509_data():
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400573 """
Alex Chanc6077062016-11-18 13:53:39 +0000574 Create a new private key and start a certificate request (for a test
575 to finish in one way or another).
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400576 """
Alex Chanc6077062016-11-18 13:53:39 +0000577 # Basic setup stuff to generate a certificate
578 pkey = PKey()
579 pkey.generate_key(TYPE_RSA, 384)
580 req = X509Req()
581 req.set_pubkey(pkey)
582 # Authority good you have.
583 req.get_subject().commonName = "Yoda root CA"
584 x509 = X509()
585 subject = x509.get_subject()
586 subject.commonName = req.get_subject().commonName
587 x509.set_issuer(subject)
588 x509.set_pubkey(pkey)
589 now = datetime.now()
590 expire = datetime.now() + timedelta(days=100)
591 x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
592 x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
593 yield pkey, x509
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400594
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400595
Alex Chanc6077062016-11-18 13:53:39 +0000596class TestX509Ext(object):
597 """
598 Tests for `OpenSSL.crypto.X509Extension`.
599 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -0800600
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400601 def test_str(self):
602 """
Alex Chanc6077062016-11-18 13:53:39 +0000603 The string representation of `X509Extension` instances as
604 returned by `str` includes stuff.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400605 """
606 # This isn't necessarily the best string representation. Perhaps it
607 # will be changed/improved in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000608 assert (
609 str(X509Extension(b'basicConstraints', True, b'CA:false')) ==
610 'CA:FALSE'
611 )
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400612
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400613 def test_type(self):
614 """
Alex Chanc6077062016-11-18 13:53:39 +0000615 `X509Extension` and `X509ExtensionType` refer to the same type object
616 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400617 """
Alex Chanc6077062016-11-18 13:53:39 +0000618 assert X509Extension is X509ExtensionType
619 assert is_consistent_type(
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400620 X509Extension,
Alex Gaynore7f51982016-09-11 11:48:14 -0400621 'X509Extension', b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400622
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500623 def test_construction(self):
624 """
Alex Chanc6077062016-11-18 13:53:39 +0000625 `X509Extension` accepts an extension type name, a critical flag,
626 and an extension value and returns an `X509ExtensionType` instance.
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500627 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400628 basic = X509Extension(b'basicConstraints', True, b'CA:true')
Alex Chanc6077062016-11-18 13:53:39 +0000629 assert isinstance(basic, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500630
Alex Chanc6077062016-11-18 13:53:39 +0000631 comment = X509Extension(b'nsComment', False, b'pyOpenSSL unit test')
632 assert isinstance(comment, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500633
Alex Chanc6077062016-11-18 13:53:39 +0000634 @pytest.mark.parametrize('type_name, critical, value', [
635 (b'thisIsMadeUp', False, b'hi'),
636 (b'basicConstraints', False, b'blah blah'),
Jean-Paul Calderone391585f2008-12-31 14:36:31 -0500637
Jean-Paul Calderone2ee1e7c2008-12-31 14:58:38 -0500638 # Exercise a weird one (an extension which uses the r2i method). This
639 # exercises the codepath that requires a non-NULL ctx to be passed to
640 # X509V3_EXT_nconf. It can't work now because we provide no
641 # configuration database. It might be made to work in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000642 (b'proxyCertInfo', True,
643 b'language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')
644 ])
645 def test_invalid_extension(self, type_name, critical, value):
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500646 """
Alex Chanc6077062016-11-18 13:53:39 +0000647 `X509Extension` raises something if it is passed a bad
648 extension name or value.
649 """
650 with pytest.raises(Error):
651 X509Extension(type_name, critical, value)
652
653 @pytest.mark.parametrize('critical_flag', [True, False])
654 def test_get_critical(self, critical_flag):
655 """
656 `X509ExtensionType.get_critical` returns the value of the
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500657 extension's critical flag.
658 """
Alex Chanc6077062016-11-18 13:53:39 +0000659 ext = X509Extension(b'basicConstraints', critical_flag, b'CA:true')
660 assert ext.get_critical() == critical_flag
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500661
Alex Chanc6077062016-11-18 13:53:39 +0000662 @pytest.mark.parametrize('short_name, value', [
663 (b'basicConstraints', b'CA:true'),
664 (b'nsComment', b'foo bar'),
665 ])
666 def test_get_short_name(self, short_name, value):
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500667 """
Alex Chanc6077062016-11-18 13:53:39 +0000668 `X509ExtensionType.get_short_name` returns a string giving the
Alex Gaynor31287502015-09-05 16:11:27 -0400669 short type name of the extension.
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500670 """
Alex Chanc6077062016-11-18 13:53:39 +0000671 ext = X509Extension(short_name, True, value)
672 assert ext.get_short_name() == short_name
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500673
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400674 def test_get_data(self):
675 """
Alex Chanc6077062016-11-18 13:53:39 +0000676 `X509Extension.get_data` returns a string giving the data of
Alex Gaynor31287502015-09-05 16:11:27 -0400677 the extension.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400678 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400679 ext = X509Extension(b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400680 # Expect to get back the DER encoded form of CA:true.
Alex Chanc6077062016-11-18 13:53:39 +0000681 assert ext.get_data() == b'0\x03\x01\x01\xff'
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400682
Alex Chanc6077062016-11-18 13:53:39 +0000683 def test_unused_subject(self, x509_data):
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400684 """
Alex Chanc6077062016-11-18 13:53:39 +0000685 The `subject` parameter to `X509Extension` may be provided for an
686 extension which does not use it and is ignored in this case.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400687 """
Alex Chanc6077062016-11-18 13:53:39 +0000688 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400689 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000690 b'basicConstraints', False, b'CA:TRUE', subject=x509)
691 x509.add_extensions([ext1])
692 x509.sign(pkey, 'sha1')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400693 # This is a little lame. Can we think of a better way?
Alex Chanc6077062016-11-18 13:53:39 +0000694 text = dump_certificate(FILETYPE_TEXT, x509)
695 assert b'X509v3 Basic Constraints:' in text
696 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400697
Alex Chanc6077062016-11-18 13:53:39 +0000698 def test_subject(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400699 """
Alex Chanc6077062016-11-18 13:53:39 +0000700 If an extension requires a subject, the `subject` parameter to
701 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400702 """
Alex Chanc6077062016-11-18 13:53:39 +0000703 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400704 ext3 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000705 b'subjectKeyIdentifier', False, b'hash', subject=x509)
706 x509.add_extensions([ext3])
707 x509.sign(pkey, 'sha1')
708 text = dump_certificate(FILETYPE_TEXT, x509)
709 assert b'X509v3 Subject Key Identifier:' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400710
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400711 def test_missing_subject(self):
712 """
Alex Chanc6077062016-11-18 13:53:39 +0000713 If an extension requires a subject and the `subject` parameter
Alex Gaynor31287502015-09-05 16:11:27 -0400714 is given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400715 """
Alex Chanc6077062016-11-18 13:53:39 +0000716 with pytest.raises(Error):
717 X509Extension(b'subjectKeyIdentifier', False, b'hash')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400718
Alex Chanc6077062016-11-18 13:53:39 +0000719 @pytest.mark.parametrize('bad_obj', [
720 True,
721 object(),
722 "hello",
723 [],
724 ])
725 def test_invalid_subject(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400726 """
Alex Chanc6077062016-11-18 13:53:39 +0000727 If the `subject` parameter is given a value which is not an
728 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400729 """
Alex Chanc6077062016-11-18 13:53:39 +0000730 with pytest.raises(TypeError):
731 X509Extension(
732 'basicConstraints', False, 'CA:TRUE', subject=bad_obj)
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400733
Alex Chanc6077062016-11-18 13:53:39 +0000734 def test_unused_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400735 """
Alex Chanc6077062016-11-18 13:53:39 +0000736 The `issuer` parameter to `X509Extension` may be provided for an
737 extension which does not use it and is ignored in this case.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400738 """
Alex Chanc6077062016-11-18 13:53:39 +0000739 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400740 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000741 b'basicConstraints', False, b'CA:TRUE', issuer=x509)
742 x509.add_extensions([ext1])
743 x509.sign(pkey, 'sha1')
744 text = dump_certificate(FILETYPE_TEXT, x509)
745 assert b'X509v3 Basic Constraints:' in text
746 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400747
Alex Chanc6077062016-11-18 13:53:39 +0000748 def test_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400749 """
Alex Chanc6077062016-11-18 13:53:39 +0000750 If an extension requires an issuer, the `issuer` parameter to
751 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400752 """
Alex Chanc6077062016-11-18 13:53:39 +0000753 pkey, x509 = x509_data
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400754 ext2 = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -0400755 b'authorityKeyIdentifier', False, b'issuer:always',
Alex Chanc6077062016-11-18 13:53:39 +0000756 issuer=x509)
757 x509.add_extensions([ext2])
758 x509.sign(pkey, 'sha1')
759 text = dump_certificate(FILETYPE_TEXT, x509)
760 assert b'X509v3 Authority Key Identifier:' in text
761 assert b'DirName:/CN=Yoda root CA' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400762
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400763 def test_missing_issuer(self):
764 """
Alex Chanc6077062016-11-18 13:53:39 +0000765 If an extension requires an issue and the `issuer` parameter is
766 given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400767 """
Alex Chanc6077062016-11-18 13:53:39 +0000768 with pytest.raises(Error):
769 X509Extension(
770 b'authorityKeyIdentifier',
771 False, b'keyid:always,issuer:always')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400772
Alex Chanc6077062016-11-18 13:53:39 +0000773 @pytest.mark.parametrize('bad_obj', [
774 True,
775 object(),
776 "hello",
777 [],
778 ])
779 def test_invalid_issuer(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400780 """
Alex Chanc6077062016-11-18 13:53:39 +0000781 If the `issuer` parameter is given a value which is not an
782 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400783 """
Alex Chanc6077062016-11-18 13:53:39 +0000784 with pytest.raises(TypeError):
785 X509Extension(
786 'basicConstraints', False, 'keyid:always,issuer:always',
787 issuer=bad_obj)
Rick Dean47262da2009-07-08 16:17:17 -0500788
789
Paul Kehrer72d968b2016-07-29 15:31:04 +0800790class TestPKey(object):
791 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +0100792 Tests for `OpenSSL.crypto.PKey`.
Paul Kehrer72d968b2016-07-29 15:31:04 +0800793 """
794
795 def test_convert_from_cryptography_private_key(self):
796 """
797 PKey.from_cryptography_key creates a proper private PKey.
798 """
799 key = serialization.load_pem_private_key(
800 intermediate_key_pem, None, backend
801 )
802 pkey = PKey.from_cryptography_key(key)
803
804 assert isinstance(pkey, PKey)
805 assert pkey.bits() == key.key_size
806 assert pkey._only_public is False
807 assert pkey._initialized is True
808
809 def test_convert_from_cryptography_public_key(self):
810 """
811 PKey.from_cryptography_key creates a proper public PKey.
812 """
813 key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
814 pkey = PKey.from_cryptography_key(key)
815
816 assert isinstance(pkey, PKey)
817 assert pkey.bits() == key.key_size
818 assert pkey._only_public is True
819 assert pkey._initialized is True
820
821 def test_convert_from_cryptography_unsupported_type(self):
822 """
823 PKey.from_cryptography_key raises TypeError with an unsupported type.
824 """
825 key = serialization.load_pem_private_key(
826 ec_private_key_pem, None, backend
827 )
828 with pytest.raises(TypeError):
829 PKey.from_cryptography_key(key)
830
831 def test_convert_public_pkey_to_cryptography_key(self):
832 """
833 PKey.to_cryptography_key creates a proper cryptography public key.
834 """
835 pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
836 key = pkey.to_cryptography_key()
837
838 assert isinstance(key, rsa.RSAPublicKey)
839 assert pkey.bits() == key.key_size
840
841 def test_convert_private_pkey_to_cryptography_key(self):
842 """
843 PKey.to_cryptography_key creates a proper cryptography private key.
844 """
845 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
846 key = pkey.to_cryptography_key()
847
848 assert isinstance(key, rsa.RSAPrivateKey)
849 assert pkey.bits() == key.key_size
850
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400851 def test_type(self):
852 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000853 `PKey` and `PKeyType` refer to the same type object and can be used to
854 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400855 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000856 assert PKey is PKeyType
857 assert is_consistent_type(PKey, 'PKey')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400858
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500859 def test_construction(self):
860 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000861 `PKey` takes no arguments and returns a new `PKey` instance.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500862 """
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500863 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000864 assert isinstance(key, PKey)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500865
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500866 def test_pregeneration(self):
867 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000868 `PKey.bits` and `PKey.type` return `0` before the key is generated.
869 `PKey.check` raises `TypeError` before the key is generated.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500870 """
871 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000872 assert key.type() == 0
873 assert key.bits() == 0
874 with pytest.raises(TypeError):
875 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500876
Alex Chan9e2a9932017-01-25 14:29:19 +0000877 def test_failed_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500878 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000879 `PKey.generate_key` takes two arguments, the first giving the key type
880 as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
881 bits to generate. If an invalid type is specified or generation fails,
882 `Error` is raised. If an invalid number of bits is specified,
883 `ValueError` or `Error` is raised.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500884 """
885 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000886 with pytest.raises(TypeError):
887 key.generate_key("foo", "bar")
888 with pytest.raises(Error):
889 key.generate_key(-1, 0)
Jean-Paul Calderoneab82db72008-03-06 00:09:31 -0500890
Alex Chan9e2a9932017-01-25 14:29:19 +0000891 with pytest.raises(ValueError):
892 key.generate_key(TYPE_RSA, -1)
893 with pytest.raises(ValueError):
894 key.generate_key(TYPE_RSA, 0)
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500895
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400896 with pytest.raises(TypeError):
897 key.generate_key(TYPE_RSA, object())
898
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500899 # XXX RSA generation for small values of bits is fairly buggy in a wide
900 # range of OpenSSL versions. I need to figure out what the safe lower
901 # bound for a reasonable number of OpenSSL versions is and explicitly
902 # check for that in the wrapper. The failure behavior is typically an
903 # infinite loop inside OpenSSL.
904
Alex Chan9e2a9932017-01-25 14:29:19 +0000905 # with pytest.raises(Error):
906 # key.generate_key(TYPE_RSA, 2)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500907
908 # XXX DSA generation seems happy with any number of bits. The DSS
909 # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
910 # generator doesn't seem to care about the upper limit at all. For
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500911 # the lower limit, it uses 512 if anything smaller is specified.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500912 # So, it doesn't seem possible to make generate_key fail for
913 # TYPE_DSA with a bits argument which is at least an int.
914
Alex Chan9e2a9932017-01-25 14:29:19 +0000915 # with pytest.raises(Error):
916 # key.generate_key(TYPE_DSA, -7)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500917
Alex Chan9e2a9932017-01-25 14:29:19 +0000918 def test_rsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500919 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000920 `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
921 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500922 """
923 bits = 128
924 key = PKey()
925 key.generate_key(TYPE_RSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000926 assert key.type() == TYPE_RSA
927 assert key.bits() == bits
928 assert key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500929
Alex Chan9e2a9932017-01-25 14:29:19 +0000930 def test_dsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500931 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000932 `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
933 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500934 """
935 # 512 is a magic number. The DSS (Digital Signature Standard)
936 # allows a minimum of 512 bits for DSA. DSA_generate_parameters
937 # will silently promote any value below 512 to 512.
938 bits = 512
939 key = PKey()
940 key.generate_key(TYPE_DSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000941 assert key.type() == TYPE_DSA
942 assert key.bits() == bits
943 with pytest.raises(TypeError):
944 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500945
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500946 def test_regeneration(self):
947 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000948 `PKey.generate_key` can be called multiple times on the same key to
949 generate new keys.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500950 """
951 key = PKey()
952 for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
Alex Gaynor7f636492015-09-04 13:26:52 -0400953 key.generate_key(type, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000954 assert key.type() == type
955 assert key.bits() == bits
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500956
Alex Chan9e2a9932017-01-25 14:29:19 +0000957 def test_inconsistent_key(self):
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400958 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000959 `PKey.check` returns `Error` if the key is not consistent.
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400960 """
961 key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
Alex Chan9e2a9932017-01-25 14:29:19 +0000962 with pytest.raises(Error):
963 key.check()
Jean-Paul Calderonee81020e2011-06-12 21:48:57 -0400964
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400965 def test_check_public_key(self):
966 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000967 `PKey.check` raises `TypeError` if only the public part of the key
968 is available.
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400969 """
970 # A trick to get a public-only key
971 key = PKey()
972 key.generate_key(TYPE_RSA, 512)
973 cert = X509()
974 cert.set_pubkey(key)
975 pub = cert.get_pubkey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000976 with pytest.raises(TypeError):
977 pub.check()
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400978
979
Alex Chan9e2a9932017-01-25 14:29:19 +0000980def x509_name(**attrs):
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500981 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000982 Return a new X509Name with the given attributes.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500983 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000984 # XXX There's no other way to get a new X509Name yet.
985 name = X509().get_subject()
986 attrs = list(attrs.items())
Alex Gaynoraceb3e22015-09-05 12:00:22 -0400987
Alex Chan9e2a9932017-01-25 14:29:19 +0000988 # Make the order stable - order matters!
989 def key(attr):
990 return attr[1]
991 attrs.sort(key=key)
992 for k, v in attrs:
993 setattr(name, k, v)
994 return name
Alex Gaynor85b49702015-09-05 16:30:59 -0400995
Alex Chan9e2a9932017-01-25 14:29:19 +0000996
997class TestX509Name(object):
998 """
999 Unit tests for `OpenSSL.crypto.X509Name`.
1000 """
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001001
Rick Deane15b1472009-07-09 15:53:42 -05001002 def test_type(self):
1003 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001004 The type of X509Name objects is `X509NameType`.
Rick Deane15b1472009-07-09 15:53:42 -05001005 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001006 assert X509Name is X509NameType
1007 assert X509NameType.__name__ == 'X509Name'
1008 assert isinstance(X509NameType, type)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001009
Alex Chan9e2a9932017-01-25 14:29:19 +00001010 name = x509_name()
1011 assert isinstance(name, X509NameType)
Rick Deane15b1472009-07-09 15:53:42 -05001012
Alex Chan9e2a9932017-01-25 14:29:19 +00001013 def test_only_string_attributes(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001014 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001015 Attempting to set a non-`str` attribute name on an `X509Name` instance
1016 causes `TypeError` to be raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001017 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001018 name = x509_name()
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001019 # Beyond these cases, you may also think that unicode should be
Alex Gaynor31287502015-09-05 16:11:27 -04001020 # rejected. Sorry, you're wrong. unicode is automatically converted
1021 # to str outside of the control of X509Name, so there's no way to
1022 # reject it.
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -08001023
Alex Gaynor31287502015-09-05 16:11:27 -04001024 # Also, this used to test str subclasses, but that test is less
1025 # relevant now that the implementation is in Python instead of C. Also
1026 # PyPy automatically converts str subclasses to str when they are
1027 # passed to setattr, so we can't test it on PyPy. Apparently CPython
1028 # does this sometimes as well.
Alex Chan9e2a9932017-01-25 14:29:19 +00001029 with pytest.raises(TypeError):
1030 setattr(name, None, "hello")
1031 with pytest.raises(TypeError):
1032 setattr(name, 30, "hello")
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001033
Alex Chan9e2a9932017-01-25 14:29:19 +00001034 def test_set_invalid_attribute(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001035 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001036 Attempting to set any attribute name on an `X509Name` instance for
1037 which no corresponding NID is defined causes `AttributeError` to be
1038 raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001039 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001040 name = x509_name()
1041 with pytest.raises(AttributeError):
1042 setattr(name, "no such thing", None)
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001043
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001044 def test_attributes(self):
1045 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001046 `X509Name` instances have attributes for each standard (?)
1047 X509Name field.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001048 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001049 name = x509_name()
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001050 name.commonName = "foo"
Alex Gaynor37726112016-07-04 09:51:32 -04001051 assert name.commonName == "foo"
1052 assert name.CN == "foo"
1053
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001054 name.CN = "baz"
Alex Gaynor37726112016-07-04 09:51:32 -04001055 assert name.commonName == "baz"
1056 assert name.CN == "baz"
1057
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001058 name.commonName = "bar"
Alex Gaynor37726112016-07-04 09:51:32 -04001059 assert name.commonName == "bar"
1060 assert name.CN == "bar"
1061
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001062 name.CN = "quux"
Alex Gaynor37726112016-07-04 09:51:32 -04001063 assert name.commonName == "quux"
1064 assert name.CN == "quux"
1065
1066 assert name.OU is None
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001067
Alex Gaynor7778e792016-07-03 23:38:48 -04001068 with pytest.raises(AttributeError):
1069 name.foobar
1070
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001071 def test_copy(self):
1072 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001073 `X509Name` creates a new `X509Name` instance with all the same
1074 attributes as an existing `X509Name` instance when called with one.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001075 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001076 name = x509_name(commonName="foo", emailAddress="bar@example.com")
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001077
1078 copy = X509Name(name)
Alex Chan9e2a9932017-01-25 14:29:19 +00001079 assert copy.commonName == "foo"
1080 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001081
1082 # Mutate the copy and ensure the original is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001083 copy.commonName = "baz"
Alex Chan9e2a9932017-01-25 14:29:19 +00001084 assert name.commonName == "foo"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001085
1086 # Mutate the original and ensure the copy is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001087 name.emailAddress = "quux@example.com"
Alex Chan9e2a9932017-01-25 14:29:19 +00001088 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001089
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001090 def test_repr(self):
1091 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001092 `repr` passed an `X509Name` instance should return a string containing
1093 a description of the type and the NIDs which have been set on it.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001094 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001095 name = x509_name(commonName="foo", emailAddress="bar")
1096 assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001097
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001098 def test_comparison(self):
1099 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001100 `X509Name` instances should compare based on their NIDs.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001101 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001102 def _equality(a, b, assert_true, assert_false):
1103 assert_true(a == b)
1104 assert_false(a != b)
1105 assert_true(b == a)
1106 assert_false(b != a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001107
Alex Chan9e2a9932017-01-25 14:29:19 +00001108 def assert_true(x):
1109 assert x
1110
1111 def assert_false(x):
1112 assert not x
1113
1114 def assert_equal(a, b):
1115 _equality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001116
1117 # Instances compare equal to themselves.
Alex Chan9e2a9932017-01-25 14:29:19 +00001118 name = x509_name()
1119 assert_equal(name, name)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001120
1121 # Empty instances should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001122 assert_equal(x509_name(), x509_name())
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001123
1124 # Instances with equal NIDs should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001125 assert_equal(x509_name(commonName="foo"),
1126 x509_name(commonName="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001127
1128 # Instance with equal NIDs set using different aliases should compare
1129 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001130 assert_equal(x509_name(commonName="foo"),
1131 x509_name(CN="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001132
1133 # Instances with more than one NID with the same values should compare
1134 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001135 assert_equal(x509_name(CN="foo", organizationalUnitName="bar"),
1136 x509_name(commonName="foo", OU="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001137
Alex Chan9e2a9932017-01-25 14:29:19 +00001138 def assert_not_equal(a, b):
1139 _equality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001140
1141 # Instances with different values for the same NID should not compare
1142 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001143 assert_not_equal(x509_name(CN="foo"),
1144 x509_name(CN="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001145
1146 # Instances with different NIDs should not compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001147 assert_not_equal(x509_name(CN="foo"),
1148 x509_name(OU="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001149
Alex Chan9e2a9932017-01-25 14:29:19 +00001150 assert_not_equal(x509_name(), object())
Alex Gaynor7778e792016-07-03 23:38:48 -04001151
Alex Chan9e2a9932017-01-25 14:29:19 +00001152 def _inequality(a, b, assert_true, assert_false):
1153 assert_true(a < b)
1154 assert_true(a <= b)
1155 assert_true(b > a)
1156 assert_true(b >= a)
1157 assert_false(a > b)
1158 assert_false(a >= b)
1159 assert_false(b < a)
1160 assert_false(b <= a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001161
Alex Chan9e2a9932017-01-25 14:29:19 +00001162 def assert_less_than(a, b):
1163 _inequality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001164
1165 # An X509Name with a NID with a value which sorts less than the value
1166 # of the same NID on another X509Name compares less than the other
1167 # X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001168 assert_less_than(x509_name(CN="abc"),
1169 x509_name(CN="def"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001170
Alex Chan9e2a9932017-01-25 14:29:19 +00001171 def assert_greater_than(a, b):
1172 _inequality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001173
1174 # An X509Name with a NID with a value which sorts greater than the
1175 # value of the same NID on another X509Name compares greater than the
1176 # other X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001177 assert_greater_than(x509_name(CN="def"),
1178 x509_name(CN="abc"))
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001179
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001180 def test_hash(self):
1181 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001182 `X509Name.hash` returns an integer hash based on the value of the name.
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001183 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001184 a = x509_name(CN="foo")
1185 b = x509_name(CN="foo")
1186 assert a.hash() == b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001187 a.CN = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001188 assert a.hash() != b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001189
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001190 def test_der(self):
1191 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001192 `X509Name.der` returns the DER encoded form of the name.
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001193 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001194 a = x509_name(CN="foo", C="US")
1195 assert (a.der() ==
1196 b'0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
1197 b'1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo')
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001198
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001199 def test_get_components(self):
1200 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001201 `X509Name.get_components` returns a `list` of two-tuples of `str`
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001202 giving the NIDs and associated values which make up the name.
1203 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001204 a = x509_name()
1205 assert a.get_components() == []
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001206 a.CN = "foo"
Alex Chan9e2a9932017-01-25 14:29:19 +00001207 assert a.get_components() == [(b"CN", b"foo")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001208 a.organizationalUnitName = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001209 assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001210
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001211 def test_load_nul_byte_attribute(self):
1212 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001213 An `X509Name` from an `X509` instance loaded from a file can have a
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001214 NUL byte in the value of one of its attributes.
1215 """
1216 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1217 subject = cert.get_subject()
Alex Chan9e2a9932017-01-25 14:29:19 +00001218 assert "null.python.org\x00example.org" == subject.commonName
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001219
Alex Chan9e2a9932017-01-25 14:29:19 +00001220 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001221 """
1222 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001223 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001224 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001225 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001226 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001227 with pytest.raises(Error):
1228 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001229
1230
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001231class _PKeyInteractionTestsMixin:
1232 """
1233 Tests which involve another thing and a PKey.
1234 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001235
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001236 def signable(self):
1237 """
Alex Chanfb078d82017-04-20 11:16:15 +01001238 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001239 """
1240 raise NotImplementedError()
1241
Alex Chanb00ede22017-01-30 07:24:40 +00001242 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001243 """
Alex Chanb00ede22017-01-30 07:24:40 +00001244 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001245 """
1246 request = self.signable()
1247 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001248 with pytest.raises(ValueError):
1249 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001250
Alex Chanb00ede22017-01-30 07:24:40 +00001251 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001252 """
Alex Chanb00ede22017-01-30 07:24:40 +00001253 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1254 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001255 """
1256 request = self.signable()
1257 key = PKey()
1258 key.generate_key(TYPE_RSA, 512)
1259 request.set_pubkey(key)
1260 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001261 with pytest.raises(ValueError):
1262 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001263
Alex Chanb00ede22017-01-30 07:24:40 +00001264 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001265 """
Alex Chanb00ede22017-01-30 07:24:40 +00001266 `X509Req.sign` raises `ValueError` when passed a digest name which is
1267 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001268 """
1269 request = self.signable()
1270 key = PKey()
1271 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001272 with pytest.raises(ValueError):
1273 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001274
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001275 def test_sign(self):
1276 """
Alex Chanb00ede22017-01-30 07:24:40 +00001277 `X509Req.sign` succeeds when passed a private key object and a
1278 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001279 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001280 """
1281 request = self.signable()
1282 key = PKey()
1283 key.generate_key(TYPE_RSA, 512)
1284 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001285 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001286 # If the type has a verify method, cover that too.
1287 if getattr(request, 'verify', None) is not None:
1288 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001289 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001290 # Make another key that won't verify.
1291 key = PKey()
1292 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001293 with pytest.raises(Error):
1294 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001295
1296
Alex Chanb00ede22017-01-30 07:24:40 +00001297class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001298 """
Alex Chanb00ede22017-01-30 07:24:40 +00001299 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001300 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001301
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001302 def signable(self):
1303 """
Alex Chanb00ede22017-01-30 07:24:40 +00001304 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001305 """
1306 return X509Req()
1307
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001308 def test_type(self):
1309 """
Alex Chanb00ede22017-01-30 07:24:40 +00001310 `X509Req` and `X509ReqType` refer to the same type object and can be
1311 used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001312 """
Alex Chanb00ede22017-01-30 07:24:40 +00001313 assert X509Req is X509ReqType
1314 assert is_consistent_type(X509Req, 'X509Req')
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001315
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001316 def test_construction(self):
1317 """
Alex Chanb00ede22017-01-30 07:24:40 +00001318 `X509Req` takes no arguments and returns an `X509ReqType` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001319 """
1320 request = X509Req()
Alex Gaynor31287502015-09-05 16:11:27 -04001321 assert isinstance(request, X509ReqType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001322
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001323 def test_version(self):
1324 """
Alex Chanb00ede22017-01-30 07:24:40 +00001325 `X509Req.set_version` sets the X.509 version of the certificate
1326 request. `X509Req.get_version` returns the X.509 version of the
1327 certificate request. The initial value of the version is 0.
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001328 """
1329 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001330 assert request.get_version() == 0
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001331 request.set_version(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001332 assert request.get_version() == 1
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001333 request.set_version(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001334 assert request.get_version() == 3
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001335
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001336 def test_version_wrong_args(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001337 """
Alex Chanb00ede22017-01-30 07:24:40 +00001338 `X509Req.set_version` raises `TypeError` if called with a non-`int`
1339 argument.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001340 """
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001341 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001342 with pytest.raises(TypeError):
1343 request.set_version("foo")
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001344
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001345 def test_get_subject(self):
1346 """
Alex Chanb00ede22017-01-30 07:24:40 +00001347 `X509Req.get_subject` returns an `X509Name` for the subject of the
1348 request and which is valid even after the request object is
1349 otherwise dead.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001350 """
1351 request = X509Req()
1352 subject = request.get_subject()
Alex Gaynor31287502015-09-05 16:11:27 -04001353 assert isinstance(subject, X509NameType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001354 subject.commonName = "foo"
Alex Chanb00ede22017-01-30 07:24:40 +00001355 assert request.get_subject().commonName == "foo"
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001356 del request
1357 subject.commonName = "bar"
Alex Chanb00ede22017-01-30 07:24:40 +00001358 assert subject.commonName == "bar"
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001359
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001360 def test_add_extensions(self):
1361 """
Alex Chanb00ede22017-01-30 07:24:40 +00001362 `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
1363 and adds them to the X509 request.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001364 """
1365 request = X509Req()
1366 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001367 X509Extension(b'basicConstraints', True, b'CA:false')])
Stephen Holsappleca545b72014-01-28 21:43:25 -08001368 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001369 assert len(exts) == 1
1370 assert exts[0].get_short_name() == b'basicConstraints'
1371 assert exts[0].get_critical() == 1
1372 assert exts[0].get_data() == b'0\x00'
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001373
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001374 def test_get_extensions(self):
1375 """
Alex Chanb00ede22017-01-30 07:24:40 +00001376 `X509Req.get_extensions` returns a `list` of extensions added to this
1377 X509 request.
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001378 """
1379 request = X509Req()
1380 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001381 assert exts == []
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001382 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001383 X509Extension(b'basicConstraints', True, b'CA:true'),
1384 X509Extension(b'keyUsage', False, b'digitalSignature')])
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001385 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001386 assert len(exts) == 2
1387 assert exts[0].get_short_name() == b'basicConstraints'
1388 assert exts[0].get_critical() == 1
1389 assert exts[0].get_data() == b'0\x03\x01\x01\xff'
1390 assert exts[1].get_short_name() == b'keyUsage'
1391 assert exts[1].get_critical() == 0
1392 assert exts[1].get_data() == b'\x03\x02\x07\x80'
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001393
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001394 def test_add_extensions_wrong_args(self):
1395 """
Alex Chanb00ede22017-01-30 07:24:40 +00001396 `X509Req.add_extensions` raises `TypeError` if called with a
1397 non-`list`. Or it raises `ValueError` if called with a `list`
1398 containing objects other than `X509Extension` instances.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001399 """
1400 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001401 with pytest.raises(TypeError):
1402 request.add_extensions(object())
1403 with pytest.raises(ValueError):
1404 request.add_extensions([object()])
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001405
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001406 def test_verify_wrong_args(self):
1407 """
Alex Chanb00ede22017-01-30 07:24:40 +00001408 `X509Req.verify` raises `TypeError` if passed anything other than a
1409 `PKey` instance as its single argument.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001410 """
1411 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001412 with pytest.raises(TypeError):
1413 request.verify(object())
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001414
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001415 def test_verify_uninitialized_key(self):
1416 """
Alex Chanb00ede22017-01-30 07:24:40 +00001417 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1418 `OpenSSL.crypto.PKey` which contains no key data.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001419 """
1420 request = X509Req()
1421 pkey = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001422 with pytest.raises(Error):
1423 request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001424
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001425 def test_verify_wrong_key(self):
1426 """
Alex Chanb00ede22017-01-30 07:24:40 +00001427 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1428 `OpenSSL.crypto.PKey` which does not represent the public part of the
Alex Gaynor31287502015-09-05 16:11:27 -04001429 key which signed the request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001430 """
1431 request = X509Req()
1432 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001433 request.sign(pkey, GOOD_DIGEST)
Alex Chanb00ede22017-01-30 07:24:40 +00001434 another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
1435 with pytest.raises(Error):
1436 request.verify(another_pkey)
1437
1438 def test_verify_success(self):
1439 """
1440 `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
1441 which represents the public part of the key which signed the request.
1442 """
1443 request = X509Req()
1444 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
1445 request.sign(pkey, GOOD_DIGEST)
1446 assert request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001447
Paul Kehrer41c10242017-06-29 18:24:17 -05001448 def test_convert_from_cryptography(self):
1449 crypto_req = x509.load_pem_x509_csr(
1450 cleartextCertificateRequestPEM, backend
1451 )
1452 req = X509Req.from_cryptography(crypto_req)
1453 assert isinstance(req, X509Req)
1454
1455 def test_convert_from_cryptography_unsupported_type(self):
1456 with pytest.raises(TypeError):
1457 X509Req.from_cryptography(object())
1458
1459 def test_convert_to_cryptography_key(self):
1460 req = load_certificate_request(
1461 FILETYPE_PEM, cleartextCertificateRequestPEM
1462 )
1463 crypto_req = req.to_cryptography()
1464 assert isinstance(crypto_req, x509.CertificateSigningRequest)
1465
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001466
Alex Chanb00ede22017-01-30 07:24:40 +00001467class TestX509(_PKeyInteractionTestsMixin):
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001468 """
Alex Chanb00ede22017-01-30 07:24:40 +00001469 Tests for `OpenSSL.crypto.X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001470 """
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001471 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Jean-Paul Calderone8114b452008-03-25 15:27:59 -04001472
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001473 extpem = """
1474-----BEGIN CERTIFICATE-----
1475MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
1476BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
1477eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
1478MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
1479aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
1480hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
1481Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
1482zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
1483hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
1484TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
148503HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
1486MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
1487b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
1488MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
1489uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
1490WpOdIpB8KksUTCzV591Nr1wd
1491-----END CERTIFICATE-----
1492 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001493
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001494 def signable(self):
1495 """
Alex Chanb00ede22017-01-30 07:24:40 +00001496 Create and return a new `X509`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001497 """
1498 return X509()
1499
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001500 def test_type(self):
1501 """
Alex Chanb00ede22017-01-30 07:24:40 +00001502 `X509` and `X509Type` refer to the same type object and can be used to
1503 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001504 """
Alex Chanb00ede22017-01-30 07:24:40 +00001505 assert X509 is X509Type
1506 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001507
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001508 def test_construction(self):
1509 """
Alex Chanb00ede22017-01-30 07:24:40 +00001510 `X509` takes no arguments and returns an instance of `X509Type`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001511 """
1512 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001513 assert isinstance(certificate, X509Type)
1514 assert type(X509Type).__name__ == 'type'
1515 assert type(certificate).__name__ == 'X509'
1516 assert type(certificate) == X509Type
1517 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001518
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001519 def test_set_version_wrong_args(self):
1520 """
Alex Chanb00ede22017-01-30 07:24:40 +00001521 `X509.set_version` raises `TypeError` if invoked with an argument
1522 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001523 """
1524 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001525 with pytest.raises(TypeError):
1526 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001527
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001528 def test_version(self):
1529 """
Alex Chanb00ede22017-01-30 07:24:40 +00001530 `X509.set_version` sets the certificate version number.
1531 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001532 """
1533 cert = X509()
1534 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001535 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001536
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001537 def test_serial_number(self):
1538 """
Alex Chanb00ede22017-01-30 07:24:40 +00001539 The serial number of an `X509` can be retrieved and
1540 modified with `X509.get_serial_number` and
1541 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001542 """
1543 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001544 with pytest.raises(TypeError):
1545 certificate.set_serial_number("1")
1546 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001547 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001548 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001549 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001550 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001551 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001552 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001553 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001554 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001555
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001556 def _setBoundTest(self, which):
1557 """
Alex Chanb00ede22017-01-30 07:24:40 +00001558 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001559 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1560 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001561 """
1562 certificate = X509()
1563 set = getattr(certificate, 'set_not' + which)
1564 get = getattr(certificate, 'get_not' + which)
1565
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001566 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001567 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001568
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001569 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001570 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001571 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001572 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001573
1574 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001575 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001576 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001577 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001578
1579 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001580 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001581 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001582 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001583
1584 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001585 with pytest.raises(ValueError):
1586 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001587
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001588 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001589 with pytest.raises(TypeError):
1590 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001591 with pytest.raises(TypeError):
1592 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001593 with pytest.raises(TypeError):
1594 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001595
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001596 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001597
1598 def test_set_notBefore(self):
1599 """
Alex Chanb00ede22017-01-30 07:24:40 +00001600 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001601 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1602 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001603 """
1604 self._setBoundTest("Before")
1605
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001606 def test_set_notAfter(self):
1607 """
Alex Chanb00ede22017-01-30 07:24:40 +00001608 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001609 GENERALIZEDTIME and sets the end of the certificate's validity period
1610 to it.
1611 """
1612 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001613
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001614 def test_get_notBefore(self):
1615 """
Alex Chanb00ede22017-01-30 07:24:40 +00001616 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001617 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001618 internally.
1619 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001620 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001621 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001622
Rick Dean38a05c82009-07-18 01:41:30 -05001623 def test_get_notAfter(self):
1624 """
Alex Chanb00ede22017-01-30 07:24:40 +00001625 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001626 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001627 internally.
1628 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001629 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001630 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001631
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001632 def test_gmtime_adj_notBefore_wrong_args(self):
1633 """
Alex Chanb00ede22017-01-30 07:24:40 +00001634 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1635 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001636 """
1637 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001638 with pytest.raises(TypeError):
1639 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001640
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001641 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001642 def test_gmtime_adj_notBefore(self):
1643 """
Alex Chanb00ede22017-01-30 07:24:40 +00001644 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1645 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001646 """
1647 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001648 not_before_min = (
1649 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1650 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001651 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001652 not_before = datetime.strptime(
1653 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1654 )
Alex Gaynor7f5610c2017-07-07 00:09:34 -04001655 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001656 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001657
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001658 def test_gmtime_adj_notAfter_wrong_args(self):
1659 """
Alex Chanb00ede22017-01-30 07:24:40 +00001660 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1661 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001662 """
1663 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001664 with pytest.raises(TypeError):
1665 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001666
Alex Gaynor642de6f2017-07-24 00:57:38 -04001667 @flaky.flaky
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001668 def test_gmtime_adj_notAfter(self):
1669 """
Alex Chanb00ede22017-01-30 07:24:40 +00001670 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001671 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001672 """
1673 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001674 not_after_min = (
1675 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1676 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001677 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001678 not_after = datetime.strptime(
1679 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1680 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001681 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001682 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001683
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001684 def test_has_expired(self):
1685 """
Alex Chanb00ede22017-01-30 07:24:40 +00001686 `X509.has_expired` returns `True` if the certificate's not-after time
1687 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001688 """
1689 cert = X509()
1690 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001691 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001692
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001693 def test_has_not_expired(self):
1694 """
Alex Chanb00ede22017-01-30 07:24:40 +00001695 `X509.has_expired` returns `False` if the certificate's not-after time
1696 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001697 """
1698 cert = X509()
1699 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001700 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001701
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001702 def test_root_has_not_expired(self):
1703 """
Alex Chanb00ede22017-01-30 07:24:40 +00001704 `X509.has_expired` returns `False` if the certificate's not-after time
1705 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001706 """
1707 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001708 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001709
Rick Dean38a05c82009-07-18 01:41:30 -05001710 def test_digest(self):
1711 """
Alex Chanb00ede22017-01-30 07:24:40 +00001712 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001713 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001714 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001715 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001716 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001717 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1718 # actually matters to the assertion (ie, another arbitrary, good
1719 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001720 # Digest verified with the command:
1721 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001722 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001723 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001724
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001725 def _extcert(self, pkey, extensions):
1726 cert = X509()
1727 cert.set_pubkey(pkey)
1728 cert.get_subject().commonName = "Unit Tests"
1729 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001730 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001731 cert.set_notBefore(when)
1732 cert.set_notAfter(when)
1733
1734 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001735 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001736 return load_certificate(
1737 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1738
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001739 def test_extension_count(self):
1740 """
Alex Chanb00ede22017-01-30 07:24:40 +00001741 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001742 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001743 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001744 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001745 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1746 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001747 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001748 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001749
1750 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001751 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001752 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001753
1754 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001755 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001756 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001757
1758 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001759 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001760 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001761
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001762 def test_get_extension(self):
1763 """
Alex Chanb00ede22017-01-30 07:24:40 +00001764 `X509.get_extension` takes an integer and returns an
1765 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001766 """
1767 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001768 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1769 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001770 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001771 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001772
1773 cert = self._extcert(pkey, [ca, key, subjectAltName])
1774
1775 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001776 assert isinstance(ext, X509Extension)
1777 assert ext.get_critical()
1778 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001779
1780 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001781 assert isinstance(ext, X509Extension)
1782 assert ext.get_critical()
1783 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001784
1785 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001786 assert isinstance(ext, X509Extension)
1787 assert not ext.get_critical()
1788 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001789
Alex Chanb00ede22017-01-30 07:24:40 +00001790 with pytest.raises(IndexError):
1791 cert.get_extension(-1)
1792 with pytest.raises(IndexError):
1793 cert.get_extension(4)
1794 with pytest.raises(TypeError):
1795 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001796
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001797 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001798 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001799 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001800 bytes and this value is reflected in the string representation of the
1801 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001802 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001803 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001804
1805 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001806 assert ext.get_short_name() == b'subjectAltName'
1807 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001808 b"DNS:altnull.python.org\x00example.com, "
1809 b"email:null@python.org\x00user@example.org, "
1810 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001811 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 -04001812 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001813
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001814 def test_invalid_digest_algorithm(self):
1815 """
Alex Chanb00ede22017-01-30 07:24:40 +00001816 `X509.digest` raises `ValueError` if called with an unrecognized hash
1817 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001818 """
1819 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001820 with pytest.raises(ValueError):
1821 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001822
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001823 def test_get_subject(self):
1824 """
Alex Chanb00ede22017-01-30 07:24:40 +00001825 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001826 """
1827 cert = load_certificate(FILETYPE_PEM, self.pemData)
1828 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001829 assert isinstance(subj, X509Name)
1830 assert (
1831 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001832 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1833 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001834
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001835 def test_set_subject_wrong_args(self):
1836 """
Alex Chanb00ede22017-01-30 07:24:40 +00001837 `X509.set_subject` raises a `TypeError` if called with an argument not
1838 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001839 """
1840 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001841 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001842 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001843
1844 def test_set_subject(self):
1845 """
Alex Chanb00ede22017-01-30 07:24:40 +00001846 `X509.set_subject` changes the subject of the certificate to the one
1847 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001848 """
1849 cert = X509()
1850 name = cert.get_subject()
1851 name.C = 'AU'
1852 name.O = 'Unit Tests'
1853 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001854 assert (
1855 cert.get_subject().get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001856 [(b'C', b'AU'), (b'O', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001857
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001858 def test_get_issuer(self):
1859 """
Alex Chanb00ede22017-01-30 07:24:40 +00001860 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001861 """
1862 cert = load_certificate(FILETYPE_PEM, self.pemData)
1863 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001864 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001865 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001866 assert (
1867 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001868 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1869 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001870
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001871 def test_set_issuer_wrong_args(self):
1872 """
Alex Chanb00ede22017-01-30 07:24:40 +00001873 `X509.set_issuer` raises a `TypeError` if called with an argument not
1874 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001875 """
1876 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001877 with pytest.raises(TypeError):
1878 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001879
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001880 def test_set_issuer(self):
1881 """
Alex Chanb00ede22017-01-30 07:24:40 +00001882 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001883 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001884 """
1885 cert = X509()
1886 name = cert.get_issuer()
1887 name.C = 'AU'
1888 name.O = 'Unit Tests'
1889 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001890 assert (
1891 cert.get_issuer().get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001892 [(b'C', b'AU'), (b'O', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001893
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001894 def test_get_pubkey_uninitialized(self):
1895 """
Alex Chanb00ede22017-01-30 07:24:40 +00001896 When called on a certificate with no public key, `X509.get_pubkey`
1897 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001898 """
1899 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001900 with pytest.raises(Error):
1901 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001902
Alex Gaynor7778e792016-07-03 23:38:48 -04001903 def test_set_pubkey_wrong_type(self):
1904 """
Alex Chanb00ede22017-01-30 07:24:40 +00001905 `X509.set_pubkey` raises `TypeError` when given an object of the
1906 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001907 """
1908 cert = X509()
1909 with pytest.raises(TypeError):
1910 cert.set_pubkey(object())
1911
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001912 def test_subject_name_hash(self):
1913 """
Alex Chanb00ede22017-01-30 07:24:40 +00001914 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001915 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001916 """
1917 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001918 assert cert.subject_name_hash() in [
1919 3350047874, # OpenSSL 0.9.8, MD5
1920 3278919224, # OpenSSL 1.0.0, SHA1
1921 ]
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001922
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001923 def test_get_signature_algorithm(self):
1924 """
Alex Chanb00ede22017-01-30 07:24:40 +00001925 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001926 the algorithm used to sign the certificate.
1927 """
1928 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001929 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001930
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001931 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001932 """
Alex Chanb00ede22017-01-30 07:24:40 +00001933 `X509.get_signature_algorithm` raises `ValueError` if the signature
1934 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001935 """
1936 # This certificate has been modified to indicate a bogus OID in the
1937 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001938 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001939-----BEGIN CERTIFICATE-----
1940MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1941EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1942cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1943MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1944EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1945CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1946AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1947+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1948hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1949BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1950FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1951dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1952aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1953MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1954jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1955PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1956tgI5
1957-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001958"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001959 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001960 with pytest.raises(ValueError):
1961 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001962
Alex Gaynor37726112016-07-04 09:51:32 -04001963 def test_sign_bad_pubkey_type(self):
1964 """
Alex Chanb00ede22017-01-30 07:24:40 +00001965 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001966 """
1967 cert = X509()
1968 with pytest.raises(TypeError):
1969 cert.sign(object(), b"sha256")
1970
Alex Gaynor9939ba12017-06-25 16:28:24 -04001971 def test_convert_from_cryptography(self):
1972 crypto_cert = x509.load_pem_x509_certificate(
1973 intermediate_cert_pem, backend
1974 )
1975 cert = X509.from_cryptography(crypto_cert)
1976
1977 assert isinstance(cert, X509)
1978 assert cert.get_version() == crypto_cert.version.value
1979
1980 def test_convert_from_cryptography_unsupported_type(self):
1981 with pytest.raises(TypeError):
1982 X509.from_cryptography(object())
1983
1984 def test_convert_to_cryptography_key(self):
1985 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1986 crypto_cert = cert.to_cryptography()
1987
1988 assert isinstance(crypto_cert, x509.Certificate)
1989 assert crypto_cert.version.value == cert.get_version()
1990
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001991
Alex Chan9e2a9932017-01-25 14:29:19 +00001992class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001993 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001994 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001995 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001996
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001997 def test_type(self):
1998 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001999 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002001 assert X509Store is X509StoreType
2002 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002003
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002004 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002005 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002006 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002007 """
2008 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002010 store.add_cert(cert)
2011
Alex Chanfb078d82017-04-20 11:16:15 +01002012 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
2013 def test_add_cert_wrong_args(self, cert):
2014 """
2015 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
2016 as its first argument.
2017 """
2018 store = X509Store()
2019 with pytest.raises(TypeError):
2020 store.add_cert(cert)
2021
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002022 def test_add_cert_rejects_duplicate(self):
2023 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002024 `X509Store.add_cert` raises `OpenSSL.crypto.Error` if an attempt is
2025 made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08002026 """
2027 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2028 store = X509Store()
2029 store.add_cert(cert)
Alex Chan9e2a9932017-01-25 14:29:19 +00002030 with pytest.raises(Error):
2031 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002032
2033
Alex Chanb00ede22017-01-30 07:24:40 +00002034class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05002035 """
Alex Chanb00ede22017-01-30 07:24:40 +00002036 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002037 """
2038 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
2039
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002040 def test_type(self):
2041 """
Alex Chanb00ede22017-01-30 07:24:40 +00002042 `PKCS12Type` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002043 """
Alex Chanb00ede22017-01-30 07:24:40 +00002044 assert PKCS12 is PKCS12Type
2045 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002046
Rick Deanf94096c2009-07-18 14:23:06 -05002047 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002048 """
Alex Chanb00ede22017-01-30 07:24:40 +00002049 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2050 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002051 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002052 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002053 assert None is p12.get_certificate()
2054 assert None is p12.get_privatekey()
2055 assert None is p12.get_ca_certificates()
2056 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002057
2058 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002059 """
Alex Chanb00ede22017-01-30 07:24:40 +00002060 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2061 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2062 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002063 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002064 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002065 for bad_arg in [3, PKey(), X509]:
2066 with pytest.raises(TypeError):
2067 p12.set_certificate(bad_arg)
2068 for bad_arg in [3, 'legbone', X509()]:
2069 with pytest.raises(TypeError):
2070 p12.set_privatekey(bad_arg)
2071 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2072 with pytest.raises(TypeError):
2073 p12.set_ca_certificates(bad_arg)
2074 for bad_arg in [6, ('foo', 'bar')]:
2075 with pytest.raises(TypeError):
2076 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002077
2078 def test_key_only(self):
2079 """
Alex Chanb00ede22017-01-30 07:24:40 +00002080 A `PKCS12` with only a private key can be exported using
2081 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002082 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002083 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002084 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002085 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002086 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002087 assert None is p12.get_certificate()
2088 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002089 try:
2090 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2091 except Error:
2092 # Some versions of OpenSSL will throw an exception
2093 # for this nearly useless PKCS12 we tried to generate:
2094 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2095 return
Rick Dean623ee362009-07-17 12:22:16 -05002096 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002097 assert None is p12.get_ca_certificates()
2098 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002099
2100 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2101 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002102 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002103
2104 def test_cert_only(self):
2105 """
Alex Chanb00ede22017-01-30 07:24:40 +00002106 A `PKCS12` with only a certificate can be exported using
2107 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002108 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002109 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002110 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002111 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002112 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002113 assert cert == p12.get_certificate()
2114 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002115 try:
2116 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2117 except Error:
2118 # Some versions of OpenSSL will throw an exception
2119 # for this nearly useless PKCS12 we tried to generate:
2120 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2121 return
Rick Dean623ee362009-07-17 12:22:16 -05002122 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002123 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002124
2125 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002126 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002127
2128 # Oh ho. It puts the certificate into the ca certificates list, in
2129 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2130 # that to check to see if it reconstructed the certificate we expected
2131 # it to. At some point, hopefully this will change so that
2132 # p12.get_certificate() is actually what returns the loaded
2133 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002134 assert (
2135 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002136 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002137
Alex Gaynor31287502015-09-05 16:11:27 -04002138 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2139 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002140 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002141 Generate a PKCS12 object with components from PEM. Verify that the set
2142 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002143 """
Rick Deanf94096c2009-07-18 14:23:06 -05002144 p12 = PKCS12()
2145 if cert_pem:
2146 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002147 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002148 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002149 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002150 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002151 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002152 ret = p12.set_ca_certificates(
2153 (load_certificate(FILETYPE_PEM, ca_pem),)
2154 )
Alex Chanb00ede22017-01-30 07:24:40 +00002155 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002156 if friendly_name:
2157 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002158 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002159 return p12
2160
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002161 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002162 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002163 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002164 Use openssl program to confirm three components are recoverable from a
2165 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002166 """
2167 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002168 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002169 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2170 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002171 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002172 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002173 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002174 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2175 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002176 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002177 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002178 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002179 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2180 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002181 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002182
Stephen Holsapple38482622014-04-05 20:29:34 -07002183 def verify_pkcs12_container(self, p12):
2184 """
2185 Verify that the PKCS#12 container contains the correct client
2186 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002187
2188 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002189 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002190 """
2191 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2192 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002193 assert (
2194 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002195 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002196
Rick Deanf94096c2009-07-18 14:23:06 -05002197 def test_load_pkcs12(self):
2198 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002199 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002200 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002201 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002202 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002203 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002204 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002205 pem,
2206 b"pkcs12",
2207 b"-export",
2208 b"-clcerts",
2209 b"-passout",
2210 b"pass:" + passwd
2211 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002212 p12 = load_pkcs12(p12_str, passphrase=passwd)
2213 self.verify_pkcs12_container(p12)
2214
Abraham Martinc5484ba2015-03-25 15:33:05 +00002215 def test_load_pkcs12_text_passphrase(self):
2216 """
2217 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002218 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002219 Using text as passphrase instead of bytes. DeprecationWarning expected.
2220 """
2221 pem = client_key_pem + client_cert_pem
2222 passwd = b"whatever"
2223 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2224 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002225 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002226 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002227 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002228 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002229 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002230 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002231 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002232
Abraham Martinc5484ba2015-03-25 15:33:05 +00002233 self.verify_pkcs12_container(p12)
2234
Stephen Holsapple38482622014-04-05 20:29:34 -07002235 def test_load_pkcs12_no_passphrase(self):
2236 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002237 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002238 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002239 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002240 """
2241 pem = client_key_pem + client_cert_pem
2242 p12_str = _runopenssl(
2243 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2244 p12 = load_pkcs12(p12_str)
2245 self.verify_pkcs12_container(p12)
2246
Stephen Holsapple38482622014-04-05 20:29:34 -07002247 def _dump_and_load(self, dump_passphrase, load_passphrase):
2248 """
2249 A helper method to dump and load a PKCS12 object.
2250 """
2251 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2252 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2253 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2254
Stephen Holsapple38482622014-04-05 20:29:34 -07002255 def test_load_pkcs12_null_passphrase_load_empty(self):
2256 """
2257 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002258 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002259 extracted and examined.
2260 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002261 self.verify_pkcs12_container(
2262 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002263
Stephen Holsapple38482622014-04-05 20:29:34 -07002264 def test_load_pkcs12_null_passphrase_load_null(self):
2265 """
2266 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002267 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002268 extracted and examined.
2269 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002270 self.verify_pkcs12_container(
2271 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002272
Stephen Holsapple38482622014-04-05 20:29:34 -07002273 def test_load_pkcs12_empty_passphrase_load_empty(self):
2274 """
2275 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002276 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002277 extracted and examined.
2278 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002279 self.verify_pkcs12_container(
2280 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002281
Stephen Holsapple38482622014-04-05 20:29:34 -07002282 def test_load_pkcs12_empty_passphrase_load_null(self):
2283 """
2284 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002285 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002286 extracted and examined.
2287 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002288 self.verify_pkcs12_container(
2289 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002290
Rick Deanee568302009-07-24 09:56:29 -05002291 def test_load_pkcs12_garbage(self):
2292 """
Alex Chanb00ede22017-01-30 07:24:40 +00002293 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002294 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002295 """
2296 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002297 with pytest.raises(Error) as err:
2298 load_pkcs12(b'fruit loops', passwd)
2299 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2300 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002301
Rick Deanf94096c2009-07-18 14:23:06 -05002302 def test_replace(self):
2303 """
Alex Chanb00ede22017-01-30 07:24:40 +00002304 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2305 cluster. `PKCS12.set_privatekey` replaces the private key.
2306 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002307 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002308 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2309 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2310 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002311 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002312 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002313 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002314 assert 1 == len(p12.get_ca_certificates())
2315 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002316 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002317 assert 2 == len(p12.get_ca_certificates())
2318 assert client_cert == p12.get_ca_certificates()[0]
2319 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002320
Rick Deanf94096c2009-07-18 14:23:06 -05002321 def test_friendly_name(self):
2322 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002323 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002324 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2325 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002326 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002327 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002328 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002329 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002330 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002331 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002332 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002333 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002334 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002335 # We would use the openssl program to confirm the friendly
2336 # name, but it is not possible. The pkcs12 command
2337 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002338 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002339 self.check_recovery(
2340 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2341 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002342
Rick Deanf94096c2009-07-18 14:23:06 -05002343 def test_various_empty_passphrases(self):
2344 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002345 Test that missing, None, and '' passphrases are identical for PKCS12
2346 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002347 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002348 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002349 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002350 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2351 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2352 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2353 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2354 self.check_recovery(
2355 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2356 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002357
Rick Deanf94096c2009-07-18 14:23:06 -05002358 def test_removing_ca_cert(self):
2359 """
Alex Chanb00ede22017-01-30 07:24:40 +00002360 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2361 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002362 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002363 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2364 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002365 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002366
Rick Deanf94096c2009-07-18 14:23:06 -05002367 def test_export_without_mac(self):
2368 """
Alex Chanb00ede22017-01-30 07:24:40 +00002369 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002370 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002371 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002372 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002373 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002374 self.check_recovery(
2375 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002376 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002377
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002378 def test_load_without_mac(self):
2379 """
2380 Loading a PKCS12 without a MAC does something other than crash.
2381 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002382 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002383 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2384 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002385 try:
2386 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2387 # The person who generated this PCKS12 should be flogged,
2388 # or better yet we should have a means to determine
2389 # whether a PCKS12 had a MAC that was verified.
2390 # Anyway, libopenssl chooses to allow it, so the
2391 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002392 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002393 except Error:
2394 # Failing here with an exception is preferred as some openssl
2395 # versions do.
2396 pass
Rick Dean623ee362009-07-17 12:22:16 -05002397
Rick Dean25bcc1f2009-07-20 11:53:13 -05002398 def test_zero_len_list_for_ca(self):
2399 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002400 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002401 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002402 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002403 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002404 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002405 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002406 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2407 self.check_recovery(
2408 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2409 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002410
Rick Deanf94096c2009-07-18 14:23:06 -05002411 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002412 """
Alex Chanb00ede22017-01-30 07:24:40 +00002413 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002414 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002415 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002416 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002417 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002418 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002419
Abraham Martinc5484ba2015-03-25 15:33:05 +00002420 def test_export_without_bytes(self):
2421 """
Alex Chanb00ede22017-01-30 07:24:40 +00002422 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002423 """
2424 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2425
Alex Chanb00ede22017-01-30 07:24:40 +00002426 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002427 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002428 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002429 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002430 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002431 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002432 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002433 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002434 dumped_p12,
2435 key=server_key_pem,
2436 cert=server_cert_pem,
2437 passwd=b"randomtext"
2438 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002439
Rick Deanf94096c2009-07-18 14:23:06 -05002440 def test_key_cert_mismatch(self):
2441 """
Alex Chanb00ede22017-01-30 07:24:40 +00002442 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002443 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002444 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002445 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002446 with pytest.raises(Error):
2447 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002448
2449
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002450# These quoting functions taken directly from Twisted's twisted.python.win32.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002451_cmdLineQuoteRe = re.compile(br'(\\*)"')
2452_cmdLineQuoteRe2 = re.compile(br'(\\+)\Z')
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002453
2454
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002455def cmdLineQuote(s):
2456 """
2457 Internal method for quoting a single command-line argument.
2458
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002459 See http://www.perlmonks.org/?node_id=764004
2460
Jonathan Ballet648875f2011-07-16 14:14:58 +09002461 :type: :py:obj:`str`
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002462 :param s: A single unquoted string to quote for something that is expecting
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002463 cmd.exe-style quoting
2464
Jonathan Ballet648875f2011-07-16 14:14:58 +09002465 :rtype: :py:obj:`str`
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002466 :return: A cmd.exe-style quoted string
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002467 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002468 s = _cmdLineQuoteRe2.sub(br"\1\1", _cmdLineQuoteRe.sub(br'\1\1\\"', s))
2469 return b'"' + s + b'"'
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002470
2471
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002472def quoteArguments(arguments):
2473 """
2474 Quote an iterable of command-line arguments for passing to CreateProcess or
Alex Gaynor791212d2015-09-05 15:46:08 -04002475 a similar API. This allows the list passed to
2476 :py:obj:`reactor.spawnProcess` to match the child process's
2477 :py:obj:`sys.argv` properly.
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002478
Jonathan Ballet648875f2011-07-16 14:14:58 +09002479 :type arguments: :py:obj:`iterable` of :py:obj:`str`
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002480 :param arguments: An iterable of unquoted arguments to quote
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002481
Jonathan Ballet648875f2011-07-16 14:14:58 +09002482 :rtype: :py:obj:`str`
Alex Gaynor791212d2015-09-05 15:46:08 -04002483 :return: A space-delimited string containing quoted versions of
2484 :py:obj:`arguments`
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002485 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002486 return b' '.join(map(cmdLineQuote, arguments))
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002487
2488
Rick Dean4c9ad612009-07-17 15:05:22 -05002489def _runopenssl(pem, *args):
2490 """
2491 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002492 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002493 """
Jean-Paul Calderone038de952009-08-21 12:16:06 -04002494 if os.name == 'posix':
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002495 command = b"openssl " + b" ".join([
Alex Gaynor85b49702015-09-05 16:30:59 -04002496 (b"'" + arg.replace(b"'", b"'\\''") + b"'")
2497 for arg in args
2498 ])
Rick Dean55d1ce62009-08-13 17:40:24 -05002499 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002500 command = b"openssl " + quoteArguments(args)
2501 proc = Popen(native(command), shell=True, stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002502 proc.stdin.write(pem)
2503 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002504 output = proc.stdout.read()
2505 proc.stdout.close()
2506 proc.wait()
2507 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002508
2509
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002510class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002511 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002512 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002513 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002514 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002515 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002516 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002517 """
2518 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002519
2520 assert True is key._only_public
2521 assert 2048 == key.bits()
2522 assert TYPE_RSA == key.type()
2523
2524 def test_invalid_type(self):
2525 """
2526 load_publickey doesn't support FILETYPE_TEXT.
2527 """
2528 with pytest.raises(ValueError):
2529 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2530
2531 def test_invalid_key_format(self):
2532 """
2533 load_publickey explodes on incorrect keys.
2534 """
2535 with pytest.raises(Error):
2536 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2537
2538 def test_tolerates_unicode_strings(self):
2539 """
2540 load_publickey works with text strings, not just bytes.
2541 """
2542 serialized = cleartextPublicKeyPEM.decode('ascii')
2543 key = load_publickey(FILETYPE_PEM, serialized)
2544 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2545
2546 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002547
2548
Alex Chanb00ede22017-01-30 07:24:40 +00002549class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002550 """
Alex Chanb00ede22017-01-30 07:24:40 +00002551 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002552 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002553
2554 def test_load_privatekey_invalid_format(self):
2555 """
Alex Chanb00ede22017-01-30 07:24:40 +00002556 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002557 """
Alex Chanb00ede22017-01-30 07:24:40 +00002558 with pytest.raises(ValueError):
2559 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002560
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002561 def test_load_privatekey_invalid_passphrase_type(self):
2562 """
Alex Chanb00ede22017-01-30 07:24:40 +00002563 `load_privatekey` raises `TypeError` if passed a passphrase that is
2564 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002565 """
Alex Chanb00ede22017-01-30 07:24:40 +00002566 with pytest.raises(TypeError):
2567 load_privatekey(
2568 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002569
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002570 def test_load_privatekey_wrongPassphrase(self):
2571 """
Alex Chanb00ede22017-01-30 07:24:40 +00002572 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2573 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002574 """
Alex Chanb00ede22017-01-30 07:24:40 +00002575 with pytest.raises(Error) as err:
2576 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2577 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002578
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002579 def test_load_privatekey_passphraseWrongType(self):
2580 """
Alex Chanb00ede22017-01-30 07:24:40 +00002581 `load_privatekey` raises `ValueError` when it is passeda passphrase
2582 with a private key encoded in a format, that doesn't support
2583 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002584 """
2585 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2586 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002587 with pytest.raises(ValueError):
2588 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002589
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002590 def test_load_privatekey_passphrase(self):
2591 """
Alex Chanb00ede22017-01-30 07:24:40 +00002592 `load_privatekey` can create a `PKey` object from an encrypted PEM
2593 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002594 """
2595 key = load_privatekey(
2596 FILETYPE_PEM, encryptedPrivateKeyPEM,
2597 encryptedPrivateKeyPEMPassphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002598 assert isinstance(key, PKeyType)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002599
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002600 def test_load_privatekey_passphrase_exception(self):
2601 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002602 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002603 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002604 """
2605 def cb(ignored):
2606 raise ArithmeticError
2607
Alex Gaynor791212d2015-09-05 15:46:08 -04002608 with pytest.raises(ArithmeticError):
2609 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002610
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002611 def test_load_privatekey_wrongPassphraseCallback(self):
2612 """
Alex Chanb00ede22017-01-30 07:24:40 +00002613 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002614 is passed an encrypted PEM and a passphrase callback which returns an
2615 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002616 """
2617 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002618
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002619 def cb(*a):
2620 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002621 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002622 with pytest.raises(Error) as err:
2623 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2624 assert called
2625 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002626
2627 def test_load_privatekey_passphraseCallback(self):
2628 """
Alex Chanb00ede22017-01-30 07:24:40 +00002629 `load_privatekey` can create a `PKey` object from an encrypted PEM
2630 string if given a passphrase callback which returns the correct
2631 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002632 """
2633 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002634
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002635 def cb(writing):
2636 called.append(writing)
2637 return encryptedPrivateKeyPEMPassphrase
2638 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002639 assert isinstance(key, PKeyType)
2640 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002641
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002642 def test_load_privatekey_passphrase_wrong_return_type(self):
2643 """
Alex Chanb00ede22017-01-30 07:24:40 +00002644 `load_privatekey` raises `ValueError` if the passphrase callback
2645 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002646 """
Alex Chanb00ede22017-01-30 07:24:40 +00002647 with pytest.raises(ValueError):
2648 load_privatekey(
2649 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002650
Alex Chanfb078d82017-04-20 11:16:15 +01002651 def test_dump_privatekey_wrong_args(self):
2652 """
2653 `dump_privatekey` raises `TypeError` if called with a `cipher`
2654 argument but no `passphrase` argument.
2655 """
2656 key = PKey()
2657 key.generate_key(TYPE_RSA, 512)
2658 with pytest.raises(TypeError):
2659 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2660
Paul Kehrercded9932017-06-29 18:43:42 -05002661 def test_dump_privatekey_not_rsa_key(self):
2662 """
2663 `dump_privatekey` raises `TypeError` if called with a key that is
2664 not RSA.
2665 """
2666 key = PKey()
2667 key.generate_key(TYPE_DSA, 512)
2668 with pytest.raises(TypeError):
2669 dump_privatekey(FILETYPE_TEXT, key)
2670
2671 def test_dump_privatekey_invalid_pkey(self):
2672 with pytest.raises(TypeError):
2673 dump_privatekey(FILETYPE_TEXT, object())
2674
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002675 def test_dump_privatekey_unknown_cipher(self):
2676 """
Alex Chanb00ede22017-01-30 07:24:40 +00002677 `dump_privatekey` raises `ValueError` if called with an unrecognized
2678 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002679 """
2680 key = PKey()
2681 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002682 with pytest.raises(ValueError):
2683 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002684
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002685 def test_dump_privatekey_invalid_passphrase_type(self):
2686 """
Alex Chanb00ede22017-01-30 07:24:40 +00002687 `dump_privatekey` raises `TypeError` if called with a passphrase which
2688 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002689 """
2690 key = PKey()
2691 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002692 with pytest.raises(TypeError):
2693 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002694
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002695 def test_dump_privatekey_invalid_filetype(self):
2696 """
Alex Chanb00ede22017-01-30 07:24:40 +00002697 `dump_privatekey` raises `ValueError` if called with an unrecognized
2698 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002699 """
2700 key = PKey()
2701 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002702 with pytest.raises(ValueError):
2703 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002704
Alex Chanb00ede22017-01-30 07:24:40 +00002705 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002706 """
Alex Chanb00ede22017-01-30 07:24:40 +00002707 `crypto.load_privatekey` should raise an error when the passphrase
2708 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002709 """
2710 def cb(ignored):
2711 return "a" * 1025
2712
Alex Gaynor791212d2015-09-05 15:46:08 -04002713 with pytest.raises(ValueError):
2714 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002715
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002716 def test_dump_privatekey_passphrase(self):
2717 """
Alex Chanb00ede22017-01-30 07:24:40 +00002718 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002719 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002720 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002721 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002722 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002723 assert isinstance(pem, binary_type)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002724 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002725 assert isinstance(loadedKey, PKeyType)
2726 assert loadedKey.type() == key.type()
2727 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002728
Alex Chanb00ede22017-01-30 07:24:40 +00002729 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002730 """
Alex Chanb00ede22017-01-30 07:24:40 +00002731 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2732 with a private key encoded in a format, that doesn't support
2733 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002734 """
2735 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002736 with pytest.raises(ValueError):
2737 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002738
Rick Dean5b7b6372009-04-01 11:34:06 -05002739 def test_dump_certificate(self):
2740 """
Alex Chanb00ede22017-01-30 07:24:40 +00002741 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002742 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002743 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002744 cert = load_certificate(FILETYPE_PEM, pemData)
2745 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002746 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002747 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002748 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002749 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002750 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2751 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002752 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002753 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002754 good_text = _runopenssl(
2755 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002756 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002757
Alex Gaynor37726112016-07-04 09:51:32 -04002758 def test_dump_certificate_bad_type(self):
2759 """
Alex Chanb00ede22017-01-30 07:24:40 +00002760 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002761 a bad type.
2762 """
2763 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2764 with pytest.raises(ValueError):
2765 dump_certificate(object(), cert)
2766
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002767 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002768 """
Alex Chanb00ede22017-01-30 07:24:40 +00002769 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002770 """
2771 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002772 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002773 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002774 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002775
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002776 def test_dump_privatekey_asn1(self):
2777 """
Alex Chanb00ede22017-01-30 07:24:40 +00002778 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002779 """
2780 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2781 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2782
Rick Dean5b7b6372009-04-01 11:34:06 -05002783 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002784 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002785 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002786 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002787 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2788 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002789 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002790
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002791 def test_dump_privatekey_text(self):
2792 """
Alex Chanb00ede22017-01-30 07:24:40 +00002793 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002794 """
2795 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2796 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2797
Rick Dean5b7b6372009-04-01 11:34:06 -05002798 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002799 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002800 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002801
Cory Benfield6492f7c2015-10-27 16:57:58 +09002802 def test_dump_publickey_pem(self):
2803 """
Cory Benfield11c10192015-10-27 17:23:03 +09002804 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002805 """
2806 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2807 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002808 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002809
2810 def test_dump_publickey_asn1(self):
2811 """
Cory Benfield11c10192015-10-27 17:23:03 +09002812 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002813 """
2814 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2815 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2816 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2817 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002818 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002819
Cory Benfielde02c7d82015-10-27 17:34:49 +09002820 def test_dump_publickey_invalid_type(self):
2821 """
2822 dump_publickey doesn't support FILETYPE_TEXT.
2823 """
2824 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2825
2826 with pytest.raises(ValueError):
2827 dump_publickey(FILETYPE_TEXT, key)
2828
Rick Dean5b7b6372009-04-01 11:34:06 -05002829 def test_dump_certificate_request(self):
2830 """
Alex Chanb00ede22017-01-30 07:24:40 +00002831 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002832 """
Alex Gaynor31287502015-09-05 16:11:27 -04002833 req = load_certificate_request(
2834 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002835 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002836 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002837 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002838 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002839 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002840 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2841 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002842 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002843 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002844 good_text = _runopenssl(
2845 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002846 assert dumped_text == good_text
2847 with pytest.raises(ValueError):
2848 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002849
Alex Chanb00ede22017-01-30 07:24:40 +00002850 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002851 """
Alex Chanb00ede22017-01-30 07:24:40 +00002852 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002853 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002854 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002855 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002856 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002857
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002858 def cb(writing):
2859 called.append(writing)
2860 return passphrase
2861 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002862 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002863 assert isinstance(pem, binary_type)
2864 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002865 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002866 assert isinstance(loadedKey, PKeyType)
2867 assert loadedKey.type() == key.type()
2868 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002869
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002870 def test_dump_privatekey_passphrase_exception(self):
2871 """
Alex Chanb00ede22017-01-30 07:24:40 +00002872 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002873 by the passphrase callback.
2874 """
2875 def cb(ignored):
2876 raise ArithmeticError
2877
2878 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002879 with pytest.raises(ArithmeticError):
2880 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002881
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002882 def test_dump_privatekey_passphraseCallbackLength(self):
2883 """
Alex Chanb00ede22017-01-30 07:24:40 +00002884 `crypto.dump_privatekey` should raise an error when the passphrase
2885 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002886 """
2887 def cb(ignored):
2888 return "a" * 1025
2889
2890 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002891 with pytest.raises(ValueError):
2892 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002893
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002894 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002895 """
Alex Chanb00ede22017-01-30 07:24:40 +00002896 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2897 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002898 """
2899 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002900 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002901
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002902 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002903 """
Alex Chanb00ede22017-01-30 07:24:40 +00002904 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2905 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002906 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002907 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002908 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002909
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002910 def test_load_pkcs7_data_invalid(self):
2911 """
Alex Chanb00ede22017-01-30 07:24:40 +00002912 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002913 """
Alex Chanb00ede22017-01-30 07:24:40 +00002914 with pytest.raises(Error):
2915 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002916
Alex Gaynor09a386e2016-07-03 09:32:44 -04002917 def test_load_pkcs7_type_invalid(self):
2918 """
Alex Chanb00ede22017-01-30 07:24:40 +00002919 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002920 """
2921 with pytest.raises(ValueError):
2922 load_pkcs7_data(object(), b"foo")
2923
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002924
Alex Chan9e2a9932017-01-25 14:29:19 +00002925class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002926 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002927 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002928 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002929
Alex Chan9e2a9932017-01-25 14:29:19 +00002930 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002931 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002932 If the file type passed to `load_certificate_request` is neither
2933 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002934 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002935 with pytest.raises(ValueError):
2936 load_certificate_request(object(), b"")
2937 with pytest.raises(ValueError):
2938 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002939
Alex Gaynor37726112016-07-04 09:51:32 -04002940 def test_bad_certificate(self):
2941 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002942 If the bytes passed to `load_certificate` are not a valid certificate,
2943 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002944 """
2945 with pytest.raises(Error):
2946 load_certificate(FILETYPE_ASN1, b"lol")
2947
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002948
Alex Chanb00ede22017-01-30 07:24:40 +00002949class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002950 """
Alex Chanb00ede22017-01-30 07:24:40 +00002951 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002952 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002953
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002954 def test_type(self):
2955 """
Alex Chanb00ede22017-01-30 07:24:40 +00002956 `PKCS7` is a type object.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002957 """
Alex Chanb00ede22017-01-30 07:24:40 +00002958 assert isinstance(PKCS7, type)
2959 assert PKCS7Type.__name__ == 'PKCS7'
2960 assert PKCS7 is PKCS7Type
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002961
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002962 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002963 """
Alex Chanb00ede22017-01-30 07:24:40 +00002964 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2965 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002966 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002967 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002968 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002969
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002970 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002971 """
Alex Chanb00ede22017-01-30 07:24:40 +00002972 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2973 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002974 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002975 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002976 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002977
Alex Chanb00ede22017-01-30 07:24:40 +00002978 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002979 """
Alex Chanb00ede22017-01-30 07:24:40 +00002980 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002981 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002982 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002983 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002984 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002985
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002986 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002987 """
Alex Chanb00ede22017-01-30 07:24:40 +00002988 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2989 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002990 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002991 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002992 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002993
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002994 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002995 """
Alex Chanb00ede22017-01-30 07:24:40 +00002996 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002997 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002998 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002999 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00003000 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04003001
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04003002 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04003003 """
Alex Gaynor791212d2015-09-05 15:46:08 -04003004 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00003005 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04003006 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04003007 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00003008 with pytest.raises(AttributeError):
3009 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04003010
3011
Alex Chanb00ede22017-01-30 07:24:40 +00003012class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003013 """
Alex Chanb00ede22017-01-30 07:24:40 +00003014 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003015 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003016
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04003017 def signable(self):
3018 """
Alex Chanb00ede22017-01-30 07:24:40 +00003019 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04003020 """
3021 return NetscapeSPKI()
3022
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003023 def test_type(self):
3024 """
Alex Chanb00ede22017-01-30 07:24:40 +00003025 `NetscapeSPKI` and `NetscapeSPKIType` refer to the same type object
3026 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003027 """
Alex Chanb00ede22017-01-30 07:24:40 +00003028 assert NetscapeSPKI is NetscapeSPKIType
3029 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003030
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003031 def test_construction(self):
3032 """
Alex Chanb00ede22017-01-30 07:24:40 +00003033 `NetscapeSPKI` returns an instance of `NetscapeSPKIType`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003034 """
3035 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00003036 assert isinstance(nspki, NetscapeSPKIType)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003037
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04003038 def test_invalid_attribute(self):
3039 """
Alex Chanb00ede22017-01-30 07:24:40 +00003040 Accessing a non-existent attribute of a `NetscapeSPKI` instance
3041 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04003042 """
3043 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00003044 with pytest.raises(AttributeError):
3045 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04003046
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003047 def test_b64_encode(self):
3048 """
Alex Chanb00ede22017-01-30 07:24:40 +00003049 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003050 """
3051 nspki = NetscapeSPKI()
3052 blob = nspki.b64_encode()
Alex Chanb00ede22017-01-30 07:24:40 +00003053 assert isinstance(blob, binary_type)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04003054
3055
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003056class TestRevoked(object):
3057 """
Alex Chandeec9342016-12-19 22:00:38 +00003058 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003059 """
3060 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
3061 """
3062 The get_reason method on the Revoked class checks to see if the
3063 extension is NID_crl_reason and should skip it otherwise. This test
3064 loads a CRL with extensions it should ignore.
3065 """
3066 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3067 revoked = crl.get_revoked()
3068 reason = revoked[1].get_reason()
3069 assert reason == b'Unspecified'
3070
3071 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3072 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3073 revoked = crl.get_revoked()
3074 revoked[1].set_reason(None)
3075 reason = revoked[1].get_reason()
3076 assert reason is None
3077
Rick Dean536ba022009-07-24 23:57:27 -05003078 def test_construction(self):
3079 """
Alex Chandeec9342016-12-19 22:00:38 +00003080 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3081 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003082 """
3083 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003084 assert isinstance(revoked, Revoked)
3085 assert type(revoked) == Revoked
3086 assert revoked.get_serial() == b'00'
3087 assert revoked.get_rev_date() is None
3088 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003089
Rick Dean536ba022009-07-24 23:57:27 -05003090 def test_serial(self):
3091 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003092 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003093 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003094 """
3095 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003096 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003097 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003098 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003099 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003100
Alex Gaynore7f51982016-09-11 11:48:14 -04003101 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003102 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003103 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003104
Alex Chandeec9342016-12-19 22:00:38 +00003105 with pytest.raises(ValueError):
3106 revoked.set_serial(b'pqrst')
3107 with pytest.raises(TypeError):
3108 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003109
Rick Dean536ba022009-07-24 23:57:27 -05003110 def test_date(self):
3111 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003112 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003113 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003114 """
3115 revoked = Revoked()
3116 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003117 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003118
Alex Gaynore7f51982016-09-11 11:48:14 -04003119 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003120 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003121 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003122 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003123 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003124
Rick Dean6385faf2009-07-26 00:07:47 -05003125 def test_reason(self):
3126 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003127 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003128 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3129 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003130 """
3131 revoked = Revoked()
3132 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003133 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003134 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003135 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003136 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003137 assert (
3138 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003139 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003140 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003141
3142 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003143 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003144
Alex Chanfb078d82017-04-20 11:16:15 +01003145 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3146 def test_set_reason_wrong_args(self, reason):
3147 """
3148 `Revoked.set_reason` raises `TypeError` if called with an argument
3149 which is neither `None` nor a byte string.
3150 """
3151 revoked = Revoked()
3152 with pytest.raises(TypeError):
3153 revoked.set_reason(reason)
3154
Alex Chandeec9342016-12-19 22:00:38 +00003155 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003156 """
Alex Chandeec9342016-12-19 22:00:38 +00003157 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3158 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003159 """
3160 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003161 with pytest.raises(ValueError):
3162 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003163
3164
Alex Chan7be83a52017-01-24 15:19:29 +00003165class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003166 """
Alex Chan7be83a52017-01-24 15:19:29 +00003167 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003168 """
3169 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3170 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3171
Dan Sully44e767a2016-06-04 18:05:27 -07003172 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3173 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3174 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3175 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3176 intermediate_server_cert = load_certificate(
3177 FILETYPE_PEM, intermediate_server_cert_pem)
3178 intermediate_server_key = load_privatekey(
3179 FILETYPE_PEM, intermediate_server_key_pem)
3180
Rick Dean536ba022009-07-24 23:57:27 -05003181 def test_construction(self):
3182 """
Alex Chan7be83a52017-01-24 15:19:29 +00003183 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003184 that it is empty
3185 """
3186 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003187 assert isinstance(crl, CRL)
3188 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003189
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003190 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003191 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003192 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003193 """
3194 crl = CRL()
3195 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003196 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003197 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003198 revoked.set_serial(b'3ab')
3199 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003200 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003201 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003202
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003203 def test_export_pem(self):
3204 """
3205 If not passed a format, ``CRL.export`` returns a "PEM" format string
3206 representing a serial number, a revoked reason, and certificate issuer
3207 information.
3208 """
3209 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003210 # PEM format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003211 dumped_crl = crl.export(
3212 self.cert, self.pkey, days=20, digest=b"sha256"
3213 )
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003214 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003215
3216 # These magic values are based on the way the CRL above was constructed
3217 # and with what certificate it was exported.
Alex Gaynore7f51982016-09-11 11:48:14 -04003218 text.index(b'Serial Number: 03AB')
3219 text.index(b'Superseded')
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003220 text.index(
Alex Gaynore7f51982016-09-11 11:48:14 -04003221 b'Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA'
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003222 )
3223
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003224 def test_export_der(self):
3225 """
3226 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3227 "DER" format string representing a serial number, a revoked reason, and
3228 certificate issuer information.
3229 """
3230 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003231
3232 # DER format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003233 dumped_crl = crl.export(
3234 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3235 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003236 text = _runopenssl(
3237 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
3238 )
Alex Gaynore7f51982016-09-11 11:48:14 -04003239 text.index(b'Serial Number: 03AB')
3240 text.index(b'Superseded')
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003241 text.index(
Alex Gaynore7f51982016-09-11 11:48:14 -04003242 b'Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA'
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003243 )
3244
Alex Gaynore466bc92017-07-06 23:43:47 -04003245 # Flaky because we compare the output of running commands which sometimes
3246 # varies by 1 second
3247 @flaky.flaky
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003248 def test_export_text(self):
3249 """
3250 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3251 text format string like the one produced by the openssl command line
3252 tool.
3253 """
3254 crl = self._get_crl()
3255
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003256 dumped_crl = crl.export(
3257 self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
3258 )
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003259 text = _runopenssl(
3260 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
3261 )
Rick Dean536ba022009-07-24 23:57:27 -05003262
3263 # text format
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003264 dumped_text = crl.export(
3265 self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
3266 )
Alex Chan7be83a52017-01-24 15:19:29 +00003267 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003268
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003269 def test_export_custom_digest(self):
3270 """
3271 If passed the name of a digest function, ``CRL.export`` uses a
3272 signature algorithm based on that digest function.
3273 """
3274 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003275 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003276 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003277 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003278
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003279 def test_export_md5_digest(self):
3280 """
3281 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3282 not emit a deprecation warning.
3283 """
3284 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003285 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003286 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003287 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003288 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3289 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003290 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003291
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003292 def test_export_default_digest(self):
3293 """
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003294 If not passed the name of a digest function, ``CRL.export`` raises a
3295 ``TypeError``.
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003296 """
3297 crl = self._get_crl()
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003298 with pytest.raises(TypeError):
3299 crl.export(self.cert, self.pkey)
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003300
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003301 def test_export_invalid(self):
3302 """
Alex Chan7be83a52017-01-24 15:19:29 +00003303 If `CRL.export` is used with an uninitialized `X509` instance,
3304 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003305 """
3306 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003307 with pytest.raises(Error):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003308 crl.export(X509(), PKey(), digest=b"sha256")
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003309
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003310 def test_add_revoked_keyword(self):
3311 """
Alex Chan7be83a52017-01-24 15:19:29 +00003312 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003313 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003314 """
3315 crl = CRL()
3316 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003317 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003318 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003319 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003320 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003321
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003322 def test_export_wrong_args(self):
3323 """
Alex Chan7be83a52017-01-24 15:19:29 +00003324 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003325 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003326 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003327 """
3328 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003329 with pytest.raises(TypeError):
3330 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3331 with pytest.raises(TypeError):
3332 crl.export(self.cert, None, FILETYPE_PEM, 10)
3333 with pytest.raises(TypeError):
3334 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003335 with pytest.raises(TypeError):
3336 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003337
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003338 def test_export_unknown_filetype(self):
3339 """
Alex Chan7be83a52017-01-24 15:19:29 +00003340 Calling `OpenSSL.CRL.export` with a file type other than
3341 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3342 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003343 """
3344 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003345 with pytest.raises(ValueError):
Alex Gaynor173e4ba2017-06-30 08:01:12 -07003346 crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003347
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003348 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003349 """
Alex Chan7be83a52017-01-24 15:19:29 +00003350 Calling `OpenSSL.CRL.export` with an unsupported digest results
3351 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003352 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003353 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003354 with pytest.raises(ValueError):
3355 crl.export(
3356 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003357
Rick Dean536ba022009-07-24 23:57:27 -05003358 def test_get_revoked(self):
3359 """
Alex Chan7be83a52017-01-24 15:19:29 +00003360 Use python to create a simple CRL with two revocations. Get back the
3361 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003362 """
3363 crl = CRL()
3364
3365 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003366 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003367 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003368 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003369 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003370 revoked.set_serial(b'100')
3371 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003372 crl.add_revoked(revoked)
3373
3374 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003375 assert len(revs) == 2
3376 assert type(revs[0]) == Revoked
3377 assert type(revs[1]) == Revoked
3378 assert revs[0].get_serial() == b'03AB'
3379 assert revs[1].get_serial() == b'0100'
3380 assert revs[0].get_rev_date() == now
3381 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003382
Rick Dean536ba022009-07-24 23:57:27 -05003383 def test_load_crl(self):
3384 """
Alex Chan7be83a52017-01-24 15:19:29 +00003385 Load a known CRL and inspect its revocations. Both EM and DER formats
3386 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003387 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003388 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003389 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003390 assert len(revs) == 2
3391 assert revs[0].get_serial() == b'03AB'
3392 assert revs[0].get_reason() is None
3393 assert revs[1].get_serial() == b'0100'
3394 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003395
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003396 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003397 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003398 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003399 assert len(revs) == 2
3400 assert revs[0].get_serial() == b'03AB'
3401 assert revs[0].get_reason() is None
3402 assert revs[1].get_serial() == b'0100'
3403 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003404
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003405 def test_load_crl_bad_filetype(self):
3406 """
Alex Chan7be83a52017-01-24 15:19:29 +00003407 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3408 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003409 """
Alex Chan7be83a52017-01-24 15:19:29 +00003410 with pytest.raises(ValueError):
3411 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003412
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003413 def test_load_crl_bad_data(self):
3414 """
Alex Chan7be83a52017-01-24 15:19:29 +00003415 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3416 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003417 """
Alex Chan7be83a52017-01-24 15:19:29 +00003418 with pytest.raises(Error):
3419 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003420
Dan Sully44e767a2016-06-04 18:05:27 -07003421 def test_get_issuer(self):
3422 """
Alex Chan7be83a52017-01-24 15:19:29 +00003423 Load a known CRL and assert its issuer's common name is what we expect
3424 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003425 """
3426 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003427 assert isinstance(crl.get_issuer(), X509Name)
3428 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003429
Dominic Chenf05b2122015-10-13 16:32:35 +00003430 def test_dump_crl(self):
3431 """
3432 The dumped CRL matches the original input.
3433 """
3434 crl = load_crl(FILETYPE_PEM, crlData)
3435 buf = dump_crl(FILETYPE_PEM, crl)
3436 assert buf == crlData
3437
Dan Sully44e767a2016-06-04 18:05:27 -07003438 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3439 """
3440 Create a CRL.
3441
3442 :param list[X509] certs: A list of certificates to revoke.
3443 :rtype: CRL
3444 """
3445 crl = CRL()
3446 for cert in certs:
3447 revoked = Revoked()
3448 # FIXME: This string splicing is an unfortunate implementation
3449 # detail that has been reported in
3450 # https://github.com/pyca/pyopenssl/issues/258
3451 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3452 revoked.set_serial(serial)
3453 revoked.set_reason(b'unspecified')
3454 revoked.set_rev_date(b'20140601000000Z')
3455 crl.add_revoked(revoked)
3456 crl.set_version(1)
3457 crl.set_lastUpdate(b'20140601000000Z')
3458 crl.set_nextUpdate(b'20180601000000Z')
3459 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3460 return crl
3461
3462 def test_verify_with_revoked(self):
3463 """
Alex Chan7be83a52017-01-24 15:19:29 +00003464 `verify_certificate` raises error when an intermediate certificate is
3465 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003466 """
3467 store = X509Store()
3468 store.add_cert(self.root_cert)
3469 store.add_cert(self.intermediate_cert)
3470 root_crl = self._make_test_crl(
3471 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3472 intermediate_crl = self._make_test_crl(
3473 self.intermediate_cert, self.intermediate_key, certs=[])
3474 store.add_crl(root_crl)
3475 store.add_crl(intermediate_crl)
3476 store.set_flags(
3477 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3478 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003479 with pytest.raises(X509StoreContextError) as err:
3480 store_ctx.verify_certificate()
3481 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003482
3483 def test_verify_with_missing_crl(self):
3484 """
Alex Chan7be83a52017-01-24 15:19:29 +00003485 `verify_certificate` raises error when an intermediate certificate's
3486 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003487 """
3488 store = X509Store()
3489 store.add_cert(self.root_cert)
3490 store.add_cert(self.intermediate_cert)
3491 root_crl = self._make_test_crl(
3492 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3493 store.add_crl(root_crl)
3494 store.set_flags(
3495 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3496 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003497 with pytest.raises(X509StoreContextError) as err:
3498 store_ctx.verify_certificate()
3499 assert err.value.args[0][2] == 'unable to get certificate CRL'
3500 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003501
Paul Kehrer41c10242017-06-29 18:24:17 -05003502 def test_convert_from_cryptography(self):
3503 crypto_crl = x509.load_pem_x509_crl(crlData, backend)
3504 crl = CRL.from_cryptography(crypto_crl)
3505 assert isinstance(crl, CRL)
3506
3507 def test_convert_from_cryptography_unsupported_type(self):
3508 with pytest.raises(TypeError):
3509 CRL.from_cryptography(object())
3510
3511 def test_convert_to_cryptography_key(self):
3512 crl = load_crl(FILETYPE_PEM, crlData)
3513 crypto_crl = crl.to_cryptography()
3514 assert isinstance(crypto_crl, x509.CertificateRevocationList)
3515
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003516
Alex Chan7be83a52017-01-24 15:19:29 +00003517class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003518 """
Alex Chan7be83a52017-01-24 15:19:29 +00003519 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003520 """
3521 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3522 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003523 intermediate_server_cert = load_certificate(
3524 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003525
3526 def test_valid(self):
3527 """
Alex Chan7be83a52017-01-24 15:19:29 +00003528 `verify_certificate` returns ``None`` when called with a certificate
3529 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003530 """
3531 store = X509Store()
3532 store.add_cert(self.root_cert)
3533 store.add_cert(self.intermediate_cert)
3534 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003535 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003536
3537 def test_reuse(self):
3538 """
Alex Chan7be83a52017-01-24 15:19:29 +00003539 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003540 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003541 """
3542 store = X509Store()
3543 store.add_cert(self.root_cert)
3544 store.add_cert(self.intermediate_cert)
3545 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003546 assert store_ctx.verify_certificate() is None
3547 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003548
3549 def test_trusted_self_signed(self):
3550 """
Alex Chan7be83a52017-01-24 15:19:29 +00003551 `verify_certificate` returns ``None`` when called with a self-signed
3552 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003553 """
3554 store = X509Store()
3555 store.add_cert(self.root_cert)
3556 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003557 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003558
3559 def test_untrusted_self_signed(self):
3560 """
Alex Chan7be83a52017-01-24 15:19:29 +00003561 `verify_certificate` raises error when a self-signed certificate is
3562 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003563 """
3564 store = X509Store()
3565 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003566 with pytest.raises(X509StoreContextError) as exc:
3567 store_ctx.verify_certificate()
3568
3569 assert exc.value.args[0][2] == 'self signed certificate'
3570 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003571
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003572 def test_invalid_chain_no_root(self):
3573 """
Alex Chan7be83a52017-01-24 15:19:29 +00003574 `verify_certificate` raises error when a root certificate is missing
3575 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003576 """
3577 store = X509Store()
3578 store.add_cert(self.intermediate_cert)
3579 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003580
3581 with pytest.raises(X509StoreContextError) as exc:
3582 store_ctx.verify_certificate()
3583
3584 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3585 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003586
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003587 def test_invalid_chain_no_intermediate(self):
3588 """
Alex Chan7be83a52017-01-24 15:19:29 +00003589 `verify_certificate` raises error when an intermediate certificate is
3590 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003591 """
3592 store = X509Store()
3593 store.add_cert(self.root_cert)
3594 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003595
Alex Gaynor85b49702015-09-05 16:30:59 -04003596 with pytest.raises(X509StoreContextError) as exc:
3597 store_ctx.verify_certificate()
3598
3599 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3600 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003601
Stephen Holsapple46a09252015-02-12 14:45:43 -08003602 def test_modification_pre_verify(self):
3603 """
Alex Chan7be83a52017-01-24 15:19:29 +00003604 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003605 instantiation.
3606 """
3607 store_bad = X509Store()
3608 store_bad.add_cert(self.intermediate_cert)
3609 store_good = X509Store()
3610 store_good.add_cert(self.root_cert)
3611 store_good.add_cert(self.intermediate_cert)
3612 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003613
3614 with pytest.raises(X509StoreContextError) as exc:
3615 store_ctx.verify_certificate()
3616
3617 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3618 assert exc.value.certificate.get_subject().CN == 'intermediate'
3619
Stephen Holsapple46a09252015-02-12 14:45:43 -08003620 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003621 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003622
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003623 def test_verify_with_time(self):
3624 """
3625 `verify_certificate` raises error when the verification time is
3626 set at notAfter.
3627 """
3628 store = X509Store()
3629 store.add_cert(self.root_cert)
3630 store.add_cert(self.intermediate_cert)
3631
3632 expire_time = self.intermediate_server_cert.get_notAfter()
3633 expire_datetime = datetime.strptime(
3634 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3635 )
3636 store.set_time(expire_datetime)
3637
3638 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3639 with pytest.raises(X509StoreContextError) as exc:
3640 store_ctx.verify_certificate()
3641
3642 assert exc.value.args[0][2] == 'certificate has expired'
3643
Stephen Holsapple46a09252015-02-12 14:45:43 -08003644
Alex Chan7be83a52017-01-24 15:19:29 +00003645class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003646 """
Alex Chan7be83a52017-01-24 15:19:29 +00003647 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003648 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003649
James Yonan7c2e5d32010-02-27 05:45:50 -07003650 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003651 """
Alex Chan7be83a52017-01-24 15:19:29 +00003652 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003653 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003654 content = (
3655 b"It was a bright cold day in April, and the clocks were striking "
3656 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3657 b"effort to escape the vile wind, slipped quickly through the "
3658 b"glass doors of Victory Mansions, though not quickly enough to "
3659 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003660
3661 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003662 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003663 # verify the content with this cert
3664 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3665 # certificate unrelated to priv_key, used to trigger an error
3666 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003667
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003668 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003669 sig = sign(priv_key, content, digest)
3670
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003671 # Verify the signature of content, will throw an exception if
3672 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003673 verify(good_cert, sig, content, digest)
3674
3675 # This should fail because the certificate doesn't match the
3676 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003677 with pytest.raises(Error):
3678 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003679
3680 # This should fail because we've "tainted" the content after
3681 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003682 with pytest.raises(Error):
3683 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003684
3685 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003686 with pytest.raises(ValueError):
3687 sign(priv_key, content, "strange-digest")
3688 with pytest.raises(ValueError):
3689 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003690
Abraham Martinc5484ba2015-03-25 15:33:05 +00003691 def test_sign_verify_with_text(self):
3692 """
Alex Chan7be83a52017-01-24 15:19:29 +00003693 `sign` generates a cryptographic signature which
3694 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003695 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003696 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003697 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003698 b"It was a bright cold day in April, and the clocks were striking "
3699 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3700 b"effort to escape the vile wind, slipped quickly through the "
3701 b"glass doors of Victory Mansions, though not quickly enough to "
3702 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003703 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003704
3705 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3706 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3707 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003708 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003709 simplefilter("always")
3710 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003711 assert (
3712 "{0} for data is no longer accepted, use bytes".format(
3713 WARNING_TYPE_EXPECTED
3714 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003715
Alex Chan7be83a52017-01-24 15:19:29 +00003716 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003717 simplefilter("always")
3718 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003719 assert (
3720 "{0} for data is no longer accepted, use bytes".format(
3721 WARNING_TYPE_EXPECTED
3722 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003723
Paul Kehrer59d26252017-07-20 10:45:54 +02003724 def test_sign_verify_ecdsa(self):
3725 """
3726 `sign` generates a cryptographic signature which `verify` can check.
3727 ECDSA Signatures in the X9.62 format may have variable length,
3728 different from the length of the private key.
3729 """
3730 content = (
3731 b"It was a bright cold day in April, and the clocks were striking "
3732 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3733 b"effort to escape the vile wind, slipped quickly through the "
3734 b"glass doors of Victory Mansions, though not quickly enough to "
3735 b"prevent a swirl of gritty dust from entering along with him."
3736 ).decode("ascii")
3737 priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
3738 cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
3739 sig = sign(priv_key, content, "sha1")
3740 verify(cert, sig, content, "sha1")
3741
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003742 def test_sign_nulls(self):
3743 """
Alex Chan7be83a52017-01-24 15:19:29 +00003744 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003745 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003746 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003747 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3748 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3749 sig = sign(priv_key, content, "sha1")
3750 verify(good_cert, sig, content, "sha1")
3751
Colleen Murphye09399b2016-03-01 17:40:49 -08003752 def test_sign_with_large_key(self):
3753 """
Alex Chan7be83a52017-01-24 15:19:29 +00003754 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003755 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003756 content = (
3757 b"It was a bright cold day in April, and the clocks were striking "
3758 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3759 b"effort to escape the vile wind, slipped quickly through the "
3760 b"glass doors of Victory Mansions, though not quickly enough to "
3761 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003762
3763 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3764 sign(priv_key, content, "sha1")
3765
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003766
Alex Chan63ef9bc2016-12-19 12:02:06 +00003767class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003768 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003769 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3770 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003771 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003772
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003773 def test_set(self):
3774 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003775 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003776 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003777 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003778
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003779 def test_a_curve(self):
3780 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003781 `get_elliptic_curve` can be used to retrieve a particular supported
3782 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003783 """
3784 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003785 curve = next(iter(curves))
3786 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003787
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003788 def test_not_a_curve(self):
3789 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003790 `get_elliptic_curve` raises `ValueError` if called with a name which
3791 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003792 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003793 with pytest.raises(ValueError):
3794 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003795
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003796 def test_repr(self):
3797 """
3798 The string representation of a curve object includes simply states the
3799 object is a curve and what its name is.
3800 """
3801 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003802 curve = next(iter(curves))
3803 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003804
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003805 def test_to_EC_KEY(self):
3806 """
3807 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003808 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003809 """
3810 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003811 curve = next(iter(curves))
3812 # It's not easy to assert anything about this object. However, see
3813 # leakcheck/crypto.py for a test that demonstrates it at least does
3814 # not leak memory.
3815 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003816
3817
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003818class EllipticCurveFactory(object):
3819 """
3820 A helper to get the names of two curves.
3821 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003822
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003823 def __init__(self):
3824 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003825 self.curve_name = next(curves).name
3826 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003827
3828
Alex Chan63ef9bc2016-12-19 12:02:06 +00003829class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003830 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003831 Tests `_EllipticCurve`\ 's implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003832 """
3833 curve_factory = EllipticCurveFactory()
3834
3835 if curve_factory.curve_name is None:
3836 skip = "There are no curves available there can be no curve objects."
3837
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003838 def anInstance(self):
3839 """
3840 Get the curve object for an arbitrary curve supported by the system.
3841 """
3842 return get_elliptic_curve(self.curve_factory.curve_name)
3843
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003844 def anotherInstance(self):
3845 """
3846 Get the curve object for an arbitrary curve supported by the system -
3847 but not the one returned by C{anInstance}.
3848 """
3849 return get_elliptic_curve(self.curve_factory.another_curve_name)
3850
3851
Alex Chan63ef9bc2016-12-19 12:02:06 +00003852class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003853 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003854 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3855 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003856 """
3857 curve_factory = EllipticCurveFactory()
3858
3859 if curve_factory.curve_name is None:
3860 skip = "There are no curves available there can be no curve objects."
3861
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003862 def test_contains(self):
3863 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003864 The ``in`` operator reports that a `set` containing a curve does
3865 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003866 """
3867 curve = get_elliptic_curve(self.curve_factory.curve_name)
3868 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003869 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003870
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003871 def test_does_not_contain(self):
3872 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003873 The ``in`` operator reports that a `set` not containing a curve
3874 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003875 """
3876 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003877 curves = set([
3878 get_elliptic_curve(self.curve_factory.another_curve_name)
3879 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003880 assert curve not in curves