blob: 2bcc933b9e52cd094a582d1fab1066020b88e40f [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
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -050025from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
Jean-Paul Calderone78381d22008-03-06 23:35:22 -050026from OpenSSL.crypto import X509, X509Type, X509Name, X509NameType
Alex Gaynor31287502015-09-05 16:11:27 -040027from OpenSSL.crypto import (
Dan Sully44e767a2016-06-04 18:05:27 -070028 X509Store,
29 X509StoreFlags,
30 X509StoreType,
31 X509StoreContext,
32 X509StoreContextError
Alex Gaynor31287502015-09-05 16:11:27 -040033)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070034from OpenSSL.crypto import X509Req, X509ReqType
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -050035from OpenSSL.crypto import X509Extension, X509ExtensionType
Rick Dean5b7b6372009-04-01 11:34:06 -050036from OpenSSL.crypto import load_certificate, load_privatekey
Cory Benfield6492f7c2015-10-27 16:57:58 +090037from OpenSSL.crypto import load_publickey, dump_publickey
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -040038from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
Jean-Paul Calderone71919862009-04-01 13:01:19 -040039from OpenSSL.crypto import dump_certificate, load_certificate_request
40from OpenSSL.crypto import dump_certificate_request, dump_privatekey
Alex Chanb00ede22017-01-30 07:24:40 +000041from OpenSSL.crypto import PKCS7, PKCS7Type, load_pkcs7_data
Jean-Paul Calderone9178ee62010-01-25 17:55:30 -050042from OpenSSL.crypto import PKCS12, PKCS12Type, load_pkcs12
Dominic Chenf05b2122015-10-13 16:32:35 +000043from OpenSSL.crypto import CRL, Revoked, dump_crl, load_crl
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -040044from OpenSSL.crypto import NetscapeSPKI, NetscapeSPKIType
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040045from OpenSSL.crypto import (
46 sign, verify, get_elliptic_curve, get_elliptic_curves)
Alex Chan63ef9bc2016-12-19 12:02:06 +000047from OpenSSL._util import native
Hynek Schlawackf0e66852015-10-16 20:18:38 +020048
Alex Chanb00ede22017-01-30 07:24:40 +000049from .util import EqualityTestsMixin, is_consistent_type, WARNING_TYPE_EXPECTED
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040050
Alex Gaynoraceb3e22015-09-05 12:00:22 -040051
Jean-Paul Calderone9da338d2011-05-04 11:40:54 -040052def normalize_privatekey_pem(pem):
53 return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
54
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -040055
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050056GOOD_CIPHER = "blowfish"
57BAD_CIPHER = "zippers"
58
Anthony Alba2ce737f2015-12-04 11:04:56 +080059GOOD_DIGEST = "SHA1"
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050060BAD_DIGEST = "monkeys"
61
Paul Kehrera40898b2017-06-11 16:30:58 -100062old_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
Rick Dean94e46fd2009-07-18 14:51:24 -050063MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
64BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
65ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
66NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
67MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
68ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
69urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
702xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
711dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
72FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
73VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
74BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
75b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
76AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
77hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
78w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
79-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -040080"""
Rick Dean94e46fd2009-07-18 14:51:24 -050081
Paul Kehrera40898b2017-06-11 16:30:58 -100082root_cert_pem = b"""-----BEGIN CERTIFICATE-----
83MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
84BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
85ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
86WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
87BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
88bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
89bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
90LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
91onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
92LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
93yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
94aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
95Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
96R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
97gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
98lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
99-----END CERTIFICATE-----
100"""
101
Alex Gaynore7f51982016-09-11 11:48:14 -0400102root_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500103MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
104jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
1053claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
106AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
107yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
1086JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
109BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
110u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
111PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
112I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
113ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
1146AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
115cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
116-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400117"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500118
Alex Gaynore7f51982016-09-11 11:48:14 -0400119intermediate_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700120MIICVzCCAcCgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQENBQAw
121WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
122DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTQw
123ODI4MDIwNDA4WhcNMjQwODI1MDIwNDA4WjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
124dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
125MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIGfMA0GCSqGSIb3DQEB
126AQUAA4GNADCBiQKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmK
127FGIbljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT
12821H2qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwID
129AQABoxMwETAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDQUAA4GBAPIWSkLX
130QRMApOjjyC+tMxumT5e2pMqChHmxobQK4NMdrf2VCx+cRT6EmY8sK3/Xl/X8UBQ+
1319n5zXb1ZwhW/sTWgUvmOceJ4/XVs9FkdWOOn1J0XBch9ZIiFe/s5ASIgG7fUdcUF
1329mAWS6FK2ca3xIh5kIupCXOFa0dPvlw/YUFT
133-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400134"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700135
Alex Gaynore7f51982016-09-11 11:48:14 -0400136intermediate_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700137MIICWwIBAAKBgQDYcEQw5lfbEQRjr5Yy4yxAHGV0b9Al+Lmu7wLHMkZ/ZMmKFGIb
138ljbviiD1Nz97Oh2cpB91YwOXOTN2vXHq26S+A5xe8z/QJbBsyghMur88CjdT21H2
139qwMa+r5dCQwEhuGIiZ3KbzB/n4DTMYI5zy4IYPv0pjxShZn4aZTCCK2IUwIDAQAB
140AoGAfSZVV80pSeOKHTYfbGdNY/jHdU9eFUa/33YWriXU+77EhpIItJjkRRgivIfo
141rhFJpBSGmDLblaqepm8emsXMeH4+2QzOYIf0QGGP6E6scjTt1PLqdqKfVJ1a2REN
142147cujNcmFJb/5VQHHMpaPTgttEjlzuww4+BCDPsVRABWrkCQQD3loH36nLoQTtf
143+kQq0T6Bs9/UWkTAGo0ND81ALj0F8Ie1oeZg6RNT96RxZ3aVuFTESTv6/TbjWywO
144wdzlmV1vAkEA38rTJ6PTwaJlw5OttdDzAXGPB9tDmzh9oSi7cHwQQXizYd8MBYx4
145sjHUKD3dCQnb1dxJFhd3BT5HsnkRMbVZXQJAbXduH17ZTzcIOXc9jHDXYiFVZV5D
14652vV0WCbLzVCZc3jMrtSUKa8lPN5EWrdU3UchWybyG0MR5mX8S5lrF4SoQJAIyUD
147DBKaSqpqONCUUx1BTFS9FYrFjzbL4+c1qHCTTPTblt8kUCrDOZjBrKAqeiTmNSum
148/qUot9YUBF8m6BuGsQJATHHmdFy/fG1VLkyBp49CAa8tN3Z5r/CgTznI4DfMTf4C
149NbRHn2UmYlwQBa+L5lg9phewNe8aEwpPyPLoV85U8Q==
150-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400151"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700152
Alex Gaynore7f51982016-09-11 11:48:14 -0400153server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000154MIICJDCCAY2gAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
155BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
156VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMTA1
157N1oXDTM3MDYwNzAwMTA1N1owGDEWMBQGA1UEAwwNbG92ZWx5IHNlcnZlcjCBnzAN
158BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAvqb4brndXS2kEL84qXbZXE6LYK+UrhNi
15970sdIM/24NVN7tXkPlOXqrMWhFHHml+aeSpPkH5b1vKnY1TcULmEubnNICtvjmZ5
160SGMQn+J+RmBs1SMd0EgY/0wBBQdlrlYp2QYgm8YC+zxTNSqWvhMFZAgHbj6Un5SS
161T8JGBqytjB0CAwEAAaM2MDQwHQYDVR0OBBYEFINVdy1eIfFJDAkk51QJEo3IfgSu
162MBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4GBAGki1K6WgHHJ
163qC6aY2EowjaWOXLO6jUZIhGk7BA7vMRfNug429AOZ4m5F6OQhzmJmlw67Jyu2FeI
164h0VtBuQoHPtjqZXF59oX6hMMmGLMs9pV0UA3fJs5MYA4/V5ZcQy0Ie0QoJNejLzE
1656V1Qz1rRTYLUyEcpI7ZCmBg2KQQI8YZI
Rick Dean94e46fd2009-07-18 14:51:24 -0500166-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400167"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500168
Alex Gaynore7f51982016-09-11 11:48:14 -0400169server_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500170MIICWwIBAAKBgQC+pvhuud1dLaQQvzipdtlcTotgr5SuE2LvSx0gz/bg1U3u1eQ+
171U5eqsxaEUceaX5p5Kk+QflvW8qdjVNxQuYS5uc0gK2+OZnlIYxCf4n5GYGzVIx3Q
172SBj/TAEFB2WuVinZBiCbxgL7PFM1Kpa+EwVkCAduPpSflJJPwkYGrK2MHQIDAQAB
173AoGAbwuZ0AR6JveahBaczjfnSpiFHf+mve2UxoQdpyr6ROJ4zg/PLW5K/KXrC48G
174j6f3tXMrfKHcpEoZrQWUfYBRCUsGD5DCazEhD8zlxEHahIsqpwA0WWssJA2VOLEN
175j6DuV2pCFbw67rfTBkTSo32ahfXxEKev5KswZk0JIzH3ooECQQDgzS9AI89h0gs8
176Dt+1m11Rzqo3vZML7ZIyGApUzVan+a7hbc33nbGRkAXjHaUBJO31it/H6dTO+uwX
177msWwNG5ZAkEA2RyFKs5xR5USTFaKLWCgpH/ydV96KPOpBND7TKQx62snDenFNNbn
178FwwOhpahld+vqhYk+pfuWWUpQciE+Bu7ZQJASjfT4sQv4qbbKK/scePicnDdx9th
1794e1EeB9xwb+tXXXUo/6Bor/AcUNwfiQ6Zt9PZOK9sR3lMZSsP7rMi7kzuQJABie6
1801sXXjFH7nNJvRG4S39cIxq8YRYTy68II/dlB2QzGpKxV/POCxbJ/zu0CU79tuYK7
181NaeNCFfH3aeTrX0LyQJAMBWjWmeKM2G2sCExheeQK0ROnaBC8itCECD4Jsve4nqf
182r50+LF74iLXFwqysVCebPKMOpDWp/qQ1BbJQIPs7/A==
183-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400184""")
Rick Dean94e46fd2009-07-18 14:51:24 -0500185
Alex Gaynore7f51982016-09-11 11:48:14 -0400186intermediate_server_cert_pem = b"""-----BEGIN CERTIFICATE-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700187MIICWDCCAcGgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQENBQAw
188ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
189CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
190biBEaWVnbzAeFw0xNDA4MjgwMjEwNDhaFw0yNDA4MjUwMjEwNDhaMG4xHTAbBgNV
191BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
192CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
193biBEaWVnbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqpJZygd+w1faLOr1
194iOAmbBhx5SZWcTCZ/ZjHQTJM7GuPT624QkqsixFghRKdDROwpwnAP7gMRukLqiy4
195+kRuGT5OfyGggL95i2xqA+zehjj08lSTlvGHpePJgCyTavIy5+Ljsj4DKnKyuhxm
196biXTRrH83NDgixVkObTEmh/OVK0CAwEAATANBgkqhkiG9w0BAQ0FAAOBgQBa0Npw
197UkzjaYEo1OUE1sTI6Mm4riTIHMak4/nswKh9hYup//WVOlr/RBSBtZ7Q/BwbjobN
1983bfAtV7eSAqBsfxYXyof7G1ALANQERkq3+oyLP1iVt08W1WOUlIMPhdCF/QuCwy6
199x9MJLhUCGLJPM+O2rAPWVD9wCmvq10ALsiH3yA==
200-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400201"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700202
Alex Gaynore7f51982016-09-11 11:48:14 -0400203intermediate_server_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700204MIICXAIBAAKBgQCqklnKB37DV9os6vWI4CZsGHHlJlZxMJn9mMdBMkzsa49PrbhC
205SqyLEWCFEp0NE7CnCcA/uAxG6QuqLLj6RG4ZPk5/IaCAv3mLbGoD7N6GOPTyVJOW
2068Yel48mALJNq8jLn4uOyPgMqcrK6HGZuJdNGsfzc0OCLFWQ5tMSaH85UrQIDAQAB
207AoGAIQ594j5zna3/9WaPsTgnmhlesVctt4AAx/n827DA4ayyuHFlXUuVhtoWR5Pk
2085ezj9mtYW8DyeCegABnsu2vZni/CdvU6uiS1Hv6qM1GyYDm9KWgovIP9rQCDSGaz
209d57IWVGxx7ODFkm3gN5nxnSBOFVHytuW1J7FBRnEsehRroECQQDXHFOv82JuXDcz
210z3+4c74IEURdOHcbycxlppmK9kFqm5lsUdydnnGW+mvwDk0APOB7Wg7vyFyr393e
211dpmBDCzNAkEAyv6tVbTKUYhSjW+QhabJo896/EqQEYUmtMXxk4cQnKeR/Ao84Rkf
212EqD5IykMUfUI0jJU4DGX+gWZ10a7kNbHYQJAVFCuHNFxS4Cpwo0aqtnzKoZaHY/8
213X9ABZfafSHCtw3Op92M+7ikkrOELXdS9KdKyyqbKJAKNEHF3LbOfB44WIQJAA2N4
2149UNNVUsXRbElEnYUS529CdUczo4QdVgQjkvk5RiPAUwSdBd9Q0xYnFOlFwEmIowg
215ipWJWe0aAlP18ZcEQQJBAL+5lekZ/GUdQoZ4HAsN5a9syrzavJ9VvU1KOOPorPZK
216nMRZbbQgP+aSB7yl6K0gaLaZ8XaK0pjxNBh6ASqg9f4=
217-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400218"""
Stephen Holsapple0d9815f2014-08-27 19:36:53 -0700219
Alex Gaynore7f51982016-09-11 11:48:14 -0400220client_cert_pem = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000221MIICIjCCAYugAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBBQUAMFgxCzAJBgNV
222BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
223VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTE3MDYxMjAwMDQx
224M1oXDTM3MDYwNzAwMDQxM1owFjEUMBIGA1UEAwwLdWdseSBjbGllbnQwgZ8wDQYJ
225KoZIhvcNAQEBBQADgY0AMIGJAoGBAMBmH9JG02bme0xPipvpjMSlOugyWrauf4at
226EdGJn7GQLD8IY2Fu0+Kvv9DFpSPboFKZCsfDVsYoRs+xaJbtt1dJ6ymX7EqKS7gb
2278q+eeZZ14keqyJd5Rm2q6swQtw9ADD3E8cS6GqpQm+8SgxOycISoYz7sO1ugJFqN
228jId+W4BFAgMBAAGjNjA0MB0GA1UdDgQWBBSDVXctXiHxSQwJJOdUCRKNyH4ErjAT
229BgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQAMqcHyweaCOZNN
230dWQQOsBKQlL5wqVVZwucHPWqobjxpULKy9gS2ha2zbgkXcB/BnBOSwe0Fm+MJV0T
231NbnTghcGJNpEH7VKn4xSLvIGZmnZZWgxeIB16z4GhpkK2fShBJ+6GKZjsgjT0lSH
232JRgjHbWutZfZvbSHXr9n7PIphG1Ojg==
Rick Dean94e46fd2009-07-18 14:51:24 -0500233-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400234"""
Rick Dean94e46fd2009-07-18 14:51:24 -0500235
Alex Gaynore7f51982016-09-11 11:48:14 -0400236client_key_pem = normalize_privatekey_pem(b"""-----BEGIN RSA PRIVATE KEY-----
Rick Dean94e46fd2009-07-18 14:51:24 -0500237MIICXgIBAAKBgQDAZh/SRtNm5ntMT4qb6YzEpTroMlq2rn+GrRHRiZ+xkCw/CGNh
238btPir7/QxaUj26BSmQrHw1bGKEbPsWiW7bdXSespl+xKiku4G/KvnnmWdeJHqsiX
239eUZtqurMELcPQAw9xPHEuhqqUJvvEoMTsnCEqGM+7DtboCRajYyHfluARQIDAQAB
240AoGATkZ+NceY5Glqyl4mD06SdcKfV65814vg2EL7V9t8+/mi9rYL8KztSXGlQWPX
241zuHgtRoMl78yQ4ZJYOBVo+nsx8KZNRCEBlE19bamSbQLCeQMenWnpeYyQUZ908gF
242h6L9qsFVJepgA9RDgAjyDoS5CaWCdCCPCH2lDkdcqC54SVUCQQDseuduc4wi8h4t
243V8AahUn9fn9gYfhoNuM0gdguTA0nPLVWz4hy1yJiWYQe0H7NLNNTmCKiLQaJpAbb
244TC6vE8C7AkEA0Ee8CMJUc20BnGEmxwgWcVuqFWaKCo8jTH1X38FlATUsyR3krjW2
245dL3yDD9NwHxsYP7nTKp/U8MV7U9IBn4y/wJBAJl7H0/BcLeRmuJk7IqJ7b635iYB
246D/9beFUw3MUXmQXZUfyYz39xf6CDZsu1GEdEC5haykeln3Of4M9d/4Kj+FcCQQCY
247si6xwT7GzMDkk/ko684AV3KPc/h6G0yGtFIrMg7J3uExpR/VdH2KgwMkZXisSMvw
248JJEQjOMCVsEJlRk54WWjAkEAzoZNH6UhDdBK5F38rVt/y4SEHgbSfJHIAmPS32Kq
249f6GGcfNpip0Uk7q7udTKuX7Q/buZi/C4YW7u3VKAquv9NA==
250-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400251""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400252
Alex Gaynore7f51982016-09-11 11:48:14 -0400253cleartextCertificatePEM = b"""-----BEGIN CERTIFICATE-----
Paul Kehrera40898b2017-06-11 16:30:58 -1000254MIIC6TCCAlKgAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400255BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
Paul Kehrera40898b2017-06-11 16:30:58 -1000256ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMTcwNjExMjIzMjU5
257WhcNMzcwNjA2MjIzMjU5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
258BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
259bmcgUm9vdCBDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA+ZpC6Yu6ukTn
260bu5IQd0vWmpwNGZbO773xjpgfNP8nspYRqbIwI1np9FbUkJHvzZRDxrTt/LbFewr
261LhZ0prHIbwJxq3CZe+m9FDjh1IA0yKEcQukA1N3JWnoMLKwQPrCRAW6seUXV2yER
262onDxv/KkOGZtUijoKLXG8ImqK9ssWdsCAwEAAaOBuzCBuDAdBgNVHQ4EFgQUg1V3
263LV4h8UkMCSTnVAkSjch+BK4wgYgGA1UdIwSBgDB+gBSDVXctXiHxSQwJJOdUCRKN
264yH4ErqFcpFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdD
265aGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3Qg
266Q0GCCD0MxODG3rn0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEANFYQ
267R+T70VcZ+SnvURnwviFgCXeedBzCr21meo+DNHbkp2gudB9W8Xrned/wtUBVymy9
268gjB5jINfU7Lci0H57Evsw96UJJVfhXdUMHpqt1RGCoEd9FWnrDyrSy0NysnBT2bH
269lEqxh3aFEUx9IOQ4sgnx1/NOFXBpkRtivl6O0Ec=
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400270-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400271"""
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400272
Alex Gaynore7f51982016-09-11 11:48:14 -0400273cleartextPrivateKeyPEM = normalize_privatekey_pem(b"""\
Jean-Paul Calderoned50d2042011-05-04 17:00:49 -0400274-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400275MIICXQIBAAKBgQD5mkLpi7q6ROdu7khB3S9aanA0Zls7vvfGOmB80/yeylhGpsjA
276jWen0VtSQke/NlEPGtO38tsV7CsuFnSmschvAnGrcJl76b0UOOHUgDTIoRxC6QDU
2773claegwsrBA+sJEBbqx5RdXbIRGicPG/8qQ4Zm1SKOgotcbwiaor2yxZ2wIDAQAB
278AoGBAPCgMpmLxzwDaUmcFbTJUvlLW1hoxNNYSu2jIZm1k/hRAcE60JYwvBkgz3UB
279yMEh0AtLxYe0bFk6EHah11tMUPgscbCq73snJ++8koUw+csk22G65hOs51bVb7Aa
2806JBe67oLzdtvgCUFAA2qfrKzWRZzAdhUirQUZgySZk+Xq1pBAkEA/kZG0A6roTSM
281BVnx7LnPfsycKUsTumorpXiylZJjTi9XtmzxhrYN6wgZlDOOwOLgSQhszGpxVoMD
282u3gByT1b2QJBAPtL3mSKdvwRu/+40zaZLwvSJRxaj0mcE4BJOS6Oqs/hS1xRlrNk
283PpQ7WJ4yM6ZOLnXzm2mKyxm50Mv64109FtMCQQDOqS2KkjHaLowTGVxwC0DijMfr
284I9Lf8sSQk32J5VWCySWf5gGTfEnpmUa41gKTMJIbqZZLucNuDcOtzUaeWZlZAkA8
285ttXigLnCqR486JDPTi9ZscoZkZ+w7y6e/hH8t6d5Vjt48JVyfjPIaJY+km58LcN3
2866AWSeGAdtRFHVzR7oHjVAkB4hutvxiOeiIVQNBhM6RSI9aBPMI21DoX2JRoxvNW2
287cbvAhow217X9V0dVerEOKxnNYspXRrh36h7k4mQA+sDq
288-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400289""")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400290
Alex Gaynore7f51982016-09-11 11:48:14 -0400291cleartextCertificateRequestPEM = b"""-----BEGIN CERTIFICATE REQUEST-----
Jean-Paul Calderoneadd7bf02010-08-22 17:38:30 -0400292MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
293EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
294ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
295BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
296E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
297xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
298gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
299Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
300oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
301-----END CERTIFICATE REQUEST-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400302"""
Rick Dean5b7b6372009-04-01 11:34:06 -0500303
Alex Gaynore7f51982016-09-11 11:48:14 -0400304encryptedPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400305Proc-Type: 4,ENCRYPTED
306DEK-Info: DES-EDE3-CBC,9573604A18579E9E
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400307
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400308SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
309a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
3108+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
311mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
312+00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
313fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
314tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
315rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
316gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
317o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
3187SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
319MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
32011n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
321-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400322"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400323
Alex Gaynore7f51982016-09-11 11:48:14 -0400324encryptedPrivateKeyPEMPassphrase = b"foobar"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400325
Cory Benfield6492f7c2015-10-27 16:57:58 +0900326
Alex Gaynore7f51982016-09-11 11:48:14 -0400327cleartextPublicKeyPEM = b"""-----BEGIN PUBLIC KEY-----
Cory Benfield6492f7c2015-10-27 16:57:58 +0900328MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxszlc+b71LvlLS0ypt/l
329gT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZOtPclNY823Q4pErMTSWC
33090qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLjBuUIkQzEKEFV+8taiRV+
331ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPrUQqYQUEiTmVhh4FBUKZ5
332XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV215k4TeHMFYE5RG0KYAS
3338Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6HXRpQCyASzEG7bgtROLhL
334ywIDAQAB
335-----END PUBLIC KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400336"""
Cory Benfield6492f7c2015-10-27 16:57:58 +0900337
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400338# Some PKCS#7 stuff. Generated with the openssl command line:
339#
340# openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
341#
342# with a certificate and key (but the key should be irrelevant) in s.pem
Alex Gaynore7f51982016-09-11 11:48:14 -0400343pkcs7Data = b"""\
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400344-----BEGIN PKCS7-----
345MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
346BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
347A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
348MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
349cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
350A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
351HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
352SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
353zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
354LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
355A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
35665w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
357Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
358Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
359bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
360VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
361/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
362Ho4EzbYCOaEAMQA=
363-----END PKCS7-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400364"""
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -0400365
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700366pkcs7DataASN1 = base64.b64decode(b"""
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700367MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
368BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
369A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
370MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
371cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
372A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
373HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
374SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
375zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
376LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
377A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
37865w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
379Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
380Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
381bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
382VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
383/g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
384Ho4EzbYCOaEAMQA=
Alex Gaynor8fa1dd62014-08-14 09:57:51 -0700385""")
Alex Gaynor4b9c96a2014-08-14 09:51:48 -0700386
Alex Gaynore7f51982016-09-11 11:48:14 -0400387crlData = b"""\
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -0500388-----BEGIN X509 CRL-----
389MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
390SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
391D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
392MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
393MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
3944dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
3950yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
396vrzEeLDRiiPl92dyyWmu
397-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400398"""
Jean-Paul Calderonee890db32010-08-22 16:55:15 -0400399
Alex Gaynore7f51982016-09-11 11:48:14 -0400400crlDataUnsupportedExtension = b"""\
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400401-----BEGIN X509 CRL-----
402MIIGRzCCBS8CAQIwDQYJKoZIhvcNAQELBQAwJzELMAkGA1UEBhMCVVMxGDAWBgNV
403BAMMD2NyeXB0b2dyYXBoeS5pbxgPMjAxNTAxMDEwMDAwMDBaGA8yMDE2MDEwMTAw
404MDAwMFowggTOMBQCAQAYDzIwMTUwMTAxMDAwMDAwWjByAgEBGA8yMDE1MDEwMTAw
405MDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAn
406MQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQD
407CgEAMHICAQIYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAw
408MDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlw
409dG9ncmFwaHkuaW8wCgYDVR0VBAMKAQEwcgIBAxgPMjAxNTAxMDEwMDAwMDBaMFww
410GAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTArpCkwJzELMAkGA1UE
411BhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNVHRUEAwoBAjByAgEE
412GA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQG
413A1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5
414LmlvMAoGA1UdFQQDCgEDMHICAQUYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQR
415GA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgw
416FgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQQwcgIBBhgPMjAxNTAx
417MDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTAr
418pCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNV
419HRUEAwoBBTByAgEHGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAx
420MDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwP
421Y3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEGMHICAQgYDzIwMTUwMTAxMDAwMDAw
422WjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJ
423BgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQgw
424cgIBCRgPMjAxNTAxMDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAw
425WjA0BgNVHR0ELTArpCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dy
426YXBoeS5pbzAKBgNVHRUEAwoBCTByAgEKGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNV
427HRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJV
428UzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEKMC4CAQsYDzIw
429MTUwMTAxMDAwMDAwWjAYMAoGA1UdFQQDCgEBMAoGAyoDBAQDCgEAMA0GCSqGSIb3
430DQEBCwUAA4IBAQBTaloHlPaCZzYee8LxkWej5meiqxQVNWFoVdjesroa+f1FRrH+
431drRU60Nq97KCKf7f9GNN/J3ZIlQmYhmuDqh12f+XLpotoj1ZRfBz2hjFCkJlv+2c
432oWWGNHgA70ndFoVtcmX088SYpX8E3ARATivS4q2h9WlwV6rO93mhg3HGIe3JpcK4
4337BcW6Poi/ut/zsDOkVbI00SqaujRpdmdCTht82MH3ztjyDkI9KYaD/YEweKSrWOz
434SdEILd164bfBeLuplVI+xpmTEMVNpXBlSXl7+xIw9Vk7p7Q1Pa3k/SvhOldYCm6y
435C1xAg/AAq6w78yzYt18j5Mj0s6eeHi1YpHKw
436-----END X509 CRL-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400437"""
Paul Kehrer5e3dd4c2016-03-11 09:58:28 -0400438
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400439
440# A broken RSA private key which can be used to test the error path through
441# PKey.check.
Alex Gaynore7f51982016-09-11 11:48:14 -0400442inconsistentPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400443MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
4445kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
445OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
446zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
447nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
448HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
449oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
450-----END RSA PRIVATE KEY-----
Alex Gaynore7f51982016-09-11 11:48:14 -0400451"""
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400452
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400453# certificate with NULL bytes in subjectAltName and common name
454
Alex Gaynore7f51982016-09-11 11:48:14 -0400455nulbyteSubjectAltNamePEM = b"""-----BEGIN CERTIFICATE-----
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400456MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
457DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
458eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
459RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
460ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
461NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
462DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
463ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
464ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
465hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
466BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
467pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
468vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
469KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
470oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
47108LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
472HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
473BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
474Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
475bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
476AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
477i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
478HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
479kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
480VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
481RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
Alex Gaynore7f51982016-09-11 11:48:14 -0400482-----END CERTIFICATE-----"""
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -0400483
Alex Gaynore7f51982016-09-11 11:48:14 -0400484large_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
Colleen Murphye09399b2016-03-01 17:40:49 -0800485MIIJYgIBAAKCAg4AtRua8eIeevRfsj+fkcHr1vmse7Kgb+oX1ssJAvCb1R7JQMnH
486hNDjDP6b3vEkZuPUzlDHymP+cNkXvvi4wJ4miVbO3+SeU4Sh+jmsHeHzGIXat9xW
4879PFtuPM5FQq8zvkY8aDeRYmYwN9JKu4/neMBCBqostYlTEWg+bSytO/qWnyHTHKh
488g0GfaDdqUQPsGQw+J0MgaYIjQOCVASHAPlzbDQLCtuOb587rwTLkZA2GwoHB/LyJ
489BwT0HHgBaiObE12Vs6wi2en0Uu11CiwEuK1KIBcZ2XbE6eApaZa6VH9ysEmUxPt7
490TqyZ4E2oMIYaLPNRxuvozdwTlj1svI1k1FrkaXGc5MTjbgigPMKjIb0T7b/4GNzt
491DhP1LvAeUMnrEi3hJJrcJPXHPqS8/RiytR9xQQW6Sdh4LaA3f9MQm3WSevWage3G
492P8YcCLssOVKsArDjuA52NF5LmYuAeUzXprm4ITDi2oO+0iFBpFW6VPEK4A9vO0Yk
493M/6Wt6tG8zyWhaSH1zFUTwfQ9Yvjyt5w1lrUaAJuoTpwbMVZaDJaEhjOaXU0dyPQ
494jOsePDOQcU6dkeTWsQ3LsHPEEug/X6819TLG5mb3V7bvV9nPFBfTJSCEG794kr90
495XgZfIN71FrdByxLerlbuJI21pPs/nZi9SXi9jAWeiS45/azUxMsyYgJArui+gjq7
496sV1pWiBm6/orAgMBAAECggINQp5L6Yu+oIXBqcSjgq8tfF9M5hd30pLuf/EheHZf
497LA7uAqn2fVGFI2OInIJhXIOT5OxsAXO0xXfltzawZxIFpOFMqajj4F7aYjvSpw9V
498J4EdSiJ/zgv8y1qUdbwEZbHVThRZjoSlrtSzilonBoHZAE0mHtqMz7iRFSk1zz6t
499GunRrvo/lROPentf3TsvHquVNUYI5yaapyO1S7xJhecMIIYSb8nbsHI54FBDGNas
5006mFmpPwI/47/6HTwOEWupnn3NicsjrHzUInOUpaMig4cRR+aP5bjqg/ty8xI8AoN
501evEmCytiWTc+Rvbp1ieN+1jpjN18PjUk80/W7qioHUDt4ieLic8uxWH2VD9SCEnX
502Mpi9tA/FqoZ+2A/3m1OfrY6jiZVE2g+asi9lCK7QVWL39eK82H4rPvtp0/dyo1/i
503ZZz68TXg+m8IgEZcp88hngbkuoTTzpGE73QuPKhGA1uMIimDdqPPB5WP76q+03Oi
504IRR5DfZnqPERed49by0enJ7tKa/gFPZizOV8ALKr0Dp+vfAkxGDLPLBLd2A3//tw
505xg0Q/wltihHSBujv4nYlDXdc5oYyMYZ+Lhc/VuOghHfBq3tgEQ1ECM/ofqXEIdy7
506nVcpZn3Eeq8Jl5CrqxE1ee3NxlzsJHn99yGQpr7mOhW/psJF3XNz80Meg3L4m1T8
507sMBK0GbaassuJhdzb5whAoIBBw48sx1b1WR4XxQc5O/HjHva+l16i2pjUnOUTcDF
508RWmSbIhBm2QQ2rVhO8+fak0tkl6ZnMWW4i0U/X5LOEBbC7+IS8bO3j3Revi+Vw5x
509j96LMlIe9XEub5i/saEWgiz7maCvfzLFU08e1OpT4qPDpP293V400ubA6R7WQTCv
510pBkskGwHeu0l/TuKkVqBFFUTu7KEbps8Gjg7MkJaFriAOv1zis/umK8pVS3ZAM6e
5118w5jfpRccn8Xzta2fRwTB5kCmfxdDsY0oYGxPLRAbW72bORoLGuyyPp/ojeGwoik
512JX9RttErc6FjyZtks370Pa8UL5QskyhMbDhrZW2jFD+RXYM1BrvmZRjbAoIBBwy4
513iFJpuDfytJfz1MWtaL5DqEL/kmiZYAXl6hifNhGu5GAipVIIGsDqEYW4i+VC15aa
5147kOCwz/I5zsB3vSDW96IRs4wXtqEZSibc2W/bqfVi+xcvPPl1ZhQ2EAwa4D/x035
515kyf20ffWOU+1yf2cnijzqs3IzlveUm+meLw5s3Rc+iG7DPWWeCoe1hVwANI1euNc
516pqKwKY905yFyjOje2OgiEU2kS4YME4zGeBys8yo7E42hNnN2EPK6xkkUqzdudLLQ
5178OUlKRTc8AbIf3XG1rpA4VUpTv3hhxGGwCRy6If8zgZQsNYchgNztRGk72Gcb8Dm
518vFSEN3ZtwxU64G3YZzntdcr2WPzxAoIBBw30g6Fgdb/gmVnOpL0//T0ePNDKIMPs
519jVJLaRduhoZgB1Bb9qPUPX0SzRzLZtg1tkZSDjBDoHmOHJfhxUaXt+FLCPPbrE4t
520+nq9n/nBaMM779w9ClqhqLOyGrwKoxjSmhi+TVEHyIxCbXMvPHVHfX9WzxjbcGrN
521ZvRaEVZWo+QlIX8yqdSwqxLk1WtAIRzvlcj7NKum8xBxPed6BNFep/PtgIAmoLT5
522L8wb7EWb2iUdc2KbZ4OaY51lDScqpATgXu3WjXfM+Q52G0mX6Wyd0cjlL711Zrjb
523yLbiueZT94lgIHHRRKtKc8CEqcjkQV5OzABS3P/gQSfgZXBdLKjOpTnKDUq7IBeH
524AoIBBweAOEIAPLQg1QRUrr3xRrYKRwlakgZDii9wJt1l5AgBTICzbTA1vzDJ1JM5
525AqSpCV6w9JWyYVcXK+HLdKBRZLaPPNEQDJ5lOxD6uMziWGl2rg8tj+1xNMWfxiPz
526aTCjoe4EoBUMoTq2gwzRcM2usEQNikXVhnj9Wzaivsaeb4bJ3GRPW5DkrO6JSEtT
527w+gvyMqQM2Hy5k7E7BT46sXVwaj/jZxuqGnebRixXtnp0WixdRIqYWUr1UqLf6hQ
528G7WP2BgoxCMaCmNW8+HMD/xuxucEotoIhZ+GgJKBFoNnjl3BX+qxYdSe9RbL/5Tr
5294It6Jxtj8uETJXEbv9Cg6v1agWPS9YY8RLTBAoIBBwrU2AsAUts6h1LgGLKK3UWZ
530oLH5E+4o+7HqSGRcRodVeN9NBXIYdHHOLeEG6YNGJiJ3bFP5ZQEu9iDsyoFVKJ9O
531Mw/y6dKZuxOCZ+X8FopSROg3yWfdOpAm6cnQZp3WqLNX4n/Q6WvKojfyEiPphjwT
5320ymrUJELXLWJmjUyPoAk6HgC0Gs28ZnEXbyhx7CSbZNFyCU/PNUDZwto3GisIPD3
533le7YjqHugezmjMGlA0sDw5aCXjfbl74vowRFYMO6e3ItApfSRgNV86CDoX74WI/5
534AYU/QVM4wGt8XGT2KwDFJaxYGKsGDMWmXY04dS+WPuetCbouWUusyFwRb9SzFave
535vYeU7Ab/
Alex Gaynore7f51982016-09-11 11:48:14 -0400536-----END RSA PRIVATE KEY-----"""
Colleen Murphye09399b2016-03-01 17:40:49 -0800537
Paul Kehrer72d968b2016-07-29 15:31:04 +0800538ec_private_key_pem = b"""-----BEGIN PRIVATE KEY-----
539MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgYirTZSx+5O8Y6tlG
540cka6W6btJiocdrdolfcukSoTEk+hRANCAAQkvPNu7Pa1GcsWU4v7ptNfqCJVq8Cx
541zo0MUVPQgwJ3aJtNM1QMOQUayCrRwfklg+D/rFSUwEUqtZh7fJDiFqz3
542-----END PRIVATE KEY-----
543"""
544
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400545
Alex Chanc6077062016-11-18 13:53:39 +0000546@pytest.fixture
547def x509_data():
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400548 """
Alex Chanc6077062016-11-18 13:53:39 +0000549 Create a new private key and start a certificate request (for a test
550 to finish in one way or another).
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400551 """
Alex Chanc6077062016-11-18 13:53:39 +0000552 # Basic setup stuff to generate a certificate
553 pkey = PKey()
554 pkey.generate_key(TYPE_RSA, 384)
555 req = X509Req()
556 req.set_pubkey(pkey)
557 # Authority good you have.
558 req.get_subject().commonName = "Yoda root CA"
559 x509 = X509()
560 subject = x509.get_subject()
561 subject.commonName = req.get_subject().commonName
562 x509.set_issuer(subject)
563 x509.set_pubkey(pkey)
564 now = datetime.now()
565 expire = datetime.now() + timedelta(days=100)
566 x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
567 x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
568 yield pkey, x509
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400569
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400570
Alex Chanc6077062016-11-18 13:53:39 +0000571class TestX509Ext(object):
572 """
573 Tests for `OpenSSL.crypto.X509Extension`.
574 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -0800575
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400576 def test_str(self):
577 """
Alex Chanc6077062016-11-18 13:53:39 +0000578 The string representation of `X509Extension` instances as
579 returned by `str` includes stuff.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400580 """
581 # This isn't necessarily the best string representation. Perhaps it
582 # will be changed/improved in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000583 assert (
584 str(X509Extension(b'basicConstraints', True, b'CA:false')) ==
585 'CA:FALSE'
586 )
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -0400587
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400588 def test_type(self):
589 """
Alex Chanc6077062016-11-18 13:53:39 +0000590 `X509Extension` and `X509ExtensionType` refer to the same type object
591 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400592 """
Alex Chanc6077062016-11-18 13:53:39 +0000593 assert X509Extension is X509ExtensionType
594 assert is_consistent_type(
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400595 X509Extension,
Alex Gaynore7f51982016-09-11 11:48:14 -0400596 'X509Extension', b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400597
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500598 def test_construction(self):
599 """
Alex Chanc6077062016-11-18 13:53:39 +0000600 `X509Extension` accepts an extension type name, a critical flag,
601 and an extension value and returns an `X509ExtensionType` instance.
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500602 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400603 basic = X509Extension(b'basicConstraints', True, b'CA:true')
Alex Chanc6077062016-11-18 13:53:39 +0000604 assert isinstance(basic, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500605
Alex Chanc6077062016-11-18 13:53:39 +0000606 comment = X509Extension(b'nsComment', False, b'pyOpenSSL unit test')
607 assert isinstance(comment, X509ExtensionType)
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500608
Alex Chanc6077062016-11-18 13:53:39 +0000609 @pytest.mark.parametrize('type_name, critical, value', [
610 (b'thisIsMadeUp', False, b'hi'),
611 (b'basicConstraints', False, b'blah blah'),
Jean-Paul Calderone391585f2008-12-31 14:36:31 -0500612
Jean-Paul Calderone2ee1e7c2008-12-31 14:58:38 -0500613 # Exercise a weird one (an extension which uses the r2i method). This
614 # exercises the codepath that requires a non-NULL ctx to be passed to
615 # X509V3_EXT_nconf. It can't work now because we provide no
616 # configuration database. It might be made to work in the future.
Alex Chanc6077062016-11-18 13:53:39 +0000617 (b'proxyCertInfo', True,
618 b'language:id-ppl-anyLanguage,pathlen:1,policy:text:AB')
619 ])
620 def test_invalid_extension(self, type_name, critical, value):
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500621 """
Alex Chanc6077062016-11-18 13:53:39 +0000622 `X509Extension` raises something if it is passed a bad
623 extension name or value.
624 """
625 with pytest.raises(Error):
626 X509Extension(type_name, critical, value)
627
628 @pytest.mark.parametrize('critical_flag', [True, False])
629 def test_get_critical(self, critical_flag):
630 """
631 `X509ExtensionType.get_critical` returns the value of the
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500632 extension's critical flag.
633 """
Alex Chanc6077062016-11-18 13:53:39 +0000634 ext = X509Extension(b'basicConstraints', critical_flag, b'CA:true')
635 assert ext.get_critical() == critical_flag
Jean-Paul Calderonee7db4b42008-12-31 13:39:24 -0500636
Alex Chanc6077062016-11-18 13:53:39 +0000637 @pytest.mark.parametrize('short_name, value', [
638 (b'basicConstraints', b'CA:true'),
639 (b'nsComment', b'foo bar'),
640 ])
641 def test_get_short_name(self, short_name, value):
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500642 """
Alex Chanc6077062016-11-18 13:53:39 +0000643 `X509ExtensionType.get_short_name` returns a string giving the
Alex Gaynor31287502015-09-05 16:11:27 -0400644 short type name of the extension.
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500645 """
Alex Chanc6077062016-11-18 13:53:39 +0000646 ext = X509Extension(short_name, True, value)
647 assert ext.get_short_name() == short_name
Jean-Paul Calderonef8c5fab2008-12-31 15:53:48 -0500648
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400649 def test_get_data(self):
650 """
Alex Chanc6077062016-11-18 13:53:39 +0000651 `X509Extension.get_data` returns a string giving the data of
Alex Gaynor31287502015-09-05 16:11:27 -0400652 the extension.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400653 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400654 ext = X509Extension(b'basicConstraints', True, b'CA:true')
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400655 # Expect to get back the DER encoded form of CA:true.
Alex Chanc6077062016-11-18 13:53:39 +0000656 assert ext.get_data() == b'0\x03\x01\x01\xff'
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400657
Alex Chanc6077062016-11-18 13:53:39 +0000658 def test_unused_subject(self, x509_data):
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400659 """
Alex Chanc6077062016-11-18 13:53:39 +0000660 The `subject` parameter to `X509Extension` may be provided for an
661 extension which does not use it and is ignored in this case.
Jean-Paul Calderone5a9e4612011-04-01 18:27:45 -0400662 """
Alex Chanc6077062016-11-18 13:53:39 +0000663 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400664 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000665 b'basicConstraints', False, b'CA:TRUE', subject=x509)
666 x509.add_extensions([ext1])
667 x509.sign(pkey, 'sha1')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400668 # This is a little lame. Can we think of a better way?
Alex Chanc6077062016-11-18 13:53:39 +0000669 text = dump_certificate(FILETYPE_TEXT, x509)
670 assert b'X509v3 Basic Constraints:' in text
671 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400672
Alex Chanc6077062016-11-18 13:53:39 +0000673 def test_subject(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400674 """
Alex Chanc6077062016-11-18 13:53:39 +0000675 If an extension requires a subject, the `subject` parameter to
676 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400677 """
Alex Chanc6077062016-11-18 13:53:39 +0000678 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400679 ext3 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000680 b'subjectKeyIdentifier', False, b'hash', subject=x509)
681 x509.add_extensions([ext3])
682 x509.sign(pkey, 'sha1')
683 text = dump_certificate(FILETYPE_TEXT, x509)
684 assert b'X509v3 Subject Key Identifier:' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400685
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400686 def test_missing_subject(self):
687 """
Alex Chanc6077062016-11-18 13:53:39 +0000688 If an extension requires a subject and the `subject` parameter
Alex Gaynor31287502015-09-05 16:11:27 -0400689 is given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400690 """
Alex Chanc6077062016-11-18 13:53:39 +0000691 with pytest.raises(Error):
692 X509Extension(b'subjectKeyIdentifier', False, b'hash')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400693
Alex Chanc6077062016-11-18 13:53:39 +0000694 @pytest.mark.parametrize('bad_obj', [
695 True,
696 object(),
697 "hello",
698 [],
699 ])
700 def test_invalid_subject(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400701 """
Alex Chanc6077062016-11-18 13:53:39 +0000702 If the `subject` parameter is given a value which is not an
703 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400704 """
Alex Chanc6077062016-11-18 13:53:39 +0000705 with pytest.raises(TypeError):
706 X509Extension(
707 'basicConstraints', False, 'CA:TRUE', subject=bad_obj)
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400708
Alex Chanc6077062016-11-18 13:53:39 +0000709 def test_unused_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400710 """
Alex Chanc6077062016-11-18 13:53:39 +0000711 The `issuer` parameter to `X509Extension` may be provided for an
712 extension which does not use it and is ignored in this case.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400713 """
Alex Chanc6077062016-11-18 13:53:39 +0000714 pkey, x509 = x509_data
Jean-Paul Calderone40dd0992010-08-22 17:52:07 -0400715 ext1 = X509Extension(
Alex Chanc6077062016-11-18 13:53:39 +0000716 b'basicConstraints', False, b'CA:TRUE', issuer=x509)
717 x509.add_extensions([ext1])
718 x509.sign(pkey, 'sha1')
719 text = dump_certificate(FILETYPE_TEXT, x509)
720 assert b'X509v3 Basic Constraints:' in text
721 assert b'CA:TRUE' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400722
Alex Chanc6077062016-11-18 13:53:39 +0000723 def test_issuer(self, x509_data):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400724 """
Alex Chanc6077062016-11-18 13:53:39 +0000725 If an extension requires an issuer, the `issuer` parameter to
726 `X509Extension` provides its value.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400727 """
Alex Chanc6077062016-11-18 13:53:39 +0000728 pkey, x509 = x509_data
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400729 ext2 = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -0400730 b'authorityKeyIdentifier', False, b'issuer:always',
Alex Chanc6077062016-11-18 13:53:39 +0000731 issuer=x509)
732 x509.add_extensions([ext2])
733 x509.sign(pkey, 'sha1')
734 text = dump_certificate(FILETYPE_TEXT, x509)
735 assert b'X509v3 Authority Key Identifier:' in text
736 assert b'DirName:/CN=Yoda root CA' in text
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400737
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400738 def test_missing_issuer(self):
739 """
Alex Chanc6077062016-11-18 13:53:39 +0000740 If an extension requires an issue and the `issuer` parameter is
741 given no value, something happens.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400742 """
Alex Chanc6077062016-11-18 13:53:39 +0000743 with pytest.raises(Error):
744 X509Extension(
745 b'authorityKeyIdentifier',
746 False, b'keyid:always,issuer:always')
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400747
Alex Chanc6077062016-11-18 13:53:39 +0000748 @pytest.mark.parametrize('bad_obj', [
749 True,
750 object(),
751 "hello",
752 [],
753 ])
754 def test_invalid_issuer(self, bad_obj):
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400755 """
Alex Chanc6077062016-11-18 13:53:39 +0000756 If the `issuer` parameter is given a value which is not an
757 `X509` instance, `TypeError` is raised.
Jean-Paul Calderonef0179c72009-07-17 15:48:22 -0400758 """
Alex Chanc6077062016-11-18 13:53:39 +0000759 with pytest.raises(TypeError):
760 X509Extension(
761 'basicConstraints', False, 'keyid:always,issuer:always',
762 issuer=bad_obj)
Rick Dean47262da2009-07-08 16:17:17 -0500763
764
Paul Kehrer72d968b2016-07-29 15:31:04 +0800765class TestPKey(object):
766 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +0100767 Tests for `OpenSSL.crypto.PKey`.
Paul Kehrer72d968b2016-07-29 15:31:04 +0800768 """
769
770 def test_convert_from_cryptography_private_key(self):
771 """
772 PKey.from_cryptography_key creates a proper private PKey.
773 """
774 key = serialization.load_pem_private_key(
775 intermediate_key_pem, None, backend
776 )
777 pkey = PKey.from_cryptography_key(key)
778
779 assert isinstance(pkey, PKey)
780 assert pkey.bits() == key.key_size
781 assert pkey._only_public is False
782 assert pkey._initialized is True
783
784 def test_convert_from_cryptography_public_key(self):
785 """
786 PKey.from_cryptography_key creates a proper public PKey.
787 """
788 key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
789 pkey = PKey.from_cryptography_key(key)
790
791 assert isinstance(pkey, PKey)
792 assert pkey.bits() == key.key_size
793 assert pkey._only_public is True
794 assert pkey._initialized is True
795
796 def test_convert_from_cryptography_unsupported_type(self):
797 """
798 PKey.from_cryptography_key raises TypeError with an unsupported type.
799 """
800 key = serialization.load_pem_private_key(
801 ec_private_key_pem, None, backend
802 )
803 with pytest.raises(TypeError):
804 PKey.from_cryptography_key(key)
805
806 def test_convert_public_pkey_to_cryptography_key(self):
807 """
808 PKey.to_cryptography_key creates a proper cryptography public key.
809 """
810 pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
811 key = pkey.to_cryptography_key()
812
813 assert isinstance(key, rsa.RSAPublicKey)
814 assert pkey.bits() == key.key_size
815
816 def test_convert_private_pkey_to_cryptography_key(self):
817 """
818 PKey.to_cryptography_key creates a proper cryptography private key.
819 """
820 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
821 key = pkey.to_cryptography_key()
822
823 assert isinstance(key, rsa.RSAPrivateKey)
824 assert pkey.bits() == key.key_size
825
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400826 def test_type(self):
827 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000828 `PKey` and `PKeyType` refer to the same type object and can be used to
829 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400830 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000831 assert PKey is PKeyType
832 assert is_consistent_type(PKey, 'PKey')
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400833
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500834 def test_construction(self):
835 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000836 `PKey` takes no arguments and returns a new `PKey` instance.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500837 """
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500838 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000839 assert isinstance(key, PKey)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500840
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500841 def test_pregeneration(self):
842 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000843 `PKey.bits` and `PKey.type` return `0` before the key is generated.
844 `PKey.check` raises `TypeError` before the key is generated.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500845 """
846 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000847 assert key.type() == 0
848 assert key.bits() == 0
849 with pytest.raises(TypeError):
850 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500851
Alex Chan9e2a9932017-01-25 14:29:19 +0000852 def test_failed_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500853 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000854 `PKey.generate_key` takes two arguments, the first giving the key type
855 as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
856 bits to generate. If an invalid type is specified or generation fails,
857 `Error` is raised. If an invalid number of bits is specified,
858 `ValueError` or `Error` is raised.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500859 """
860 key = PKey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000861 with pytest.raises(TypeError):
862 key.generate_key("foo", "bar")
863 with pytest.raises(Error):
864 key.generate_key(-1, 0)
Jean-Paul Calderoneab82db72008-03-06 00:09:31 -0500865
Alex Chan9e2a9932017-01-25 14:29:19 +0000866 with pytest.raises(ValueError):
867 key.generate_key(TYPE_RSA, -1)
868 with pytest.raises(ValueError):
869 key.generate_key(TYPE_RSA, 0)
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500870
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400871 with pytest.raises(TypeError):
872 key.generate_key(TYPE_RSA, object())
873
Jean-Paul Calderoned71fe982008-03-06 00:31:50 -0500874 # XXX RSA generation for small values of bits is fairly buggy in a wide
875 # range of OpenSSL versions. I need to figure out what the safe lower
876 # bound for a reasonable number of OpenSSL versions is and explicitly
877 # check for that in the wrapper. The failure behavior is typically an
878 # infinite loop inside OpenSSL.
879
Alex Chan9e2a9932017-01-25 14:29:19 +0000880 # with pytest.raises(Error):
881 # key.generate_key(TYPE_RSA, 2)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500882
883 # XXX DSA generation seems happy with any number of bits. The DSS
884 # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
885 # generator doesn't seem to care about the upper limit at all. For
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500886 # the lower limit, it uses 512 if anything smaller is specified.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500887 # So, it doesn't seem possible to make generate_key fail for
888 # TYPE_DSA with a bits argument which is at least an int.
889
Alex Chan9e2a9932017-01-25 14:29:19 +0000890 # with pytest.raises(Error):
891 # key.generate_key(TYPE_DSA, -7)
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500892
Alex Chan9e2a9932017-01-25 14:29:19 +0000893 def test_rsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500894 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000895 `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
896 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500897 """
898 bits = 128
899 key = PKey()
900 key.generate_key(TYPE_RSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000901 assert key.type() == TYPE_RSA
902 assert key.bits() == bits
903 assert key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500904
Alex Chan9e2a9932017-01-25 14:29:19 +0000905 def test_dsa_generation(self):
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500906 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000907 `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
908 type and a reasonable number of bits.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500909 """
910 # 512 is a magic number. The DSS (Digital Signature Standard)
911 # allows a minimum of 512 bits for DSA. DSA_generate_parameters
912 # will silently promote any value below 512 to 512.
913 bits = 512
914 key = PKey()
915 key.generate_key(TYPE_DSA, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000916 assert key.type() == TYPE_DSA
917 assert key.bits() == bits
918 with pytest.raises(TypeError):
919 key.check()
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500920
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500921 def test_regeneration(self):
922 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000923 `PKey.generate_key` can be called multiple times on the same key to
924 generate new keys.
Jean-Paul Calderoned8782ad2008-03-04 23:39:59 -0500925 """
926 key = PKey()
927 for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
Alex Gaynor7f636492015-09-04 13:26:52 -0400928 key.generate_key(type, bits)
Alex Chan9e2a9932017-01-25 14:29:19 +0000929 assert key.type() == type
930 assert key.bits() == bits
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500931
Alex Chan9e2a9932017-01-25 14:29:19 +0000932 def test_inconsistent_key(self):
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400933 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000934 `PKey.check` returns `Error` if the key is not consistent.
Jean-Paul Calderone55ec1712009-05-13 14:14:30 -0400935 """
936 key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
Alex Chan9e2a9932017-01-25 14:29:19 +0000937 with pytest.raises(Error):
938 key.check()
Jean-Paul Calderonee81020e2011-06-12 21:48:57 -0400939
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400940 def test_check_public_key(self):
941 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000942 `PKey.check` raises `TypeError` if only the public part of the key
943 is available.
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400944 """
945 # A trick to get a public-only key
946 key = PKey()
947 key.generate_key(TYPE_RSA, 512)
948 cert = X509()
949 cert.set_pubkey(key)
950 pub = cert.get_pubkey()
Alex Chan9e2a9932017-01-25 14:29:19 +0000951 with pytest.raises(TypeError):
952 pub.check()
Jean-Paul Calderone02d01972011-10-31 10:39:29 -0400953
954
Alex Chan9e2a9932017-01-25 14:29:19 +0000955def x509_name(**attrs):
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500956 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000957 Return a new X509Name with the given attributes.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -0500958 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000959 # XXX There's no other way to get a new X509Name yet.
960 name = X509().get_subject()
961 attrs = list(attrs.items())
Alex Gaynoraceb3e22015-09-05 12:00:22 -0400962
Alex Chan9e2a9932017-01-25 14:29:19 +0000963 # Make the order stable - order matters!
964 def key(attr):
965 return attr[1]
966 attrs.sort(key=key)
967 for k, v in attrs:
968 setattr(name, k, v)
969 return name
Alex Gaynor85b49702015-09-05 16:30:59 -0400970
Alex Chan9e2a9932017-01-25 14:29:19 +0000971
972class TestX509Name(object):
973 """
974 Unit tests for `OpenSSL.crypto.X509Name`.
975 """
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -0500976
Rick Deane15b1472009-07-09 15:53:42 -0500977 def test_type(self):
978 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000979 The type of X509Name objects is `X509NameType`.
Rick Deane15b1472009-07-09 15:53:42 -0500980 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000981 assert X509Name is X509NameType
982 assert X509NameType.__name__ == 'X509Name'
983 assert isinstance(X509NameType, type)
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400984
Alex Chan9e2a9932017-01-25 14:29:19 +0000985 name = x509_name()
986 assert isinstance(name, X509NameType)
Rick Deane15b1472009-07-09 15:53:42 -0500987
Alex Chan9e2a9932017-01-25 14:29:19 +0000988 def test_only_string_attributes(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -0400989 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000990 Attempting to set a non-`str` attribute name on an `X509Name` instance
991 causes `TypeError` to be raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -0400992 """
Alex Chan9e2a9932017-01-25 14:29:19 +0000993 name = x509_name()
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -0400994 # Beyond these cases, you may also think that unicode should be
Alex Gaynor31287502015-09-05 16:11:27 -0400995 # rejected. Sorry, you're wrong. unicode is automatically converted
996 # to str outside of the control of X509Name, so there's no way to
997 # reject it.
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800998
Alex Gaynor31287502015-09-05 16:11:27 -0400999 # Also, this used to test str subclasses, but that test is less
1000 # relevant now that the implementation is in Python instead of C. Also
1001 # PyPy automatically converts str subclasses to str when they are
1002 # passed to setattr, so we can't test it on PyPy. Apparently CPython
1003 # does this sometimes as well.
Alex Chan9e2a9932017-01-25 14:29:19 +00001004 with pytest.raises(TypeError):
1005 setattr(name, None, "hello")
1006 with pytest.raises(TypeError):
1007 setattr(name, 30, "hello")
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001008
Alex Chan9e2a9932017-01-25 14:29:19 +00001009 def test_set_invalid_attribute(self):
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001010 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001011 Attempting to set any attribute name on an `X509Name` instance for
1012 which no corresponding NID is defined causes `AttributeError` to be
1013 raised.
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001014 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001015 name = x509_name()
1016 with pytest.raises(AttributeError):
1017 setattr(name, "no such thing", None)
Jean-Paul Calderone9ce9afb2011-04-22 18:16:22 -04001018
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001019 def test_attributes(self):
1020 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001021 `X509Name` instances have attributes for each standard (?)
1022 X509Name field.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001023 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001024 name = x509_name()
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001025 name.commonName = "foo"
Alex Gaynor37726112016-07-04 09:51:32 -04001026 assert name.commonName == "foo"
1027 assert name.CN == "foo"
1028
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001029 name.CN = "baz"
Alex Gaynor37726112016-07-04 09:51:32 -04001030 assert name.commonName == "baz"
1031 assert name.CN == "baz"
1032
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001033 name.commonName = "bar"
Alex Gaynor37726112016-07-04 09:51:32 -04001034 assert name.commonName == "bar"
1035 assert name.CN == "bar"
1036
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001037 name.CN = "quux"
Alex Gaynor37726112016-07-04 09:51:32 -04001038 assert name.commonName == "quux"
1039 assert name.CN == "quux"
1040
1041 assert name.OU is None
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001042
Alex Gaynor7778e792016-07-03 23:38:48 -04001043 with pytest.raises(AttributeError):
1044 name.foobar
1045
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001046 def test_copy(self):
1047 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001048 `X509Name` creates a new `X509Name` instance with all the same
1049 attributes as an existing `X509Name` instance when called with one.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001050 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001051 name = x509_name(commonName="foo", emailAddress="bar@example.com")
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001052
1053 copy = X509Name(name)
Alex Chan9e2a9932017-01-25 14:29:19 +00001054 assert copy.commonName == "foo"
1055 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001056
1057 # Mutate the copy and ensure the original is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001058 copy.commonName = "baz"
Alex Chan9e2a9932017-01-25 14:29:19 +00001059 assert name.commonName == "foo"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001060
1061 # Mutate the original and ensure the copy is unmodified.
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001062 name.emailAddress = "quux@example.com"
Alex Chan9e2a9932017-01-25 14:29:19 +00001063 assert copy.emailAddress == "bar@example.com"
Jean-Paul Calderoneeff3cd92008-03-05 22:35:26 -05001064
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001065 def test_repr(self):
1066 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001067 `repr` passed an `X509Name` instance should return a string containing
1068 a description of the type and the NIDs which have been set on it.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001069 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001070 name = x509_name(commonName="foo", emailAddress="bar")
1071 assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001072
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001073 def test_comparison(self):
1074 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001075 `X509Name` instances should compare based on their NIDs.
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001076 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001077 def _equality(a, b, assert_true, assert_false):
1078 assert_true(a == b)
1079 assert_false(a != b)
1080 assert_true(b == a)
1081 assert_false(b != a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001082
Alex Chan9e2a9932017-01-25 14:29:19 +00001083 def assert_true(x):
1084 assert x
1085
1086 def assert_false(x):
1087 assert not x
1088
1089 def assert_equal(a, b):
1090 _equality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001091
1092 # Instances compare equal to themselves.
Alex Chan9e2a9932017-01-25 14:29:19 +00001093 name = x509_name()
1094 assert_equal(name, name)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001095
1096 # Empty instances should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001097 assert_equal(x509_name(), x509_name())
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001098
1099 # Instances with equal NIDs should compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001100 assert_equal(x509_name(commonName="foo"),
1101 x509_name(commonName="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001102
1103 # Instance with equal NIDs set using different aliases should compare
1104 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001105 assert_equal(x509_name(commonName="foo"),
1106 x509_name(CN="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001107
1108 # Instances with more than one NID with the same values should compare
1109 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001110 assert_equal(x509_name(CN="foo", organizationalUnitName="bar"),
1111 x509_name(commonName="foo", OU="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001112
Alex Chan9e2a9932017-01-25 14:29:19 +00001113 def assert_not_equal(a, b):
1114 _equality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001115
1116 # Instances with different values for the same NID should not compare
1117 # equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001118 assert_not_equal(x509_name(CN="foo"),
1119 x509_name(CN="bar"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001120
1121 # Instances with different NIDs should not compare equal to each other.
Alex Chan9e2a9932017-01-25 14:29:19 +00001122 assert_not_equal(x509_name(CN="foo"),
1123 x509_name(OU="foo"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001124
Alex Chan9e2a9932017-01-25 14:29:19 +00001125 assert_not_equal(x509_name(), object())
Alex Gaynor7778e792016-07-03 23:38:48 -04001126
Alex Chan9e2a9932017-01-25 14:29:19 +00001127 def _inequality(a, b, assert_true, assert_false):
1128 assert_true(a < b)
1129 assert_true(a <= b)
1130 assert_true(b > a)
1131 assert_true(b >= a)
1132 assert_false(a > b)
1133 assert_false(a >= b)
1134 assert_false(b < a)
1135 assert_false(b <= a)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001136
Alex Chan9e2a9932017-01-25 14:29:19 +00001137 def assert_less_than(a, b):
1138 _inequality(a, b, assert_true, assert_false)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001139
1140 # An X509Name with a NID with a value which sorts less than the value
1141 # of the same NID on another X509Name compares less than the other
1142 # X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001143 assert_less_than(x509_name(CN="abc"),
1144 x509_name(CN="def"))
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001145
Alex Chan9e2a9932017-01-25 14:29:19 +00001146 def assert_greater_than(a, b):
1147 _inequality(a, b, assert_false, assert_true)
Jean-Paul Calderonee098dc72008-03-06 18:36:19 -05001148
1149 # An X509Name with a NID with a value which sorts greater than the
1150 # value of the same NID on another X509Name compares greater than the
1151 # other X509Name.
Alex Chan9e2a9932017-01-25 14:29:19 +00001152 assert_greater_than(x509_name(CN="def"),
1153 x509_name(CN="abc"))
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001154
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001155 def test_hash(self):
1156 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001157 `X509Name.hash` returns an integer hash based on the value of the name.
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001158 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001159 a = x509_name(CN="foo")
1160 b = x509_name(CN="foo")
1161 assert a.hash() == b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001162 a.CN = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001163 assert a.hash() != b.hash()
Jean-Paul Calderone110cd092008-03-24 17:27:42 -04001164
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001165 def test_der(self):
1166 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001167 `X509Name.der` returns the DER encoded form of the name.
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001168 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001169 a = x509_name(CN="foo", C="US")
1170 assert (a.der() ==
1171 b'0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US'
1172 b'1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo')
Jean-Paul Calderonee957a002008-03-25 15:16:51 -04001173
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001174 def test_get_components(self):
1175 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001176 `X509Name.get_components` returns a `list` of two-tuples of `str`
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001177 giving the NIDs and associated values which make up the name.
1178 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001179 a = x509_name()
1180 assert a.get_components() == []
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001181 a.CN = "foo"
Alex Chan9e2a9932017-01-25 14:29:19 +00001182 assert a.get_components() == [(b"CN", b"foo")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001183 a.organizationalUnitName = "bar"
Alex Chan9e2a9932017-01-25 14:29:19 +00001184 assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -04001185
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001186 def test_load_nul_byte_attribute(self):
1187 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001188 An `X509Name` from an `X509` instance loaded from a file can have a
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001189 NUL byte in the value of one of its attributes.
1190 """
1191 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
1192 subject = cert.get_subject()
Alex Chan9e2a9932017-01-25 14:29:19 +00001193 assert "null.python.org\x00example.org" == subject.commonName
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001194
Alex Chan9e2a9932017-01-25 14:29:19 +00001195 def test_set_attribute_failure(self):
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001196 """
1197 If the value of an attribute cannot be set for some reason then
Alex Chan9e2a9932017-01-25 14:29:19 +00001198 `Error` is raised.
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001199 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001200 name = x509_name()
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001201 # This value is too long
Alex Chan9e2a9932017-01-25 14:29:19 +00001202 with pytest.raises(Error):
1203 setattr(name, "O", b"x" * 512)
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -05001204
1205
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001206class _PKeyInteractionTestsMixin:
1207 """
1208 Tests which involve another thing and a PKey.
1209 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001210
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001211 def signable(self):
1212 """
Alex Chanfb078d82017-04-20 11:16:15 +01001213 Return something with a `set_pubkey`, `set_pubkey`, and `sign` method.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001214 """
1215 raise NotImplementedError()
1216
Alex Chanb00ede22017-01-30 07:24:40 +00001217 def test_sign_with_ungenerated(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001218 """
Alex Chanb00ede22017-01-30 07:24:40 +00001219 `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001220 """
1221 request = self.signable()
1222 key = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001223 with pytest.raises(ValueError):
1224 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001225
Alex Chanb00ede22017-01-30 07:24:40 +00001226 def test_sign_with_public_key(self):
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001227 """
Alex Chanb00ede22017-01-30 07:24:40 +00001228 `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
1229 part as the signing key.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001230 """
1231 request = self.signable()
1232 key = PKey()
1233 key.generate_key(TYPE_RSA, 512)
1234 request.set_pubkey(key)
1235 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001236 with pytest.raises(ValueError):
1237 request.sign(pub, GOOD_DIGEST)
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001238
Alex Chanb00ede22017-01-30 07:24:40 +00001239 def test_sign_with_unknown_digest(self):
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001240 """
Alex Chanb00ede22017-01-30 07:24:40 +00001241 `X509Req.sign` raises `ValueError` when passed a digest name which is
1242 not known.
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001243 """
1244 request = self.signable()
1245 key = PKey()
1246 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001247 with pytest.raises(ValueError):
1248 request.sign(key, BAD_DIGEST)
Jean-Paul Calderonecc05a912010-08-03 18:24:19 -04001249
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001250 def test_sign(self):
1251 """
Alex Chanb00ede22017-01-30 07:24:40 +00001252 `X509Req.sign` succeeds when passed a private key object and a
1253 valid digest function. `X509Req.verify` can be used to check
Alex Gaynor31287502015-09-05 16:11:27 -04001254 the signature.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001255 """
1256 request = self.signable()
1257 key = PKey()
1258 key.generate_key(TYPE_RSA, 512)
1259 request.set_pubkey(key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001260 request.sign(key, GOOD_DIGEST)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001261 # If the type has a verify method, cover that too.
1262 if getattr(request, 'verify', None) is not None:
1263 pub = request.get_pubkey()
Alex Chanb00ede22017-01-30 07:24:40 +00001264 assert request.verify(pub)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001265 # Make another key that won't verify.
1266 key = PKey()
1267 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00001268 with pytest.raises(Error):
1269 request.verify(key)
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04001270
1271
Alex Chanb00ede22017-01-30 07:24:40 +00001272class TestX509Req(_PKeyInteractionTestsMixin):
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001273 """
Alex Chanb00ede22017-01-30 07:24:40 +00001274 Tests for `OpenSSL.crypto.X509Req`.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001275 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001276
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001277 def signable(self):
1278 """
Alex Chanb00ede22017-01-30 07:24:40 +00001279 Create and return a new `X509Req`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001280 """
1281 return X509Req()
1282
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001283 def test_type(self):
1284 """
Alex Chanb00ede22017-01-30 07:24:40 +00001285 `X509Req` and `X509ReqType` refer to the same type object and can be
1286 used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001287 """
Alex Chanb00ede22017-01-30 07:24:40 +00001288 assert X509Req is X509ReqType
1289 assert is_consistent_type(X509Req, 'X509Req')
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001290
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001291 def test_construction(self):
1292 """
Alex Chanb00ede22017-01-30 07:24:40 +00001293 `X509Req` takes no arguments and returns an `X509ReqType` instance.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001294 """
1295 request = X509Req()
Alex Gaynor31287502015-09-05 16:11:27 -04001296 assert isinstance(request, X509ReqType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001297
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001298 def test_version(self):
1299 """
Alex Chanb00ede22017-01-30 07:24:40 +00001300 `X509Req.set_version` sets the X.509 version of the certificate
1301 request. `X509Req.get_version` returns the X.509 version of the
1302 certificate request. The initial value of the version is 0.
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001303 """
1304 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001305 assert request.get_version() == 0
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001306 request.set_version(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001307 assert request.get_version() == 1
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001308 request.set_version(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001309 assert request.get_version() == 3
Jean-Paul Calderone8dd19b82008-12-28 20:41:16 -05001310
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001311 def test_version_wrong_args(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001312 """
Alex Chanb00ede22017-01-30 07:24:40 +00001313 `X509Req.set_version` raises `TypeError` if called with a non-`int`
1314 argument.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04001315 """
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001316 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001317 with pytest.raises(TypeError):
1318 request.set_version("foo")
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001319
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001320 def test_get_subject(self):
1321 """
Alex Chanb00ede22017-01-30 07:24:40 +00001322 `X509Req.get_subject` returns an `X509Name` for the subject of the
1323 request and which is valid even after the request object is
1324 otherwise dead.
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001325 """
1326 request = X509Req()
1327 subject = request.get_subject()
Alex Gaynor31287502015-09-05 16:11:27 -04001328 assert isinstance(subject, X509NameType)
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001329 subject.commonName = "foo"
Alex Chanb00ede22017-01-30 07:24:40 +00001330 assert request.get_subject().commonName == "foo"
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -05001331 del request
1332 subject.commonName = "bar"
Alex Chanb00ede22017-01-30 07:24:40 +00001333 assert subject.commonName == "bar"
Jean-Paul Calderone54e49e92010-07-30 11:04:46 -04001334
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001335 def test_add_extensions(self):
1336 """
Alex Chanb00ede22017-01-30 07:24:40 +00001337 `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
1338 and adds them to the X509 request.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001339 """
1340 request = X509Req()
1341 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001342 X509Extension(b'basicConstraints', True, b'CA:false')])
Stephen Holsappleca545b72014-01-28 21:43:25 -08001343 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001344 assert len(exts) == 1
1345 assert exts[0].get_short_name() == b'basicConstraints'
1346 assert exts[0].get_critical() == 1
1347 assert exts[0].get_data() == b'0\x00'
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001348
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001349 def test_get_extensions(self):
1350 """
Alex Chanb00ede22017-01-30 07:24:40 +00001351 `X509Req.get_extensions` returns a `list` of extensions added to this
1352 X509 request.
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001353 """
1354 request = X509Req()
1355 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001356 assert exts == []
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001357 request.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -04001358 X509Extension(b'basicConstraints', True, b'CA:true'),
1359 X509Extension(b'keyUsage', False, b'digitalSignature')])
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001360 exts = request.get_extensions()
Alex Chanb00ede22017-01-30 07:24:40 +00001361 assert len(exts) == 2
1362 assert exts[0].get_short_name() == b'basicConstraints'
1363 assert exts[0].get_critical() == 1
1364 assert exts[0].get_data() == b'0\x03\x01\x01\xff'
1365 assert exts[1].get_short_name() == b'keyUsage'
1366 assert exts[1].get_critical() == 0
1367 assert exts[1].get_data() == b'\x03\x02\x07\x80'
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001368
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001369 def test_add_extensions_wrong_args(self):
1370 """
Alex Chanb00ede22017-01-30 07:24:40 +00001371 `X509Req.add_extensions` raises `TypeError` if called with a
1372 non-`list`. Or it raises `ValueError` if called with a `list`
1373 containing objects other than `X509Extension` instances.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001374 """
1375 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001376 with pytest.raises(TypeError):
1377 request.add_extensions(object())
1378 with pytest.raises(ValueError):
1379 request.add_extensions([object()])
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001380
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001381 def test_verify_wrong_args(self):
1382 """
Alex Chanb00ede22017-01-30 07:24:40 +00001383 `X509Req.verify` raises `TypeError` if passed anything other than a
1384 `PKey` instance as its single argument.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001385 """
1386 request = X509Req()
Alex Chanb00ede22017-01-30 07:24:40 +00001387 with pytest.raises(TypeError):
1388 request.verify(object())
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001389
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001390 def test_verify_uninitialized_key(self):
1391 """
Alex Chanb00ede22017-01-30 07:24:40 +00001392 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1393 `OpenSSL.crypto.PKey` which contains no key data.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001394 """
1395 request = X509Req()
1396 pkey = PKey()
Alex Chanb00ede22017-01-30 07:24:40 +00001397 with pytest.raises(Error):
1398 request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001399
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001400 def test_verify_wrong_key(self):
1401 """
Alex Chanb00ede22017-01-30 07:24:40 +00001402 `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
1403 `OpenSSL.crypto.PKey` which does not represent the public part of the
Alex Gaynor31287502015-09-05 16:11:27 -04001404 key which signed the request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001405 """
1406 request = X509Req()
1407 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001408 request.sign(pkey, GOOD_DIGEST)
Alex Chanb00ede22017-01-30 07:24:40 +00001409 another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
1410 with pytest.raises(Error):
1411 request.verify(another_pkey)
1412
1413 def test_verify_success(self):
1414 """
1415 `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
1416 which represents the public part of the key which signed the request.
1417 """
1418 request = X509Req()
1419 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
1420 request.sign(pkey, GOOD_DIGEST)
1421 assert request.verify(pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001422
1423
Alex Chanb00ede22017-01-30 07:24:40 +00001424class TestX509(_PKeyInteractionTestsMixin):
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001425 """
Alex Chanb00ede22017-01-30 07:24:40 +00001426 Tests for `OpenSSL.crypto.X509`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001427 """
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001428 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Jean-Paul Calderone8114b452008-03-25 15:27:59 -04001429
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001430 extpem = """
1431-----BEGIN CERTIFICATE-----
1432MIIC3jCCAkegAwIBAgIJAJHFjlcCgnQzMA0GCSqGSIb3DQEBBQUAMEcxCzAJBgNV
1433BAYTAlNFMRUwEwYDVQQIEwxXZXN0ZXJib3R0b20xEjAQBgNVBAoTCUNhdGFsb2dp
1434eDENMAsGA1UEAxMEUm9vdDAeFw0wODA0MjIxNDQ1MzhaFw0wOTA0MjIxNDQ1Mzha
1435MFQxCzAJBgNVBAYTAlNFMQswCQYDVQQIEwJXQjEUMBIGA1UEChMLT3Blbk1ldGFk
1436aXIxIjAgBgNVBAMTGW5vZGUxLm9tMi5vcGVubWV0YWRpci5vcmcwgZ8wDQYJKoZI
1437hvcNAQEBBQADgY0AMIGJAoGBAPIcQMrwbk2nESF/0JKibj9i1x95XYAOwP+LarwT
1438Op4EQbdlI9SY+uqYqlERhF19w7CS+S6oyqx0DRZSk4Y9dZ9j9/xgm2u/f136YS1u
1439zgYFPvfUs6PqYLPSM8Bw+SjJ+7+2+TN+Tkiof9WP1cMjodQwOmdsiRbR0/J7+b1B
1440hec1AgMBAAGjgcQwgcEwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT
1441TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFIdHsBcMVVMbAO7j6NCj
144203HgLnHaMB8GA1UdIwQYMBaAFL2h9Bf9Mre4vTdOiHTGAt7BRY/8MEYGA1UdEQQ/
1443MD2CDSouZXhhbXBsZS5vcmeCESoub20yLmV4bWFwbGUuY29thwSC7wgKgRNvbTJA
1444b3Blbm1ldGFkaXIub3JnMA0GCSqGSIb3DQEBBQUAA4GBALd7WdXkp2KvZ7/PuWZA
1445MPlIxyjS+Ly11+BNE0xGQRp9Wz+2lABtpgNqssvU156+HkKd02rGheb2tj7MX9hG
1446uZzbwDAZzJPjzDQDD7d3cWsrVcfIdqVU7epHqIadnOF+X0ghJ39pAm6VVadnSXCt
1447WpOdIpB8KksUTCzV591Nr1wd
1448-----END CERTIFICATE-----
1449 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001450
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001451 def signable(self):
1452 """
Alex Chanb00ede22017-01-30 07:24:40 +00001453 Create and return a new `X509`.
Jean-Paul Calderoneac0d95f2008-03-10 00:00:42 -04001454 """
1455 return X509()
1456
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001457 def test_type(self):
1458 """
Alex Chanb00ede22017-01-30 07:24:40 +00001459 `X509` and `X509Type` refer to the same type object and can be used to
1460 create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001461 """
Alex Chanb00ede22017-01-30 07:24:40 +00001462 assert X509 is X509Type
1463 assert is_consistent_type(X509, 'X509')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001464
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001465 def test_construction(self):
1466 """
Alex Chanb00ede22017-01-30 07:24:40 +00001467 `X509` takes no arguments and returns an instance of `X509Type`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001468 """
1469 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001470 assert isinstance(certificate, X509Type)
1471 assert type(X509Type).__name__ == 'type'
1472 assert type(certificate).__name__ == 'X509'
1473 assert type(certificate) == X509Type
1474 assert type(certificate) == X509
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001475
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001476 def test_set_version_wrong_args(self):
1477 """
Alex Chanb00ede22017-01-30 07:24:40 +00001478 `X509.set_version` raises `TypeError` if invoked with an argument
1479 not of type `int`.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001480 """
1481 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001482 with pytest.raises(TypeError):
1483 cert.set_version(None)
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001484
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001485 def test_version(self):
1486 """
Alex Chanb00ede22017-01-30 07:24:40 +00001487 `X509.set_version` sets the certificate version number.
1488 `X509.get_version` retrieves it.
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001489 """
1490 cert = X509()
1491 cert.set_version(1234)
Alex Chanb00ede22017-01-30 07:24:40 +00001492 assert cert.get_version() == 1234
Jean-Paul Calderone3544eb42010-07-30 22:09:47 -04001493
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001494 def test_serial_number(self):
1495 """
Alex Chanb00ede22017-01-30 07:24:40 +00001496 The serial number of an `X509` can be retrieved and
1497 modified with `X509.get_serial_number` and
1498 `X509.set_serial_number`.
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001499 """
1500 certificate = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001501 with pytest.raises(TypeError):
1502 certificate.set_serial_number("1")
1503 assert certificate.get_serial_number() == 0
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001504 certificate.set_serial_number(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001505 assert certificate.get_serial_number() == 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001506 certificate.set_serial_number(2 ** 32 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001507 assert certificate.get_serial_number() == 2 ** 32 + 1
Jean-Paul Calderone78381d22008-03-06 23:35:22 -05001508 certificate.set_serial_number(2 ** 64 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001509 assert certificate.get_serial_number() == 2 ** 64 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001510 certificate.set_serial_number(2 ** 128 + 1)
Alex Chanb00ede22017-01-30 07:24:40 +00001511 assert certificate.get_serial_number() == 2 ** 128 + 1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001512
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001513 def _setBoundTest(self, which):
1514 """
Alex Chanb00ede22017-01-30 07:24:40 +00001515 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001516 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1517 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001518 """
1519 certificate = X509()
1520 set = getattr(certificate, 'set_not' + which)
1521 get = getattr(certificate, 'get_not' + which)
1522
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001523 # Starts with no value.
Alex Chanb00ede22017-01-30 07:24:40 +00001524 assert get() is None
Jean-Paul Calderonee0615b52008-03-09 21:44:46 -04001525
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001526 # GMT (Or is it UTC?) -exarkun
Alex Gaynore7f51982016-09-11 11:48:14 -04001527 when = b"20040203040506Z"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001528 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001529 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001530
1531 # A plus two hours and thirty minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001532 when = b"20040203040506+0530"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001533 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001534 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001535
1536 # A minus one hour fifteen minutes offset
Alex Gaynore7f51982016-09-11 11:48:14 -04001537 when = b"20040203040506-0115"
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001538 set(when)
Alex Chanb00ede22017-01-30 07:24:40 +00001539 assert get() == when
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001540
1541 # An invalid string results in a ValueError
Alex Chanb00ede22017-01-30 07:24:40 +00001542 with pytest.raises(ValueError):
1543 set(b"foo bar")
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001544
Jean-Paul Calderone31ca2002010-01-30 15:14:43 -05001545 # The wrong number of arguments results in a TypeError.
Alex Chanb00ede22017-01-30 07:24:40 +00001546 with pytest.raises(TypeError):
1547 set()
Alex Gaynor85b49702015-09-05 16:30:59 -04001548 with pytest.raises(TypeError):
1549 set(b"20040203040506Z", b"20040203040506Z")
Alex Chanb00ede22017-01-30 07:24:40 +00001550 with pytest.raises(TypeError):
1551 get(b"foo bar")
Jean-Paul Calderonee890db32010-08-22 16:55:15 -04001552
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001553 # XXX ASN1_TIME (not GENERALIZEDTIME)
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001554
1555 def test_set_notBefore(self):
1556 """
Alex Chanb00ede22017-01-30 07:24:40 +00001557 `X509.set_notBefore` takes a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001558 ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
1559 validity period to it.
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001560 """
1561 self._setBoundTest("Before")
1562
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001563 def test_set_notAfter(self):
1564 """
Alex Chanb00ede22017-01-30 07:24:40 +00001565 `X509.set_notAfter` takes a string in the format of an ASN1
Jean-Paul Calderone525ef802008-03-09 20:39:42 -04001566 GENERALIZEDTIME and sets the end of the certificate's validity period
1567 to it.
1568 """
1569 self._setBoundTest("After")
Jean-Paul Calderone76576d52008-03-24 16:04:46 -04001570
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001571 def test_get_notBefore(self):
1572 """
Alex Chanb00ede22017-01-30 07:24:40 +00001573 `X509.get_notBefore` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001574 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001575 internally.
1576 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001577 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001578 assert cert.get_notBefore() == b"20090325123658Z"
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04001579
Rick Dean38a05c82009-07-18 01:41:30 -05001580 def test_get_notAfter(self):
1581 """
Alex Chanb00ede22017-01-30 07:24:40 +00001582 `X509.get_notAfter` returns a string in the format of an
Alex Gaynor31287502015-09-05 16:11:27 -04001583 ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
Rick Dean38a05c82009-07-18 01:41:30 -05001584 internally.
1585 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001586 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001587 assert cert.get_notAfter() == b"20170611123658Z"
Rick Dean38a05c82009-07-18 01:41:30 -05001588
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001589 def test_gmtime_adj_notBefore_wrong_args(self):
1590 """
Alex Chanb00ede22017-01-30 07:24:40 +00001591 `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
1592 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001593 """
1594 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001595 with pytest.raises(TypeError):
1596 cert.gmtime_adj_notBefore(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001597
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001598 def test_gmtime_adj_notBefore(self):
1599 """
Alex Chanb00ede22017-01-30 07:24:40 +00001600 `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
1601 current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001602 """
1603 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001604 not_before_min = (
1605 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1606 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001607 cert.gmtime_adj_notBefore(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001608 not_before = datetime.strptime(
1609 cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
1610 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001611 not_before_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001612 assert not_before_min <= not_before <= not_before_max
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001613
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001614 def test_gmtime_adj_notAfter_wrong_args(self):
1615 """
Alex Chanb00ede22017-01-30 07:24:40 +00001616 `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
1617 non-`int` argument.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001618 """
1619 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001620 with pytest.raises(TypeError):
1621 cert.gmtime_adj_notAfter(None)
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001622
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001623 def test_gmtime_adj_notAfter(self):
1624 """
Alex Chanb00ede22017-01-30 07:24:40 +00001625 `X509.gmtime_adj_notAfter` changes the not-after timestamp
Alex Gaynor31287502015-09-05 16:11:27 -04001626 to be the current time plus the number of seconds passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001627 """
1628 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Gaynor85b49702015-09-05 16:30:59 -04001629 not_after_min = (
1630 datetime.utcnow().replace(microsecond=0) + timedelta(seconds=100)
1631 )
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001632 cert.gmtime_adj_notAfter(100)
Alex Gaynor85b49702015-09-05 16:30:59 -04001633 not_after = datetime.strptime(
1634 cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
1635 )
Maximilian Hilsbed25c92015-07-25 12:58:07 +02001636 not_after_max = datetime.utcnow() + timedelta(seconds=100)
Alex Chanb00ede22017-01-30 07:24:40 +00001637 assert not_after_min <= not_after <= not_after_max
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001638
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001639 def test_has_expired(self):
1640 """
Alex Chanb00ede22017-01-30 07:24:40 +00001641 `X509.has_expired` returns `True` if the certificate's not-after time
1642 is in the past.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001643 """
1644 cert = X509()
1645 cert.gmtime_adj_notAfter(-1)
Alex Chanb00ede22017-01-30 07:24:40 +00001646 assert cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001647
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001648 def test_has_not_expired(self):
1649 """
Alex Chanb00ede22017-01-30 07:24:40 +00001650 `X509.has_expired` returns `False` if the certificate's not-after time
1651 is in the future.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001652 """
1653 cert = X509()
1654 cert.gmtime_adj_notAfter(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001655 assert not cert.has_expired()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001656
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001657 def test_root_has_not_expired(self):
1658 """
Alex Chanb00ede22017-01-30 07:24:40 +00001659 `X509.has_expired` returns `False` if the certificate's not-after time
1660 is in the future.
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001661 """
1662 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001663 assert not cert.has_expired()
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001664
Rick Dean38a05c82009-07-18 01:41:30 -05001665 def test_digest(self):
1666 """
Alex Chanb00ede22017-01-30 07:24:40 +00001667 `X509.digest` returns a string giving ":"-separated hex-encoded
Alex Gaynor31287502015-09-05 16:11:27 -04001668 words of the digest of the certificate.
Rick Dean38a05c82009-07-18 01:41:30 -05001669 """
Paul Kehrera40898b2017-06-11 16:30:58 -10001670 cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00001671 assert (
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001672 # This is MD5 instead of GOOD_DIGEST because the digest algorithm
1673 # actually matters to the assertion (ie, another arbitrary, good
1674 # digest will not product the same digest).
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001675 # Digest verified with the command:
1676 # openssl x509 -in root_cert.pem -noout -fingerprint -md5
Alex Chanb00ede22017-01-30 07:24:40 +00001677 cert.digest("MD5") ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001678 b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75")
Rick Dean38a05c82009-07-18 01:41:30 -05001679
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001680 def _extcert(self, pkey, extensions):
1681 cert = X509()
1682 cert.set_pubkey(pkey)
1683 cert.get_subject().commonName = "Unit Tests"
1684 cert.get_issuer().commonName = "Unit Tests"
Alex Gaynore7f51982016-09-11 11:48:14 -04001685 when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001686 cert.set_notBefore(when)
1687 cert.set_notAfter(when)
1688
1689 cert.add_extensions(extensions)
Jeff Tangfc18f7b2015-04-15 17:42:33 -04001690 cert.sign(pkey, 'sha1')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001691 return load_certificate(
1692 FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert))
1693
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001694 def test_extension_count(self):
1695 """
Alex Chanb00ede22017-01-30 07:24:40 +00001696 `X509.get_extension_count` returns the number of extensions
Alex Gaynor31287502015-09-05 16:11:27 -04001697 that are present in the certificate.
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001698 """
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001699 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001700 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1701 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001702 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001703 b'subjectAltName', True, b'DNS:example.com')
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001704
1705 # Try a certificate with no extensions at all.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001706 c = self._extcert(pkey, [])
Alex Chanb00ede22017-01-30 07:24:40 +00001707 assert c.get_extension_count() == 0
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001708
1709 # And a certificate with one
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001710 c = self._extcert(pkey, [ca])
Alex Chanb00ede22017-01-30 07:24:40 +00001711 assert c.get_extension_count() == 1
Jean-Paul Calderonef7b3ee62011-04-01 17:36:24 -04001712
1713 # And a certificate with several
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001714 c = self._extcert(pkey, [ca, key, subjectAltName])
Alex Chanb00ede22017-01-30 07:24:40 +00001715 assert c.get_extension_count() == 3
Roland Hedberg7e4930e2008-04-22 22:58:50 +02001716
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001717 def test_get_extension(self):
1718 """
Alex Chanb00ede22017-01-30 07:24:40 +00001719 `X509.get_extension` takes an integer and returns an
1720 `X509Extension` corresponding to the extension at that index.
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001721 """
1722 pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04001723 ca = X509Extension(b'basicConstraints', True, b'CA:FALSE')
1724 key = X509Extension(b'keyUsage', True, b'digitalSignature')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001725 subjectAltName = X509Extension(
Alex Gaynore7f51982016-09-11 11:48:14 -04001726 b'subjectAltName', False, b'DNS:example.com')
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001727
1728 cert = self._extcert(pkey, [ca, key, subjectAltName])
1729
1730 ext = cert.get_extension(0)
Alex Chanb00ede22017-01-30 07:24:40 +00001731 assert isinstance(ext, X509Extension)
1732 assert ext.get_critical()
1733 assert ext.get_short_name() == b'basicConstraints'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001734
1735 ext = cert.get_extension(1)
Alex Chanb00ede22017-01-30 07:24:40 +00001736 assert isinstance(ext, X509Extension)
1737 assert ext.get_critical()
1738 assert ext.get_short_name() == b'keyUsage'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001739
1740 ext = cert.get_extension(2)
Alex Chanb00ede22017-01-30 07:24:40 +00001741 assert isinstance(ext, X509Extension)
1742 assert not ext.get_critical()
1743 assert ext.get_short_name() == b'subjectAltName'
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001744
Alex Chanb00ede22017-01-30 07:24:40 +00001745 with pytest.raises(IndexError):
1746 cert.get_extension(-1)
1747 with pytest.raises(IndexError):
1748 cert.get_extension(4)
1749 with pytest.raises(TypeError):
1750 cert.get_extension("hello")
Jean-Paul Calderone83a593d2011-04-01 17:45:07 -04001751
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001752 def test_nullbyte_subjectAltName(self):
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001753 """
Jean-Paul Calderone9af07b02013-08-23 16:07:31 -04001754 The fields of a `subjectAltName` extension on an X509 may contain NUL
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001755 bytes and this value is reflected in the string representation of the
1756 extension object.
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001757 """
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001758 cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
Jean-Paul Calderoneff83cdd2013-08-12 18:05:51 -04001759
1760 ext = cert.get_extension(3)
Alex Chanb00ede22017-01-30 07:24:40 +00001761 assert ext.get_short_name() == b'subjectAltName'
1762 assert (
Alex Gaynore7f51982016-09-11 11:48:14 -04001763 b"DNS:altnull.python.org\x00example.com, "
1764 b"email:null@python.org\x00user@example.org, "
1765 b"URI:http://null.python.org\x00http://example.org, "
Alex Chanb00ede22017-01-30 07:24:40 +00001766 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 -04001767 str(ext).encode("ascii"))
Jean-Paul Calderone4bf75c62013-08-23 15:39:53 -04001768
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001769 def test_invalid_digest_algorithm(self):
1770 """
Alex Chanb00ede22017-01-30 07:24:40 +00001771 `X509.digest` raises `ValueError` if called with an unrecognized hash
1772 algorithm.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04001773 """
1774 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001775 with pytest.raises(ValueError):
1776 cert.digest(BAD_DIGEST)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001777
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001778 def test_get_subject(self):
1779 """
Alex Chanb00ede22017-01-30 07:24:40 +00001780 `X509.get_subject` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001781 """
1782 cert = load_certificate(FILETYPE_PEM, self.pemData)
1783 subj = cert.get_subject()
Alex Chanb00ede22017-01-30 07:24:40 +00001784 assert isinstance(subj, X509Name)
1785 assert (
1786 subj.get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001787 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1788 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001789
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001790 def test_set_subject_wrong_args(self):
1791 """
Alex Chanb00ede22017-01-30 07:24:40 +00001792 `X509.set_subject` raises a `TypeError` if called with an argument not
1793 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001794 """
1795 cert = X509()
Alex Gaynor85b49702015-09-05 16:30:59 -04001796 with pytest.raises(TypeError):
Alex Chanb00ede22017-01-30 07:24:40 +00001797 cert.set_subject(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001798
1799 def test_set_subject(self):
1800 """
Alex Chanb00ede22017-01-30 07:24:40 +00001801 `X509.set_subject` changes the subject of the certificate to the one
1802 passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001803 """
1804 cert = X509()
1805 name = cert.get_subject()
1806 name.C = 'AU'
1807 name.O = 'Unit Tests'
1808 cert.set_subject(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001809 assert (
1810 cert.get_subject().get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001811 [(b'C', b'AU'), (b'O', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001812
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001813 def test_get_issuer(self):
1814 """
Alex Chanb00ede22017-01-30 07:24:40 +00001815 `X509.get_issuer` returns an `X509Name` instance.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001816 """
1817 cert = load_certificate(FILETYPE_PEM, self.pemData)
1818 subj = cert.get_issuer()
Alex Chanb00ede22017-01-30 07:24:40 +00001819 assert isinstance(subj, X509Name)
Jean-Paul Calderone30a4cb32010-08-11 23:54:12 -04001820 comp = subj.get_components()
Alex Chanb00ede22017-01-30 07:24:40 +00001821 assert (
1822 comp ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001823 [(b'C', b'US'), (b'ST', b'IL'), (b'L', b'Chicago'),
1824 (b'O', b'Testing'), (b'CN', b'Testing Root CA')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001825
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001826 def test_set_issuer_wrong_args(self):
1827 """
Alex Chanb00ede22017-01-30 07:24:40 +00001828 `X509.set_issuer` raises a `TypeError` if called with an argument not
1829 of type `X509Name`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001830 """
1831 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001832 with pytest.raises(TypeError):
1833 cert.set_issuer(None)
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001834
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001835 def test_set_issuer(self):
1836 """
Alex Chanb00ede22017-01-30 07:24:40 +00001837 `X509.set_issuer` changes the issuer of the certificate to the
Alex Gaynor31287502015-09-05 16:11:27 -04001838 one passed in.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001839 """
1840 cert = X509()
1841 name = cert.get_issuer()
1842 name.C = 'AU'
1843 name.O = 'Unit Tests'
1844 cert.set_issuer(name)
Alex Chanb00ede22017-01-30 07:24:40 +00001845 assert (
1846 cert.get_issuer().get_components() ==
Alex Gaynore7f51982016-09-11 11:48:14 -04001847 [(b'C', b'AU'), (b'O', b'Unit Tests')])
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001848
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001849 def test_get_pubkey_uninitialized(self):
1850 """
Alex Chanb00ede22017-01-30 07:24:40 +00001851 When called on a certificate with no public key, `X509.get_pubkey`
1852 raises `OpenSSL.crypto.Error`.
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001853 """
1854 cert = X509()
Alex Chanb00ede22017-01-30 07:24:40 +00001855 with pytest.raises(Error):
1856 cert.get_pubkey()
Jean-Paul Calderone4f237b22010-07-30 22:29:39 -04001857
Alex Gaynor7778e792016-07-03 23:38:48 -04001858 def test_set_pubkey_wrong_type(self):
1859 """
Alex Chanb00ede22017-01-30 07:24:40 +00001860 `X509.set_pubkey` raises `TypeError` when given an object of the
1861 wrong type.
Alex Gaynor7778e792016-07-03 23:38:48 -04001862 """
1863 cert = X509()
1864 with pytest.raises(TypeError):
1865 cert.set_pubkey(object())
1866
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001867 def test_subject_name_hash(self):
1868 """
Alex Chanb00ede22017-01-30 07:24:40 +00001869 `X509.subject_name_hash` returns the hash of the certificate's
Alex Gaynor31287502015-09-05 16:11:27 -04001870 subject name.
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001871 """
1872 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001873 assert cert.subject_name_hash() in [
1874 3350047874, # OpenSSL 0.9.8, MD5
1875 3278919224, # OpenSSL 1.0.0, SHA1
1876 ]
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001877
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001878 def test_get_signature_algorithm(self):
1879 """
Alex Chanb00ede22017-01-30 07:24:40 +00001880 `X509.get_signature_algorithm` returns a string which means
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001881 the algorithm used to sign the certificate.
1882 """
1883 cert = load_certificate(FILETYPE_PEM, self.pemData)
Alex Chanb00ede22017-01-30 07:24:40 +00001884 assert b"sha1WithRSAEncryption" == cert.get_signature_algorithm()
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001885
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001886 def test_get_undefined_signature_algorithm(self):
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001887 """
Alex Chanb00ede22017-01-30 07:24:40 +00001888 `X509.get_signature_algorithm` raises `ValueError` if the signature
1889 algorithm is undefined or unknown.
Jean-Paul Calderone5d8e4052011-05-19 17:51:43 -04001890 """
1891 # This certificate has been modified to indicate a bogus OID in the
1892 # signature algorithm field so that OpenSSL does not recognize it.
Alex Gaynore7f51982016-09-11 11:48:14 -04001893 certPEM = b"""\
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001894-----BEGIN CERTIFICATE-----
1895MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
1896EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
1897cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
1898MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
1899EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
1900CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
1901AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
1902+fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
1903hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
1904BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
1905FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
1906dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
1907aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
1908MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
1909jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
1910PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
1911tgI5
1912-----END CERTIFICATE-----
Alex Gaynore7f51982016-09-11 11:48:14 -04001913"""
Jean-Paul Calderone2755fa52011-05-18 19:42:10 -04001914 cert = load_certificate(FILETYPE_PEM, certPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00001915 with pytest.raises(ValueError):
1916 cert.get_signature_algorithm()
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001917
Alex Gaynor37726112016-07-04 09:51:32 -04001918 def test_sign_bad_pubkey_type(self):
1919 """
Alex Chanb00ede22017-01-30 07:24:40 +00001920 `X509.sign` raises `TypeError` when called with the wrong type.
Alex Gaynor37726112016-07-04 09:51:32 -04001921 """
1922 cert = X509()
1923 with pytest.raises(TypeError):
1924 cert.sign(object(), b"sha256")
1925
Alex Gaynor9939ba12017-06-25 16:28:24 -04001926 def test_convert_from_cryptography(self):
1927 crypto_cert = x509.load_pem_x509_certificate(
1928 intermediate_cert_pem, backend
1929 )
1930 cert = X509.from_cryptography(crypto_cert)
1931
1932 assert isinstance(cert, X509)
1933 assert cert.get_version() == crypto_cert.version.value
1934
1935 def test_convert_from_cryptography_unsupported_type(self):
1936 with pytest.raises(TypeError):
1937 X509.from_cryptography(object())
1938
1939 def test_convert_to_cryptography_key(self):
1940 cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
1941 crypto_cert = cert.to_cryptography()
1942
1943 assert isinstance(crypto_cert, x509.Certificate)
1944 assert crypto_cert.version.value == cert.get_version()
1945
Jean-Paul Calderoneccf9d482010-07-30 22:36:42 -04001946
Alex Chan9e2a9932017-01-25 14:29:19 +00001947class TestX509Store(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001948 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001949 Test for `OpenSSL.crypto.X509Store`.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001950 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04001951
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001952 def test_type(self):
1953 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001954 `X509Store` is a type object.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001955 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001956 assert X509Store is X509StoreType
1957 assert is_consistent_type(X509Store, 'X509Store')
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001958
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001959 def test_add_cert(self):
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001960 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001961 `X509Store.add_cert` adds a `X509` instance to the certificate store.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001962 """
1963 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001964 store = X509Store()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001965 store.add_cert(cert)
1966
Alex Chanfb078d82017-04-20 11:16:15 +01001967 @pytest.mark.parametrize('cert', [None, 1.0, 'cert', object()])
1968 def test_add_cert_wrong_args(self, cert):
1969 """
1970 `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
1971 as its first argument.
1972 """
1973 store = X509Store()
1974 with pytest.raises(TypeError):
1975 store.add_cert(cert)
1976
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001977 def test_add_cert_rejects_duplicate(self):
1978 """
Alex Chan9e2a9932017-01-25 14:29:19 +00001979 `X509Store.add_cert` raises `OpenSSL.crypto.Error` if an attempt is
1980 made to add the same certificate to the store more than once.
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001981 """
1982 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
1983 store = X509Store()
1984 store.add_cert(cert)
Alex Chan9e2a9932017-01-25 14:29:19 +00001985 with pytest.raises(Error):
1986 store.add_cert(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001987
1988
Alex Chanb00ede22017-01-30 07:24:40 +00001989class TestPKCS12(object):
Rick Dean623ee362009-07-17 12:22:16 -05001990 """
Alex Chanb00ede22017-01-30 07:24:40 +00001991 Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05001992 """
1993 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
1994
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04001995 def test_type(self):
1996 """
Alex Chanb00ede22017-01-30 07:24:40 +00001997 `PKCS12Type` is a type object.
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04001998 """
Alex Chanb00ede22017-01-30 07:24:40 +00001999 assert PKCS12 is PKCS12Type
2000 assert is_consistent_type(PKCS12, 'PKCS12')
Jean-Paul Calderonec3a41f72009-07-25 12:36:02 -04002001
Rick Deanf94096c2009-07-18 14:23:06 -05002002 def test_empty_construction(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002003 """
Alex Chanb00ede22017-01-30 07:24:40 +00002004 `PKCS12` returns a new instance of `PKCS12` with no certificate,
2005 private key, CA certificates, or friendly name.
Rick Dean38a05c82009-07-18 01:41:30 -05002006 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002007 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002008 assert None is p12.get_certificate()
2009 assert None is p12.get_privatekey()
2010 assert None is p12.get_ca_certificates()
2011 assert None is p12.get_friendlyname()
Rick Dean623ee362009-07-17 12:22:16 -05002012
2013 def test_type_errors(self):
Rick Dean38a05c82009-07-18 01:41:30 -05002014 """
Alex Chanb00ede22017-01-30 07:24:40 +00002015 The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
2016 `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
2017 when passed objects of types other than those expected.
Rick Dean38a05c82009-07-18 01:41:30 -05002018 """
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002019 p12 = PKCS12()
Alex Chanb00ede22017-01-30 07:24:40 +00002020 for bad_arg in [3, PKey(), X509]:
2021 with pytest.raises(TypeError):
2022 p12.set_certificate(bad_arg)
2023 for bad_arg in [3, 'legbone', X509()]:
2024 with pytest.raises(TypeError):
2025 p12.set_privatekey(bad_arg)
2026 for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
2027 with pytest.raises(TypeError):
2028 p12.set_ca_certificates(bad_arg)
2029 for bad_arg in [6, ('foo', 'bar')]:
2030 with pytest.raises(TypeError):
2031 p12.set_friendlyname(bad_arg)
Rick Dean623ee362009-07-17 12:22:16 -05002032
2033 def test_key_only(self):
2034 """
Alex Chanb00ede22017-01-30 07:24:40 +00002035 A `PKCS12` with only a private key can be exported using
2036 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002037 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002038 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002039 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002040 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002041 p12.set_privatekey(pkey)
Alex Chanb00ede22017-01-30 07:24:40 +00002042 assert None is p12.get_certificate()
2043 assert pkey == p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002044 try:
2045 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2046 except Error:
2047 # Some versions of OpenSSL will throw an exception
2048 # for this nearly useless PKCS12 we tried to generate:
2049 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2050 return
Rick Dean623ee362009-07-17 12:22:16 -05002051 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002052 assert None is p12.get_ca_certificates()
2053 assert None is p12.get_certificate()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002054
2055 # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
2056 # future this will be improved.
Alex Chanb00ede22017-01-30 07:24:40 +00002057 assert isinstance(p12.get_privatekey(), (PKey, type(None)))
Rick Dean623ee362009-07-17 12:22:16 -05002058
2059 def test_cert_only(self):
2060 """
Alex Chanb00ede22017-01-30 07:24:40 +00002061 A `PKCS12` with only a certificate can be exported using
2062 `PKCS12.export` and loaded again using `load_pkcs12`.
Rick Dean623ee362009-07-17 12:22:16 -05002063 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002064 passwd = b"blah"
Rick Dean623ee362009-07-17 12:22:16 -05002065 p12 = PKCS12()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002066 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002067 p12.set_certificate(cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002068 assert cert == p12.get_certificate()
2069 assert None is p12.get_privatekey()
Rick Dean321a0512009-08-13 17:21:29 -05002070 try:
2071 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
2072 except Error:
2073 # Some versions of OpenSSL will throw an exception
2074 # for this nearly useless PKCS12 we tried to generate:
2075 # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
2076 return
Rick Dean623ee362009-07-17 12:22:16 -05002077 p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002078 assert None is p12.get_privatekey()
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002079
2080 # OpenSSL fails to bring the cert back to us. Groany mcgroan.
Alex Chanb00ede22017-01-30 07:24:40 +00002081 assert isinstance(p12.get_certificate(), (X509, type(None)))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002082
2083 # Oh ho. It puts the certificate into the ca certificates list, in
2084 # fact. Totally bogus, I would think. Nevertheless, let's exploit
2085 # that to check to see if it reconstructed the certificate we expected
2086 # it to. At some point, hopefully this will change so that
2087 # p12.get_certificate() is actually what returns the loaded
2088 # certificate.
Alex Chanb00ede22017-01-30 07:24:40 +00002089 assert (
2090 cleartextCertificatePEM ==
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002091 dump_certificate(FILETYPE_PEM, p12.get_ca_certificates()[0]))
Rick Dean623ee362009-07-17 12:22:16 -05002092
Alex Gaynor31287502015-09-05 16:11:27 -04002093 def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None,
2094 friendly_name=None):
Rick Dean623ee362009-07-17 12:22:16 -05002095 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002096 Generate a PKCS12 object with components from PEM. Verify that the set
2097 functions return None.
Rick Dean623ee362009-07-17 12:22:16 -05002098 """
Rick Deanf94096c2009-07-18 14:23:06 -05002099 p12 = PKCS12()
2100 if cert_pem:
2101 ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002102 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002103 if key_pem:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002104 ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
Alex Chanb00ede22017-01-30 07:24:40 +00002105 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002106 if ca_pem:
Alex Gaynor85b49702015-09-05 16:30:59 -04002107 ret = p12.set_ca_certificates(
2108 (load_certificate(FILETYPE_PEM, ca_pem),)
2109 )
Alex Chanb00ede22017-01-30 07:24:40 +00002110 assert ret is None
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002111 if friendly_name:
2112 ret = p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002113 assert ret is None
Rick Deanf94096c2009-07-18 14:23:06 -05002114 return p12
2115
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002116 def check_recovery(self, p12_str, key=None, cert=None, ca=None, passwd=b"",
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002117 extra=()):
Rick Deanf94096c2009-07-18 14:23:06 -05002118 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002119 Use openssl program to confirm three components are recoverable from a
2120 PKCS12 string.
Rick Deanf94096c2009-07-18 14:23:06 -05002121 """
2122 if key:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002123 recovered_key = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002124 p12_str, b"pkcs12", b"-nocerts", b"-nodes", b"-passin",
2125 b"pass:" + passwd, *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002126 assert recovered_key[-len(key):] == key
Rick Deanf94096c2009-07-18 14:23:06 -05002127 if cert:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002128 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002129 p12_str, b"pkcs12", b"-clcerts", b"-nodes", b"-passin",
2130 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002131 assert recovered_cert[-len(cert):] == cert
Rick Deanf94096c2009-07-18 14:23:06 -05002132 if ca:
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002133 recovered_cert = _runopenssl(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002134 p12_str, b"pkcs12", b"-cacerts", b"-nodes", b"-passin",
2135 b"pass:" + passwd, b"-nokeys", *extra)
Alex Chanb00ede22017-01-30 07:24:40 +00002136 assert recovered_cert[-len(ca):] == ca
Rick Deanf94096c2009-07-18 14:23:06 -05002137
Stephen Holsapple38482622014-04-05 20:29:34 -07002138 def verify_pkcs12_container(self, p12):
2139 """
2140 Verify that the PKCS#12 container contains the correct client
2141 certificate and private key.
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002142
2143 :param p12: The PKCS12 instance to verify.
Alex Chanb00ede22017-01-30 07:24:40 +00002144 :type p12: `PKCS12`
Stephen Holsapple38482622014-04-05 20:29:34 -07002145 """
2146 cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
2147 key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
Alex Chanb00ede22017-01-30 07:24:40 +00002148 assert (
2149 (client_cert_pem, client_key_pem, None) ==
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002150 (cert_pem, key_pem, p12.get_ca_certificates()))
Stephen Holsapple38482622014-04-05 20:29:34 -07002151
Rick Deanf94096c2009-07-18 14:23:06 -05002152 def test_load_pkcs12(self):
2153 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002154 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002155 with `load_pkcs12` and its components extracted and examined.
Rick Deanf94096c2009-07-18 14:23:06 -05002156 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002157 passwd = b"whatever"
Rick Dean623ee362009-07-17 12:22:16 -05002158 pem = client_key_pem + client_cert_pem
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002159 p12_str = _runopenssl(
Alex Gaynor85b49702015-09-05 16:30:59 -04002160 pem,
2161 b"pkcs12",
2162 b"-export",
2163 b"-clcerts",
2164 b"-passout",
2165 b"pass:" + passwd
2166 )
Stephen Holsapple38482622014-04-05 20:29:34 -07002167 p12 = load_pkcs12(p12_str, passphrase=passwd)
2168 self.verify_pkcs12_container(p12)
2169
Abraham Martinc5484ba2015-03-25 15:33:05 +00002170 def test_load_pkcs12_text_passphrase(self):
2171 """
2172 A PKCS12 string generated using the openssl command line can be loaded
Alex Chanb00ede22017-01-30 07:24:40 +00002173 with `load_pkcs12` and its components extracted and examined.
Abraham Martinc5484ba2015-03-25 15:33:05 +00002174 Using text as passphrase instead of bytes. DeprecationWarning expected.
2175 """
2176 pem = client_key_pem + client_cert_pem
2177 passwd = b"whatever"
2178 p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts",
2179 b"-passout", b"pass:" + passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002180 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002181 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002182 p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002183 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002184 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002185 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002186 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002187
Abraham Martinc5484ba2015-03-25 15:33:05 +00002188 self.verify_pkcs12_container(p12)
2189
Stephen Holsapple38482622014-04-05 20:29:34 -07002190 def test_load_pkcs12_no_passphrase(self):
2191 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002192 A PKCS12 string generated using openssl command line can be loaded with
Alex Chanb00ede22017-01-30 07:24:40 +00002193 `load_pkcs12` without a passphrase and its components extracted
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002194 and examined.
Stephen Holsapple38482622014-04-05 20:29:34 -07002195 """
2196 pem = client_key_pem + client_cert_pem
2197 p12_str = _runopenssl(
2198 pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:")
2199 p12 = load_pkcs12(p12_str)
2200 self.verify_pkcs12_container(p12)
2201
Stephen Holsapple38482622014-04-05 20:29:34 -07002202 def _dump_and_load(self, dump_passphrase, load_passphrase):
2203 """
2204 A helper method to dump and load a PKCS12 object.
2205 """
2206 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
2207 dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
2208 return load_pkcs12(dumped_p12, passphrase=load_passphrase)
2209
Stephen Holsapple38482622014-04-05 20:29:34 -07002210 def test_load_pkcs12_null_passphrase_load_empty(self):
2211 """
2212 A PKCS12 string can be dumped with a null passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002213 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002214 extracted and examined.
2215 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002216 self.verify_pkcs12_container(
2217 self._dump_and_load(dump_passphrase=None, load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002218
Stephen Holsapple38482622014-04-05 20:29:34 -07002219 def test_load_pkcs12_null_passphrase_load_null(self):
2220 """
2221 A PKCS12 string can be dumped with a null passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002222 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002223 extracted and examined.
2224 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002225 self.verify_pkcs12_container(
2226 self._dump_and_load(dump_passphrase=None, load_passphrase=None))
Stephen Holsapple38482622014-04-05 20:29:34 -07002227
Stephen Holsapple38482622014-04-05 20:29:34 -07002228 def test_load_pkcs12_empty_passphrase_load_empty(self):
2229 """
2230 A PKCS12 string can be dumped with an empty passphrase, loaded with an
Alex Chanb00ede22017-01-30 07:24:40 +00002231 empty passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002232 extracted and examined.
2233 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002234 self.verify_pkcs12_container(
2235 self._dump_and_load(dump_passphrase=b'', load_passphrase=b''))
Stephen Holsapple38482622014-04-05 20:29:34 -07002236
Stephen Holsapple38482622014-04-05 20:29:34 -07002237 def test_load_pkcs12_empty_passphrase_load_null(self):
2238 """
2239 A PKCS12 string can be dumped with an empty passphrase, loaded with a
Alex Chanb00ede22017-01-30 07:24:40 +00002240 null passphrase with `load_pkcs12`, and its components
Stephen Holsapple38482622014-04-05 20:29:34 -07002241 extracted and examined.
2242 """
Jean-Paul Calderonef0ff13b2014-05-05 12:48:33 -04002243 self.verify_pkcs12_container(
2244 self._dump_and_load(dump_passphrase=b'', load_passphrase=None))
Rick Deanf94096c2009-07-18 14:23:06 -05002245
Rick Deanee568302009-07-24 09:56:29 -05002246 def test_load_pkcs12_garbage(self):
2247 """
Alex Chanb00ede22017-01-30 07:24:40 +00002248 `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
Alex Gaynor85b49702015-09-05 16:30:59 -04002249 a string which is not a PKCS12 dump.
Rick Deanee568302009-07-24 09:56:29 -05002250 """
2251 passwd = 'whatever'
Alex Chanb00ede22017-01-30 07:24:40 +00002252 with pytest.raises(Error) as err:
2253 load_pkcs12(b'fruit loops', passwd)
2254 assert err.value.args[0][0][0] == 'asn1 encoding routines'
2255 assert len(err.value.args[0][0]) == 3
Rick Deanee568302009-07-24 09:56:29 -05002256
Rick Deanf94096c2009-07-18 14:23:06 -05002257 def test_replace(self):
2258 """
Alex Chanb00ede22017-01-30 07:24:40 +00002259 `PKCS12.set_certificate` replaces the certificate in a PKCS12
2260 cluster. `PKCS12.set_privatekey` replaces the private key.
2261 `PKCS12.set_ca_certificates` replaces the CA certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002262 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002263 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
2264 p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2265 p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002266 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002267 client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002268 p12.set_ca_certificates([root_cert]) # not a tuple
Alex Chanb00ede22017-01-30 07:24:40 +00002269 assert 1 == len(p12.get_ca_certificates())
2270 assert root_cert == p12.get_ca_certificates()[0]
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002271 p12.set_ca_certificates([client_cert, root_cert])
Alex Chanb00ede22017-01-30 07:24:40 +00002272 assert 2 == len(p12.get_ca_certificates())
2273 assert client_cert == p12.get_ca_certificates()[0]
2274 assert root_cert == p12.get_ca_certificates()[1]
Rick Deanf94096c2009-07-18 14:23:06 -05002275
Rick Deanf94096c2009-07-18 14:23:06 -05002276 def test_friendly_name(self):
2277 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002278 The *friendlyName* of a PKCS12 can be set and retrieved via
Alex Chanb00ede22017-01-30 07:24:40 +00002279 `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
2280 `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
Rick Deanf94096c2009-07-18 14:23:06 -05002281 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002282 passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002283 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Alex Gaynore7f51982016-09-11 11:48:14 -04002284 for friendly_name in [b'Serverlicious', None, b'###']:
Rick Dean42d69e12009-07-20 11:36:08 -05002285 p12.set_friendlyname(friendly_name)
Alex Chanb00ede22017-01-30 07:24:40 +00002286 assert p12.get_friendlyname() == friendly_name
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002287 dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
Rick Dean42d69e12009-07-20 11:36:08 -05002288 reloaded_p12 = load_pkcs12(dumped_p12, passwd)
Alex Chanb00ede22017-01-30 07:24:40 +00002289 assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
Jean-Paul Calderonea202edb2009-07-25 12:22:12 -04002290 # We would use the openssl program to confirm the friendly
2291 # name, but it is not possible. The pkcs12 command
2292 # does not store the friendly name in the cert's
Rick Dean42d69e12009-07-20 11:36:08 -05002293 # alias, which we could then extract.
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002294 self.check_recovery(
2295 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2296 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002297
Rick Deanf94096c2009-07-18 14:23:06 -05002298 def test_various_empty_passphrases(self):
2299 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002300 Test that missing, None, and '' passphrases are identical for PKCS12
2301 export.
Rick Deanf94096c2009-07-18 14:23:06 -05002302 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002303 p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002304 passwd = b""
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002305 dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
2306 dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
2307 dumped_p12_nopw = p12.export(iter=9, maciter=4)
2308 for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
2309 self.check_recovery(
2310 dumped_p12, key=client_key_pem, cert=client_cert_pem,
2311 ca=root_cert_pem, passwd=passwd)
Rick Deanf94096c2009-07-18 14:23:06 -05002312
Rick Deanf94096c2009-07-18 14:23:06 -05002313 def test_removing_ca_cert(self):
2314 """
Alex Chanb00ede22017-01-30 07:24:40 +00002315 Passing `None` to `PKCS12.set_ca_certificates` removes all CA
2316 certificates.
Rick Deanf94096c2009-07-18 14:23:06 -05002317 """
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002318 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2319 p12.set_ca_certificates(None)
Alex Chanb00ede22017-01-30 07:24:40 +00002320 assert None is p12.get_ca_certificates()
Rick Deanf94096c2009-07-18 14:23:06 -05002321
Rick Deanf94096c2009-07-18 14:23:06 -05002322 def test_export_without_mac(self):
2323 """
Alex Chanb00ede22017-01-30 07:24:40 +00002324 Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
Rick Deanf94096c2009-07-18 14:23:06 -05002325 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002326 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002327 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Dean623ee362009-07-17 12:22:16 -05002328 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002329 self.check_recovery(
2330 dumped_p12, key=server_key_pem, cert=server_cert_pem,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002331 passwd=passwd, extra=(b"-nomacver",))
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002332
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002333 def test_load_without_mac(self):
2334 """
2335 Loading a PKCS12 without a MAC does something other than crash.
2336 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002337 passwd = b"Lake Michigan"
Jean-Paul Calderone7426ed82009-07-25 21:19:23 -04002338 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2339 dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
Rick Dean321a0512009-08-13 17:21:29 -05002340 try:
2341 recovered_p12 = load_pkcs12(dumped_p12, passwd)
2342 # The person who generated this PCKS12 should be flogged,
2343 # or better yet we should have a means to determine
2344 # whether a PCKS12 had a MAC that was verified.
2345 # Anyway, libopenssl chooses to allow it, so the
2346 # pyopenssl binding does as well.
Alex Chanb00ede22017-01-30 07:24:40 +00002347 assert isinstance(recovered_p12, PKCS12)
Rick Dean321a0512009-08-13 17:21:29 -05002348 except Error:
2349 # Failing here with an exception is preferred as some openssl
2350 # versions do.
2351 pass
Rick Dean623ee362009-07-17 12:22:16 -05002352
Rick Dean25bcc1f2009-07-20 11:53:13 -05002353 def test_zero_len_list_for_ca(self):
2354 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002355 A PKCS12 with an empty CA certificates list can be exported.
Rick Dean25bcc1f2009-07-20 11:53:13 -05002356 """
Alex Gaynor6575bd12015-09-05 16:44:36 -04002357 passwd = b'Hobie 18'
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002358 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
Alex Gaynor85b49702015-09-05 16:30:59 -04002359 p12.set_ca_certificates([])
Alex Chanb00ede22017-01-30 07:24:40 +00002360 assert () == p12.get_ca_certificates()
Alex Gaynor85b49702015-09-05 16:30:59 -04002361 dumped_p12 = p12.export(passphrase=passwd, iter=3)
2362 self.check_recovery(
2363 dumped_p12, key=server_key_pem, cert=server_cert_pem,
2364 passwd=passwd)
Rick Dean25bcc1f2009-07-20 11:53:13 -05002365
Rick Deanf94096c2009-07-18 14:23:06 -05002366 def test_export_without_args(self):
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002367 """
Alex Chanb00ede22017-01-30 07:24:40 +00002368 All the arguments to `PKCS12.export` are optional.
Jean-Paul Calderone38a646d2008-03-25 15:16:18 -04002369 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002370 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
Rick Deanf94096c2009-07-18 14:23:06 -05002371 dumped_p12 = p12.export() # no args
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002372 self.check_recovery(
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002373 dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b"")
Rick Deanf94096c2009-07-18 14:23:06 -05002374
Abraham Martinc5484ba2015-03-25 15:33:05 +00002375 def test_export_without_bytes(self):
2376 """
Alex Chanb00ede22017-01-30 07:24:40 +00002377 Test `PKCS12.export` with text not bytes as passphrase
Abraham Martinc5484ba2015-03-25 15:33:05 +00002378 """
2379 p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
2380
Alex Chanb00ede22017-01-30 07:24:40 +00002381 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00002382 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002383 dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
Alex Chanb00ede22017-01-30 07:24:40 +00002384 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002385 "{0} for passphrase is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002386 WARNING_TYPE_EXPECTED
Alex Chanb00ede22017-01-30 07:24:40 +00002387 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00002388 self.check_recovery(
Alex Gaynor791212d2015-09-05 15:46:08 -04002389 dumped_p12,
2390 key=server_key_pem,
2391 cert=server_cert_pem,
2392 passwd=b"randomtext"
2393 )
Abraham Martinc5484ba2015-03-25 15:33:05 +00002394
Rick Deanf94096c2009-07-18 14:23:06 -05002395 def test_key_cert_mismatch(self):
2396 """
Alex Chanb00ede22017-01-30 07:24:40 +00002397 `PKCS12.export` raises an exception when a key and certificate
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002398 mismatch.
Rick Deanf94096c2009-07-18 14:23:06 -05002399 """
Jean-Paul Calderoneda1ffa72009-07-25 21:24:34 -04002400 p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
Alex Chanb00ede22017-01-30 07:24:40 +00002401 with pytest.raises(Error):
2402 p12.export()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002403
2404
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002405# These quoting functions taken directly from Twisted's twisted.python.win32.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002406_cmdLineQuoteRe = re.compile(br'(\\*)"')
2407_cmdLineQuoteRe2 = re.compile(br'(\\+)\Z')
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002408
2409
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002410def cmdLineQuote(s):
2411 """
2412 Internal method for quoting a single command-line argument.
2413
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002414 See http://www.perlmonks.org/?node_id=764004
2415
Jonathan Ballet648875f2011-07-16 14:14:58 +09002416 :type: :py:obj:`str`
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002417 :param s: A single unquoted string to quote for something that is expecting
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002418 cmd.exe-style quoting
2419
Jonathan Ballet648875f2011-07-16 14:14:58 +09002420 :rtype: :py:obj:`str`
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002421 :return: A cmd.exe-style quoted string
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002422 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002423 s = _cmdLineQuoteRe2.sub(br"\1\1", _cmdLineQuoteRe.sub(br'\1\1\\"', s))
2424 return b'"' + s + b'"'
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002425
2426
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002427def quoteArguments(arguments):
2428 """
2429 Quote an iterable of command-line arguments for passing to CreateProcess or
Alex Gaynor791212d2015-09-05 15:46:08 -04002430 a similar API. This allows the list passed to
2431 :py:obj:`reactor.spawnProcess` to match the child process's
2432 :py:obj:`sys.argv` properly.
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002433
Jonathan Ballet648875f2011-07-16 14:14:58 +09002434 :type arguments: :py:obj:`iterable` of :py:obj:`str`
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002435 :param arguments: An iterable of unquoted arguments to quote
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002436
Jonathan Ballet648875f2011-07-16 14:14:58 +09002437 :rtype: :py:obj:`str`
Alex Gaynor791212d2015-09-05 15:46:08 -04002438 :return: A space-delimited string containing quoted versions of
2439 :py:obj:`arguments`
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002440 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002441 return b' '.join(map(cmdLineQuote, arguments))
Jean-Paul Calderone7b874db2009-08-27 12:32:47 -04002442
2443
Rick Dean4c9ad612009-07-17 15:05:22 -05002444def _runopenssl(pem, *args):
2445 """
2446 Run the command line openssl tool with the given arguments and write
Rick Dean55d1ce62009-08-13 17:40:24 -05002447 the given PEM to its stdin. Not safe for quotes.
Rick Dean4c9ad612009-07-17 15:05:22 -05002448 """
Jean-Paul Calderone038de952009-08-21 12:16:06 -04002449 if os.name == 'posix':
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002450 command = b"openssl " + b" ".join([
Alex Gaynor85b49702015-09-05 16:30:59 -04002451 (b"'" + arg.replace(b"'", b"'\\''") + b"'")
2452 for arg in args
2453 ])
Rick Dean55d1ce62009-08-13 17:40:24 -05002454 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002455 command = b"openssl " + quoteArguments(args)
2456 proc = Popen(native(command), shell=True, stdin=PIPE, stdout=PIPE)
Jean-Paul Calderone62ca8da2010-08-11 19:58:08 -04002457 proc.stdin.write(pem)
2458 proc.stdin.close()
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002459 output = proc.stdout.read()
2460 proc.stdout.close()
2461 proc.wait()
2462 return output
Rick Dean4c9ad612009-07-17 15:05:22 -05002463
2464
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002465class TestLoadPublicKey(object):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002466 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002467 Tests for :func:`load_publickey`.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002468 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002469 def test_loading_works(self):
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002470 """
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002471 load_publickey loads public keys and sets correct attributes.
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002472 """
2473 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
Hynek Schlawack40d448f2016-06-03 16:15:14 -07002474
2475 assert True is key._only_public
2476 assert 2048 == key.bits()
2477 assert TYPE_RSA == key.type()
2478
2479 def test_invalid_type(self):
2480 """
2481 load_publickey doesn't support FILETYPE_TEXT.
2482 """
2483 with pytest.raises(ValueError):
2484 load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
2485
2486 def test_invalid_key_format(self):
2487 """
2488 load_publickey explodes on incorrect keys.
2489 """
2490 with pytest.raises(Error):
2491 load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
2492
2493 def test_tolerates_unicode_strings(self):
2494 """
2495 load_publickey works with text strings, not just bytes.
2496 """
2497 serialized = cleartextPublicKeyPEM.decode('ascii')
2498 key = load_publickey(FILETYPE_PEM, serialized)
2499 dumped_pem = dump_publickey(FILETYPE_PEM, key)
2500
2501 assert dumped_pem == cleartextPublicKeyPEM
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002502
2503
Alex Chanb00ede22017-01-30 07:24:40 +00002504class TestFunction(object):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002505 """
Alex Chanb00ede22017-01-30 07:24:40 +00002506 Tests for free-functions in the `OpenSSL.crypto` module.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002507 """
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002508
2509 def test_load_privatekey_invalid_format(self):
2510 """
Alex Chanb00ede22017-01-30 07:24:40 +00002511 `load_privatekey` raises `ValueError` if passed an unknown filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002512 """
Alex Chanb00ede22017-01-30 07:24:40 +00002513 with pytest.raises(ValueError):
2514 load_privatekey(100, root_key_pem)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002515
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002516 def test_load_privatekey_invalid_passphrase_type(self):
2517 """
Alex Chanb00ede22017-01-30 07:24:40 +00002518 `load_privatekey` raises `TypeError` if passed a passphrase that is
2519 neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002520 """
Alex Chanb00ede22017-01-30 07:24:40 +00002521 with pytest.raises(TypeError):
2522 load_privatekey(
2523 FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002524
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002525 def test_load_privatekey_wrongPassphrase(self):
2526 """
Alex Chanb00ede22017-01-30 07:24:40 +00002527 `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
2528 encrypted PEM and an incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002529 """
Alex Chanb00ede22017-01-30 07:24:40 +00002530 with pytest.raises(Error) as err:
2531 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
2532 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002533
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002534 def test_load_privatekey_passphraseWrongType(self):
2535 """
Alex Chanb00ede22017-01-30 07:24:40 +00002536 `load_privatekey` raises `ValueError` when it is passeda passphrase
2537 with a private key encoded in a format, that doesn't support
2538 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002539 """
2540 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2541 blob = dump_privatekey(FILETYPE_ASN1, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002542 with pytest.raises(ValueError):
2543 load_privatekey(FILETYPE_ASN1, blob, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002544
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002545 def test_load_privatekey_passphrase(self):
2546 """
Alex Chanb00ede22017-01-30 07:24:40 +00002547 `load_privatekey` can create a `PKey` object from an encrypted PEM
2548 string if given the passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002549 """
2550 key = load_privatekey(
2551 FILETYPE_PEM, encryptedPrivateKeyPEM,
2552 encryptedPrivateKeyPEMPassphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002553 assert isinstance(key, PKeyType)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002554
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002555 def test_load_privatekey_passphrase_exception(self):
2556 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002557 If the passphrase callback raises an exception, that exception is
Alex Chanb00ede22017-01-30 07:24:40 +00002558 raised by `load_privatekey`.
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002559 """
2560 def cb(ignored):
2561 raise ArithmeticError
2562
Alex Gaynor791212d2015-09-05 15:46:08 -04002563 with pytest.raises(ArithmeticError):
2564 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002565
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002566 def test_load_privatekey_wrongPassphraseCallback(self):
2567 """
Alex Chanb00ede22017-01-30 07:24:40 +00002568 `load_privatekey` raises `OpenSSL.crypto.Error` when it
Jean-Paul Calderoned440a082011-09-14 11:02:05 -04002569 is passed an encrypted PEM and a passphrase callback which returns an
2570 incorrect passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002571 """
2572 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002573
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002574 def cb(*a):
2575 called.append(None)
Alex Gaynore7f51982016-09-11 11:48:14 -04002576 return b"quack"
Alex Chanb00ede22017-01-30 07:24:40 +00002577 with pytest.raises(Error) as err:
2578 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
2579 assert called
2580 assert err.value.args[0] != []
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002581
2582 def test_load_privatekey_passphraseCallback(self):
2583 """
Alex Chanb00ede22017-01-30 07:24:40 +00002584 `load_privatekey` can create a `PKey` object from an encrypted PEM
2585 string if given a passphrase callback which returns the correct
2586 password.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002587 """
2588 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002589
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002590 def cb(writing):
2591 called.append(writing)
2592 return encryptedPrivateKeyPEMPassphrase
2593 key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002594 assert isinstance(key, PKeyType)
2595 assert called == [False]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002596
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002597 def test_load_privatekey_passphrase_wrong_return_type(self):
2598 """
Alex Chanb00ede22017-01-30 07:24:40 +00002599 `load_privatekey` raises `ValueError` if the passphrase callback
2600 returns something other than a byte string.
Jean-Paul Calderone105cb952011-09-14 10:16:46 -04002601 """
Alex Chanb00ede22017-01-30 07:24:40 +00002602 with pytest.raises(ValueError):
2603 load_privatekey(
2604 FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002605
Alex Chanfb078d82017-04-20 11:16:15 +01002606 def test_dump_privatekey_wrong_args(self):
2607 """
2608 `dump_privatekey` raises `TypeError` if called with a `cipher`
2609 argument but no `passphrase` argument.
2610 """
2611 key = PKey()
2612 key.generate_key(TYPE_RSA, 512)
2613 with pytest.raises(TypeError):
2614 dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
2615
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002616 def test_dump_privatekey_unknown_cipher(self):
2617 """
Alex Chanb00ede22017-01-30 07:24:40 +00002618 `dump_privatekey` raises `ValueError` if called with an unrecognized
2619 cipher name.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002620 """
2621 key = PKey()
2622 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002623 with pytest.raises(ValueError):
2624 dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002625
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002626 def test_dump_privatekey_invalid_passphrase_type(self):
2627 """
Alex Chanb00ede22017-01-30 07:24:40 +00002628 `dump_privatekey` raises `TypeError` if called with a passphrase which
2629 is neither a `str` nor a callable.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002630 """
2631 key = PKey()
2632 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002633 with pytest.raises(TypeError):
2634 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002635
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002636 def test_dump_privatekey_invalid_filetype(self):
2637 """
Alex Chanb00ede22017-01-30 07:24:40 +00002638 `dump_privatekey` raises `ValueError` if called with an unrecognized
2639 filetype.
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002640 """
2641 key = PKey()
2642 key.generate_key(TYPE_RSA, 512)
Alex Chanb00ede22017-01-30 07:24:40 +00002643 with pytest.raises(ValueError):
2644 dump_privatekey(100, key)
Jean-Paul Calderonefe1b9bd2010-08-03 18:00:21 -04002645
Alex Chanb00ede22017-01-30 07:24:40 +00002646 def test_load_privatekey_passphrase_callback_length(self):
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002647 """
Alex Chanb00ede22017-01-30 07:24:40 +00002648 `crypto.load_privatekey` should raise an error when the passphrase
2649 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002650 """
2651 def cb(ignored):
2652 return "a" * 1025
2653
Alex Gaynor791212d2015-09-05 15:46:08 -04002654 with pytest.raises(ValueError):
2655 load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002656
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002657 def test_dump_privatekey_passphrase(self):
2658 """
Alex Chanb00ede22017-01-30 07:24:40 +00002659 `dump_privatekey` writes an encrypted PEM when given a passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002660 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002661 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002662 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002663 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002664 assert isinstance(pem, binary_type)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002665 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002666 assert isinstance(loadedKey, PKeyType)
2667 assert loadedKey.type() == key.type()
2668 assert loadedKey.bits() == key.bits()
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002669
Alex Chanb00ede22017-01-30 07:24:40 +00002670 def test_dump_privatekey_passphrase_wrong_type(self):
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002671 """
Alex Chanb00ede22017-01-30 07:24:40 +00002672 `dump_privatekey` raises `ValueError` when it is passed a passphrase
2673 with a private key encoded in a format, that doesn't support
2674 encryption.
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002675 """
2676 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor791212d2015-09-05 15:46:08 -04002677 with pytest.raises(ValueError):
2678 dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
Ziga Seilnacht376cf972009-12-22 16:04:10 +01002679
Rick Dean5b7b6372009-04-01 11:34:06 -05002680 def test_dump_certificate(self):
2681 """
Alex Chanb00ede22017-01-30 07:24:40 +00002682 `dump_certificate` writes PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002683 """
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002684 pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002685 cert = load_certificate(FILETYPE_PEM, pemData)
2686 dumped_pem = dump_certificate(FILETYPE_PEM, cert)
Alex Chanb00ede22017-01-30 07:24:40 +00002687 assert dumped_pem == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002688 dumped_der = dump_certificate(FILETYPE_ASN1, cert)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002689 good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002690 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002691 cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
2692 dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
Alex Chanb00ede22017-01-30 07:24:40 +00002693 assert dumped_pem2 == cleartextCertificatePEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002694 dumped_text = dump_certificate(FILETYPE_TEXT, cert)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002695 good_text = _runopenssl(
2696 dumped_pem, b"x509", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002697 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002698
Alex Gaynor37726112016-07-04 09:51:32 -04002699 def test_dump_certificate_bad_type(self):
2700 """
Alex Chanb00ede22017-01-30 07:24:40 +00002701 `dump_certificate` raises a `ValueError` if it's called with
Alex Gaynor37726112016-07-04 09:51:32 -04002702 a bad type.
2703 """
2704 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
2705 with pytest.raises(ValueError):
2706 dump_certificate(object(), cert)
2707
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002708 def test_dump_privatekey_pem(self):
Rick Dean5b7b6372009-04-01 11:34:06 -05002709 """
Alex Chanb00ede22017-01-30 07:24:40 +00002710 `dump_privatekey` writes a PEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002711 """
2712 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Chanb00ede22017-01-30 07:24:40 +00002713 assert key.check()
Rick Dean5b7b6372009-04-01 11:34:06 -05002714 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
Alex Chanb00ede22017-01-30 07:24:40 +00002715 assert dumped_pem == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002716
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002717 def test_dump_privatekey_asn1(self):
2718 """
Alex Chanb00ede22017-01-30 07:24:40 +00002719 `dump_privatekey` writes a DER
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002720 """
2721 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2722 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2723
Rick Dean5b7b6372009-04-01 11:34:06 -05002724 dumped_der = dump_privatekey(FILETYPE_ASN1, key)
Jean-Paul Calderonef17e4212009-04-01 14:21:40 -04002725 # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002726 good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002727 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002728 key2 = load_privatekey(FILETYPE_ASN1, dumped_der)
2729 dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2)
Alex Chanb00ede22017-01-30 07:24:40 +00002730 assert dumped_pem2 == cleartextPrivateKeyPEM
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002731
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002732 def test_dump_privatekey_text(self):
2733 """
Alex Chanb00ede22017-01-30 07:24:40 +00002734 `dump_privatekey` writes a text
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002735 """
2736 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
2737 dumped_pem = dump_privatekey(FILETYPE_PEM, key)
2738
Rick Dean5b7b6372009-04-01 11:34:06 -05002739 dumped_text = dump_privatekey(FILETYPE_TEXT, key)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002740 good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text")
Alex Chanb00ede22017-01-30 07:24:40 +00002741 assert dumped_text == good_text
Rick Dean5b7b6372009-04-01 11:34:06 -05002742
Cory Benfield6492f7c2015-10-27 16:57:58 +09002743 def test_dump_publickey_pem(self):
2744 """
Cory Benfield11c10192015-10-27 17:23:03 +09002745 dump_publickey writes a PEM.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002746 """
2747 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2748 dumped_pem = dump_publickey(FILETYPE_PEM, key)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002749 assert dumped_pem == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002750
2751 def test_dump_publickey_asn1(self):
2752 """
Cory Benfield11c10192015-10-27 17:23:03 +09002753 dump_publickey writes a DER.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002754 """
2755 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2756 dumped_der = dump_publickey(FILETYPE_ASN1, key)
2757 key2 = load_publickey(FILETYPE_ASN1, dumped_der)
2758 dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
Cory Benfieldd86f1d82015-10-27 17:25:17 +09002759 assert dumped_pem2 == cleartextPublicKeyPEM
Cory Benfield6492f7c2015-10-27 16:57:58 +09002760
Cory Benfielde02c7d82015-10-27 17:34:49 +09002761 def test_dump_publickey_invalid_type(self):
2762 """
2763 dump_publickey doesn't support FILETYPE_TEXT.
2764 """
2765 key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
2766
2767 with pytest.raises(ValueError):
2768 dump_publickey(FILETYPE_TEXT, key)
2769
Rick Dean5b7b6372009-04-01 11:34:06 -05002770 def test_dump_certificate_request(self):
2771 """
Alex Chanb00ede22017-01-30 07:24:40 +00002772 `dump_certificate_request` writes a PEM, DER, and text.
Rick Dean5b7b6372009-04-01 11:34:06 -05002773 """
Alex Gaynor31287502015-09-05 16:11:27 -04002774 req = load_certificate_request(
2775 FILETYPE_PEM, cleartextCertificateRequestPEM)
Rick Dean5b7b6372009-04-01 11:34:06 -05002776 dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
Alex Chanb00ede22017-01-30 07:24:40 +00002777 assert dumped_pem == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002778 dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002779 good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
Alex Chanb00ede22017-01-30 07:24:40 +00002780 assert dumped_der == good_der
Rick Dean5b7b6372009-04-01 11:34:06 -05002781 req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
2782 dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
Alex Chanb00ede22017-01-30 07:24:40 +00002783 assert dumped_pem2 == cleartextCertificateRequestPEM
Rick Dean5b7b6372009-04-01 11:34:06 -05002784 dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
Alex Gaynor316aa2c2016-09-10 14:42:53 -04002785 good_text = _runopenssl(
2786 dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
Alex Chanb00ede22017-01-30 07:24:40 +00002787 assert dumped_text == good_text
2788 with pytest.raises(ValueError):
2789 dump_certificate_request(100, req)
Rick Dean5b7b6372009-04-01 11:34:06 -05002790
Alex Chanb00ede22017-01-30 07:24:40 +00002791 def test_dump_privatekey_passphrase_callback(self):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002792 """
Alex Chanb00ede22017-01-30 07:24:40 +00002793 `dump_privatekey` writes an encrypted PEM when given a callback
Alex Gaynor791212d2015-09-05 15:46:08 -04002794 which returns the correct passphrase.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002795 """
Alex Gaynore7f51982016-09-11 11:48:14 -04002796 passphrase = b"foo"
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002797 called = []
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002798
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002799 def cb(writing):
2800 called.append(writing)
2801 return passphrase
2802 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002803 pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Alex Chanb00ede22017-01-30 07:24:40 +00002804 assert isinstance(pem, binary_type)
2805 assert called == [True]
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -04002806 loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
Alex Chanb00ede22017-01-30 07:24:40 +00002807 assert isinstance(loadedKey, PKeyType)
2808 assert loadedKey.type() == key.type()
2809 assert loadedKey.bits() == key.bits()
Rick Dean5b7b6372009-04-01 11:34:06 -05002810
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002811 def test_dump_privatekey_passphrase_exception(self):
2812 """
Alex Chanb00ede22017-01-30 07:24:40 +00002813 `dump_privatekey` should not overwrite the exception raised
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002814 by the passphrase callback.
2815 """
2816 def cb(ignored):
2817 raise ArithmeticError
2818
2819 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002820 with pytest.raises(ArithmeticError):
2821 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht6b90a402009-12-22 14:33:47 +01002822
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002823 def test_dump_privatekey_passphraseCallbackLength(self):
2824 """
Alex Chanb00ede22017-01-30 07:24:40 +00002825 `crypto.dump_privatekey` should raise an error when the passphrase
2826 provided by the callback is too long, not silently truncate it.
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002827 """
2828 def cb(ignored):
2829 return "a" * 1025
2830
2831 key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
Alex Gaynor85b49702015-09-05 16:30:59 -04002832 with pytest.raises(ValueError):
2833 dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
Ziga Seilnacht781295a2009-12-22 14:58:01 +01002834
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002835 def test_load_pkcs7_data_pem(self):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002836 """
Alex Chanb00ede22017-01-30 07:24:40 +00002837 `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
2838 `PKCS`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002839 """
2840 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002841 assert isinstance(pkcs7, PKCS7)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002842
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002843 def test_load_pkcs7_data_asn1(self):
Alex Gaynor9875a912014-08-14 13:35:05 -07002844 """
Alex Chanb00ede22017-01-30 07:24:40 +00002845 `load_pkcs7_data` accepts a bytes containing ASN1 data representing
2846 PKCS#7 and returns an instance of `PKCS7`.
Alex Gaynor9875a912014-08-14 13:35:05 -07002847 """
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002848 pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
Alex Chanb00ede22017-01-30 07:24:40 +00002849 assert isinstance(pkcs7, PKCS7)
Alex Gaynor4b9c96a2014-08-14 09:51:48 -07002850
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002851 def test_load_pkcs7_data_invalid(self):
2852 """
Alex Chanb00ede22017-01-30 07:24:40 +00002853 If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002854 """
Alex Chanb00ede22017-01-30 07:24:40 +00002855 with pytest.raises(Error):
2856 load_pkcs7_data(FILETYPE_PEM, b"foo")
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002857
Alex Gaynor09a386e2016-07-03 09:32:44 -04002858 def test_load_pkcs7_type_invalid(self):
2859 """
Alex Chanb00ede22017-01-30 07:24:40 +00002860 If the type passed to `load_pkcs7_data`, `ValueError` is raised.
Alex Gaynor09a386e2016-07-03 09:32:44 -04002861 """
2862 with pytest.raises(ValueError):
2863 load_pkcs7_data(object(), b"foo")
2864
Jean-Paul Calderonee82e3252013-03-03 10:14:10 -08002865
Alex Chan9e2a9932017-01-25 14:29:19 +00002866class TestLoadCertificate(object):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002867 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002868 Tests for `load_certificate_request`.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002869 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002870
Alex Chan9e2a9932017-01-25 14:29:19 +00002871 def test_bad_file_type(self):
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002872 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002873 If the file type passed to `load_certificate_request` is neither
2874 `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002875 """
Alex Gaynor7778e792016-07-03 23:38:48 -04002876 with pytest.raises(ValueError):
2877 load_certificate_request(object(), b"")
2878 with pytest.raises(ValueError):
2879 load_certificate(object(), b"")
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002880
Alex Gaynor37726112016-07-04 09:51:32 -04002881 def test_bad_certificate(self):
2882 """
Alex Chan9e2a9932017-01-25 14:29:19 +00002883 If the bytes passed to `load_certificate` are not a valid certificate,
2884 an exception is raised.
Alex Gaynor37726112016-07-04 09:51:32 -04002885 """
2886 with pytest.raises(Error):
2887 load_certificate(FILETYPE_ASN1, b"lol")
2888
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002889
Alex Chanb00ede22017-01-30 07:24:40 +00002890class TestPKCS7(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002891 """
Alex Chanb00ede22017-01-30 07:24:40 +00002892 Tests for `PKCS7`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002893 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002894
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002895 def test_type(self):
2896 """
Alex Chanb00ede22017-01-30 07:24:40 +00002897 `PKCS7` is a type object.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002898 """
Alex Chanb00ede22017-01-30 07:24:40 +00002899 assert isinstance(PKCS7, type)
2900 assert PKCS7Type.__name__ == 'PKCS7'
2901 assert PKCS7 is PKCS7Type
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002902
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002903 def test_type_is_signed(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002904 """
Alex Chanb00ede22017-01-30 07:24:40 +00002905 `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
2906 the type *signed*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002907 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002908 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002909 assert pkcs7.type_is_signed()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002910
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002911 def test_type_is_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002912 """
Alex Chanb00ede22017-01-30 07:24:40 +00002913 `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
2914 of the type *enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002915 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002916 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002917 assert not pkcs7.type_is_enveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002918
Alex Chanb00ede22017-01-30 07:24:40 +00002919 def test_type_is_signed_and_enveloped(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002920 """
Alex Chanb00ede22017-01-30 07:24:40 +00002921 `PKCS7.type_is_signedAndEnveloped` returns `False`
Alex Gaynor791212d2015-09-05 15:46:08 -04002922 if the PKCS7 object is not of the type *signed and enveloped*.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002923 """
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002924 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002925 assert not pkcs7.type_is_signedAndEnveloped()
Jean-Paul Calderone07c93742010-07-30 10:53:41 -04002926
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002927 def test_type_is_data(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002928 """
Alex Chanb00ede22017-01-30 07:24:40 +00002929 `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
2930 the type data.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002931 """
Jean-Paul Calderoneb4754b92010-07-30 11:00:08 -04002932 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002933 assert not pkcs7.type_is_data()
Jean-Paul Calderone97b28ca2010-07-30 10:56:07 -04002934
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002935 def test_get_type_name(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002936 """
Alex Chanb00ede22017-01-30 07:24:40 +00002937 `PKCS7.get_type_name` returns a `str` giving the
Alex Gaynor791212d2015-09-05 15:46:08 -04002938 type name.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002939 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002940 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002941 assert pkcs7.get_type_name() == b'pkcs7-signedData'
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002942
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002943 def test_attribute(self):
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002944 """
Alex Gaynor791212d2015-09-05 15:46:08 -04002945 If an attribute other than one of the methods tested here is accessed
Alex Chanb00ede22017-01-30 07:24:40 +00002946 on an instance of `PKCS7`, `AttributeError` is raised.
Jean-Paul Calderoneaa6c0692010-09-08 22:43:09 -04002947 """
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002948 pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
Alex Chanb00ede22017-01-30 07:24:40 +00002949 with pytest.raises(AttributeError):
2950 pkcs7.foo
Jean-Paul Calderone4cbe05e2010-07-30 10:55:30 -04002951
2952
Alex Chanb00ede22017-01-30 07:24:40 +00002953class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002954 """
Alex Chanb00ede22017-01-30 07:24:40 +00002955 Tests for `OpenSSL.crypto.NetscapeSPKI`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002956 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04002957
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002958 def signable(self):
2959 """
Alex Chanb00ede22017-01-30 07:24:40 +00002960 Return a new `NetscapeSPKI` for use with signing tests.
Jean-Paul Calderoneb9725592010-08-03 18:17:22 -04002961 """
2962 return NetscapeSPKI()
2963
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002964 def test_type(self):
2965 """
Alex Chanb00ede22017-01-30 07:24:40 +00002966 `NetscapeSPKI` and `NetscapeSPKIType` refer to the same type object
2967 and can be used to create instances of that type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002968 """
Alex Chanb00ede22017-01-30 07:24:40 +00002969 assert NetscapeSPKI is NetscapeSPKIType
2970 assert is_consistent_type(NetscapeSPKI, 'NetscapeSPKI')
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002971
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002972 def test_construction(self):
2973 """
Alex Chanb00ede22017-01-30 07:24:40 +00002974 `NetscapeSPKI` returns an instance of `NetscapeSPKIType`.
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002975 """
2976 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002977 assert isinstance(nspki, NetscapeSPKIType)
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04002978
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002979 def test_invalid_attribute(self):
2980 """
Alex Chanb00ede22017-01-30 07:24:40 +00002981 Accessing a non-existent attribute of a `NetscapeSPKI` instance
2982 causes an `AttributeError` to be raised.
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002983 """
2984 nspki = NetscapeSPKI()
Alex Chanb00ede22017-01-30 07:24:40 +00002985 with pytest.raises(AttributeError):
2986 nspki.foo
Jean-Paul Calderone969efaa2010-08-03 18:19:19 -04002987
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002988 def test_b64_encode(self):
2989 """
Alex Chanb00ede22017-01-30 07:24:40 +00002990 `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002991 """
2992 nspki = NetscapeSPKI()
2993 blob = nspki.b64_encode()
Alex Chanb00ede22017-01-30 07:24:40 +00002994 assert isinstance(blob, binary_type)
Jean-Paul Calderone06ada9f2010-08-03 18:26:52 -04002995
2996
Paul Kehrer2c605ba2016-03-11 11:17:26 -04002997class TestRevoked(object):
2998 """
Alex Chandeec9342016-12-19 22:00:38 +00002999 Tests for `OpenSSL.crypto.Revoked`.
Paul Kehrer2c605ba2016-03-11 11:17:26 -04003000 """
3001 def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
3002 """
3003 The get_reason method on the Revoked class checks to see if the
3004 extension is NID_crl_reason and should skip it otherwise. This test
3005 loads a CRL with extensions it should ignore.
3006 """
3007 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3008 revoked = crl.get_revoked()
3009 reason = revoked[1].get_reason()
3010 assert reason == b'Unspecified'
3011
3012 def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
3013 crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
3014 revoked = crl.get_revoked()
3015 revoked[1].set_reason(None)
3016 reason = revoked[1].get_reason()
3017 assert reason is None
3018
Rick Dean536ba022009-07-24 23:57:27 -05003019 def test_construction(self):
3020 """
Alex Chandeec9342016-12-19 22:00:38 +00003021 Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
3022 empty.
Rick Dean536ba022009-07-24 23:57:27 -05003023 """
3024 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003025 assert isinstance(revoked, Revoked)
3026 assert type(revoked) == Revoked
3027 assert revoked.get_serial() == b'00'
3028 assert revoked.get_rev_date() is None
3029 assert revoked.get_reason() is None
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003030
Rick Dean536ba022009-07-24 23:57:27 -05003031 def test_serial(self):
3032 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003033 Confirm we can set and get serial numbers from
Alex Chandeec9342016-12-19 22:00:38 +00003034 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003035 """
3036 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003037 ret = revoked.set_serial(b'10b')
Alex Chandeec9342016-12-19 22:00:38 +00003038 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003039 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003040 assert ser == b'010B'
Rick Dean536ba022009-07-24 23:57:27 -05003041
Alex Gaynore7f51982016-09-11 11:48:14 -04003042 revoked.set_serial(b'31ppp') # a type error would be nice
Rick Dean536ba022009-07-24 23:57:27 -05003043 ser = revoked.get_serial()
Alex Chandeec9342016-12-19 22:00:38 +00003044 assert ser == b'31'
Rick Dean536ba022009-07-24 23:57:27 -05003045
Alex Chandeec9342016-12-19 22:00:38 +00003046 with pytest.raises(ValueError):
3047 revoked.set_serial(b'pqrst')
3048 with pytest.raises(TypeError):
3049 revoked.set_serial(100)
Rick Dean536ba022009-07-24 23:57:27 -05003050
Rick Dean536ba022009-07-24 23:57:27 -05003051 def test_date(self):
3052 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003053 Confirm we can set and get revocation dates from
Alex Chandeec9342016-12-19 22:00:38 +00003054 `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
Rick Dean536ba022009-07-24 23:57:27 -05003055 """
3056 revoked = Revoked()
3057 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003058 assert date is None
Rick Dean536ba022009-07-24 23:57:27 -05003059
Alex Gaynore7f51982016-09-11 11:48:14 -04003060 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003061 ret = revoked.set_rev_date(now)
Alex Chandeec9342016-12-19 22:00:38 +00003062 assert ret is None
Rick Dean536ba022009-07-24 23:57:27 -05003063 date = revoked.get_rev_date()
Alex Chandeec9342016-12-19 22:00:38 +00003064 assert date == now
Rick Dean536ba022009-07-24 23:57:27 -05003065
Rick Dean6385faf2009-07-26 00:07:47 -05003066 def test_reason(self):
3067 """
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003068 Confirm we can set and get revocation reasons from
Alex Chandeec9342016-12-19 22:00:38 +00003069 `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
3070 Likewise, each reason of all_reasons() must work.
Rick Dean6385faf2009-07-26 00:07:47 -05003071 """
3072 revoked = Revoked()
3073 for r in revoked.all_reasons():
Jean-Paul Calderoneeacad4a2010-08-22 17:12:55 -04003074 for x in range(2):
Rick Dean6385faf2009-07-26 00:07:47 -05003075 ret = revoked.set_reason(r)
Alex Chandeec9342016-12-19 22:00:38 +00003076 assert ret is None
Rick Dean6385faf2009-07-26 00:07:47 -05003077 reason = revoked.get_reason()
Alex Chandeec9342016-12-19 22:00:38 +00003078 assert (
3079 reason.lower().replace(b' ', b'') ==
Alex Gaynore7f51982016-09-11 11:48:14 -04003080 r.lower().replace(b' ', b''))
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003081 r = reason # again with the resp of get
Rick Dean6385faf2009-07-26 00:07:47 -05003082
3083 revoked.set_reason(None)
Alex Chandeec9342016-12-19 22:00:38 +00003084 assert revoked.get_reason() is None
Rick Dean6385faf2009-07-26 00:07:47 -05003085
Alex Chanfb078d82017-04-20 11:16:15 +01003086 @pytest.mark.parametrize('reason', [object(), 1.0, u'foo'])
3087 def test_set_reason_wrong_args(self, reason):
3088 """
3089 `Revoked.set_reason` raises `TypeError` if called with an argument
3090 which is neither `None` nor a byte string.
3091 """
3092 revoked = Revoked()
3093 with pytest.raises(TypeError):
3094 revoked.set_reason(reason)
3095
Alex Chandeec9342016-12-19 22:00:38 +00003096 def test_set_reason_invalid_reason(self):
Rick Dean6385faf2009-07-26 00:07:47 -05003097 """
Alex Chandeec9342016-12-19 22:00:38 +00003098 Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
3099 isn't a valid reason results in `ValueError` being raised.
Rick Dean6385faf2009-07-26 00:07:47 -05003100 """
3101 revoked = Revoked()
Alex Chandeec9342016-12-19 22:00:38 +00003102 with pytest.raises(ValueError):
3103 revoked.set_reason(b'blue')
Jean-Paul Calderone4f74bfe2010-01-30 14:32:49 -05003104
3105
Alex Chan7be83a52017-01-24 15:19:29 +00003106class TestCRL(object):
Rick Dean536ba022009-07-24 23:57:27 -05003107 """
Alex Chan7be83a52017-01-24 15:19:29 +00003108 Tests for `OpenSSL.crypto.CRL`.
Rick Dean536ba022009-07-24 23:57:27 -05003109 """
3110 cert = load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
3111 pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
3112
Dan Sully44e767a2016-06-04 18:05:27 -07003113 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3114 root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3115 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
3116 intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
3117 intermediate_server_cert = load_certificate(
3118 FILETYPE_PEM, intermediate_server_cert_pem)
3119 intermediate_server_key = load_privatekey(
3120 FILETYPE_PEM, intermediate_server_key_pem)
3121
Rick Dean536ba022009-07-24 23:57:27 -05003122 def test_construction(self):
3123 """
Alex Chan7be83a52017-01-24 15:19:29 +00003124 Confirm we can create `OpenSSL.crypto.CRL`. Check
Rick Dean536ba022009-07-24 23:57:27 -05003125 that it is empty
3126 """
3127 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003128 assert isinstance(crl, CRL)
3129 assert crl.get_revoked() is None
Jean-Paul Calderone2efd03e2010-01-30 13:59:55 -05003130
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003131 def _get_crl(self):
Rick Dean536ba022009-07-24 23:57:27 -05003132 """
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003133 Get a new ``CRL`` with a revocation.
Rick Dean536ba022009-07-24 23:57:27 -05003134 """
3135 crl = CRL()
3136 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003137 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003138 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003139 revoked.set_serial(b'3ab')
3140 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003141 crl.add_revoked(revoked)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003142 return crl
Rick Dean536ba022009-07-24 23:57:27 -05003143
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003144 def test_export_pem(self):
3145 """
3146 If not passed a format, ``CRL.export`` returns a "PEM" format string
3147 representing a serial number, a revoked reason, and certificate issuer
3148 information.
3149 """
3150 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003151 # PEM format
3152 dumped_crl = crl.export(self.cert, self.pkey, days=20)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003153 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003154
3155 # These magic values are based on the way the CRL above was constructed
3156 # and with what certificate it was exported.
Alex Gaynore7f51982016-09-11 11:48:14 -04003157 text.index(b'Serial Number: 03AB')
3158 text.index(b'Superseded')
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003159 text.index(
Alex Gaynore7f51982016-09-11 11:48:14 -04003160 b'Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA'
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003161 )
3162
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003163 def test_export_der(self):
3164 """
3165 If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
3166 "DER" format string representing a serial number, a revoked reason, and
3167 certificate issuer information.
3168 """
3169 crl = self._get_crl()
Rick Dean536ba022009-07-24 23:57:27 -05003170
3171 # DER format
3172 dumped_crl = crl.export(self.cert, self.pkey, FILETYPE_ASN1)
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003173 text = _runopenssl(
3174 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
3175 )
Alex Gaynore7f51982016-09-11 11:48:14 -04003176 text.index(b'Serial Number: 03AB')
3177 text.index(b'Superseded')
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003178 text.index(
Alex Gaynore7f51982016-09-11 11:48:14 -04003179 b'Issuer: /C=US/ST=IL/L=Chicago/O=Testing/CN=Testing Root CA'
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003180 )
3181
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003182 def test_export_text(self):
3183 """
3184 If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
3185 text format string like the one produced by the openssl command line
3186 tool.
3187 """
3188 crl = self._get_crl()
3189
3190 dumped_crl = crl.export(self.cert, self.pkey, FILETYPE_ASN1)
3191 text = _runopenssl(
3192 dumped_crl, b"crl", b"-noout", b"-text", b"-inform", b"DER"
3193 )
Rick Dean536ba022009-07-24 23:57:27 -05003194
3195 # text format
3196 dumped_text = crl.export(self.cert, self.pkey, type=FILETYPE_TEXT)
Alex Chan7be83a52017-01-24 15:19:29 +00003197 assert text == dumped_text
Rick Dean536ba022009-07-24 23:57:27 -05003198
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003199 def test_export_custom_digest(self):
3200 """
3201 If passed the name of a digest function, ``CRL.export`` uses a
3202 signature algorithm based on that digest function.
3203 """
3204 crl = self._get_crl()
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003205 dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003206 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003207 text.index(b'Signature Algorithm: sha1')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003208
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003209 def test_export_md5_digest(self):
3210 """
3211 If passed md5 as the digest function, ``CRL.export`` uses md5 and does
3212 not emit a deprecation warning.
3213 """
3214 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003215 with pytest.warns(None) as catcher:
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003216 simplefilter("always")
Alex Chan7be83a52017-01-24 15:19:29 +00003217 assert 0 == len(catcher)
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003218 dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
3219 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003220 text.index(b'Signature Algorithm: md5')
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04003221
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003222 def test_export_default_digest(self):
3223 """
3224 If not passed the name of a digest function, ``CRL.export`` uses a
3225 signature algorithm based on MD5 and emits a deprecation warning.
3226 """
3227 crl = self._get_crl()
Alex Chan7be83a52017-01-24 15:19:29 +00003228 with pytest.warns(None) as catcher:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04003229 simplefilter("always")
3230 dumped_crl = crl.export(self.cert, self.pkey)
Alex Chan7be83a52017-01-24 15:19:29 +00003231 assert (
3232 "The default message digest (md5) is deprecated. "
3233 "Pass the name of a message digest explicitly." ==
3234 str(catcher[0].message)
3235 )
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003236 text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
Alex Gaynore7f51982016-09-11 11:48:14 -04003237 text.index(b'Signature Algorithm: md5')
Bulat Gaifullin1966c972014-09-22 09:47:20 +04003238
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003239 def test_export_invalid(self):
3240 """
Alex Chan7be83a52017-01-24 15:19:29 +00003241 If `CRL.export` is used with an uninitialized `X509` instance,
3242 `OpenSSL.crypto.Error` is raised.
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003243 """
3244 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003245 with pytest.raises(Error):
3246 crl.export(X509(), PKey())
Jean-Paul Calderonec7293bc2011-09-13 15:24:38 -04003247
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003248 def test_add_revoked_keyword(self):
3249 """
Alex Chan7be83a52017-01-24 15:19:29 +00003250 `OpenSSL.CRL.add_revoked` accepts its single argument as the
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04003251 ``revoked`` keyword argument.
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003252 """
3253 crl = CRL()
3254 revoked = Revoked()
Paul Kehrerb11bffc2016-03-10 18:30:29 -04003255 revoked.set_serial(b"01")
Paul Kehrer2fe23b02016-03-09 22:02:15 -04003256 revoked.set_rev_date(b"20160310020145Z")
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003257 crl.add_revoked(revoked=revoked)
Alex Chan7be83a52017-01-24 15:19:29 +00003258 assert isinstance(crl.get_revoked()[0], Revoked)
Jean-Paul Calderone56515342010-01-30 13:49:38 -05003259
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003260 def test_export_wrong_args(self):
3261 """
Alex Chan7be83a52017-01-24 15:19:29 +00003262 Calling `OpenSSL.CRL.export` with arguments other than the certificate,
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003263 private key, integer file type, and integer number of days it
Alex Chan7be83a52017-01-24 15:19:29 +00003264 expects, results in a `TypeError` being raised.
Jean-Paul Calderone883ca4b2010-01-30 13:55:13 -05003265 """
3266 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003267 with pytest.raises(TypeError):
3268 crl.export(None, self.pkey, FILETYPE_PEM, 10)
3269 with pytest.raises(TypeError):
3270 crl.export(self.cert, None, FILETYPE_PEM, 10)
3271 with pytest.raises(TypeError):
3272 crl.export(self.cert, self.pkey, None, 10)
Alex Chan7be83a52017-01-24 15:19:29 +00003273 with pytest.raises(TypeError):
3274 crl.export(self.cert, FILETYPE_PEM, None)
Jean-Paul Calderonef1515862010-01-30 13:57:03 -05003275
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003276 def test_export_unknown_filetype(self):
3277 """
Alex Chan7be83a52017-01-24 15:19:29 +00003278 Calling `OpenSSL.CRL.export` with a file type other than
3279 `FILETYPE_PEM`, `FILETYPE_ASN1`, or
3280 `FILETYPE_TEXT` results in a `ValueError` being raised.
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003281 """
3282 crl = CRL()
Alex Gaynor85b49702015-09-05 16:30:59 -04003283 with pytest.raises(ValueError):
3284 crl.export(self.cert, self.pkey, 100, 10)
Jean-Paul Calderoneea198422010-01-30 13:58:23 -05003285
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003286 def test_export_unknown_digest(self):
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003287 """
Alex Chan7be83a52017-01-24 15:19:29 +00003288 Calling `OpenSSL.CRL.export` with an unsupported digest results
3289 in a `ValueError` being raised.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04003290 """
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003291 crl = CRL()
Alex Chan7be83a52017-01-24 15:19:29 +00003292 with pytest.raises(ValueError):
3293 crl.export(
3294 self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest")
Bulat Gaifullin925f7862014-09-22 10:10:44 +04003295
Rick Dean536ba022009-07-24 23:57:27 -05003296 def test_get_revoked(self):
3297 """
Alex Chan7be83a52017-01-24 15:19:29 +00003298 Use python to create a simple CRL with two revocations. Get back the
3299 `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
Rick Dean536ba022009-07-24 23:57:27 -05003300 """
3301 crl = CRL()
3302
3303 revoked = Revoked()
Alex Gaynore7f51982016-09-11 11:48:14 -04003304 now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
Rick Dean536ba022009-07-24 23:57:27 -05003305 revoked.set_rev_date(now)
Alex Gaynore7f51982016-09-11 11:48:14 -04003306 revoked.set_serial(b'3ab')
Rick Dean536ba022009-07-24 23:57:27 -05003307 crl.add_revoked(revoked)
Alex Gaynore7f51982016-09-11 11:48:14 -04003308 revoked.set_serial(b'100')
3309 revoked.set_reason(b'sUpErSeDEd')
Rick Dean536ba022009-07-24 23:57:27 -05003310 crl.add_revoked(revoked)
3311
3312 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003313 assert len(revs) == 2
3314 assert type(revs[0]) == Revoked
3315 assert type(revs[1]) == Revoked
3316 assert revs[0].get_serial() == b'03AB'
3317 assert revs[1].get_serial() == b'0100'
3318 assert revs[0].get_rev_date() == now
3319 assert revs[1].get_rev_date() == now
Jean-Paul Calderoneecef6fa2010-01-30 13:47:18 -05003320
Rick Dean536ba022009-07-24 23:57:27 -05003321 def test_load_crl(self):
3322 """
Alex Chan7be83a52017-01-24 15:19:29 +00003323 Load a known CRL and inspect its revocations. Both EM and DER formats
3324 are loaded.
Rick Dean536ba022009-07-24 23:57:27 -05003325 """
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003326 crl = load_crl(FILETYPE_PEM, crlData)
Rick Dean536ba022009-07-24 23:57:27 -05003327 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003328 assert len(revs) == 2
3329 assert revs[0].get_serial() == b'03AB'
3330 assert revs[0].get_reason() is None
3331 assert revs[1].get_serial() == b'0100'
3332 assert revs[1].get_reason() == b'Superseded'
Rick Dean536ba022009-07-24 23:57:27 -05003333
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003334 der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
Jean-Paul Calderoneb98eae02010-01-30 13:18:04 -05003335 crl = load_crl(FILETYPE_ASN1, der)
Rick Dean536ba022009-07-24 23:57:27 -05003336 revs = crl.get_revoked()
Alex Chan7be83a52017-01-24 15:19:29 +00003337 assert len(revs) == 2
3338 assert revs[0].get_serial() == b'03AB'
3339 assert revs[0].get_reason() is None
3340 assert revs[1].get_serial() == b'0100'
3341 assert revs[1].get_reason() == b'Superseded'
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003342
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003343 def test_load_crl_bad_filetype(self):
3344 """
Alex Chan7be83a52017-01-24 15:19:29 +00003345 Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
3346 `ValueError`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003347 """
Alex Chan7be83a52017-01-24 15:19:29 +00003348 with pytest.raises(ValueError):
3349 load_crl(100, crlData)
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003350
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003351 def test_load_crl_bad_data(self):
3352 """
Alex Chan7be83a52017-01-24 15:19:29 +00003353 Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
3354 raises a `OpenSSL.crypto.Error`.
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003355 """
Alex Chan7be83a52017-01-24 15:19:29 +00003356 with pytest.raises(Error):
3357 load_crl(FILETYPE_PEM, b"hello, world")
Jean-Paul Calderone3eb5cc72010-01-30 15:24:40 -05003358
Dan Sully44e767a2016-06-04 18:05:27 -07003359 def test_get_issuer(self):
3360 """
Alex Chan7be83a52017-01-24 15:19:29 +00003361 Load a known CRL and assert its issuer's common name is what we expect
3362 from the encoded crlData string.
Dan Sully44e767a2016-06-04 18:05:27 -07003363 """
3364 crl = load_crl(FILETYPE_PEM, crlData)
Alex Chan7be83a52017-01-24 15:19:29 +00003365 assert isinstance(crl.get_issuer(), X509Name)
3366 assert crl.get_issuer().CN == 'Testing Root CA'
Dan Sully44e767a2016-06-04 18:05:27 -07003367
Dominic Chenf05b2122015-10-13 16:32:35 +00003368 def test_dump_crl(self):
3369 """
3370 The dumped CRL matches the original input.
3371 """
3372 crl = load_crl(FILETYPE_PEM, crlData)
3373 buf = dump_crl(FILETYPE_PEM, crl)
3374 assert buf == crlData
3375
Dan Sully44e767a2016-06-04 18:05:27 -07003376 def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
3377 """
3378 Create a CRL.
3379
3380 :param list[X509] certs: A list of certificates to revoke.
3381 :rtype: CRL
3382 """
3383 crl = CRL()
3384 for cert in certs:
3385 revoked = Revoked()
3386 # FIXME: This string splicing is an unfortunate implementation
3387 # detail that has been reported in
3388 # https://github.com/pyca/pyopenssl/issues/258
3389 serial = hex(cert.get_serial_number())[2:].encode('utf-8')
3390 revoked.set_serial(serial)
3391 revoked.set_reason(b'unspecified')
3392 revoked.set_rev_date(b'20140601000000Z')
3393 crl.add_revoked(revoked)
3394 crl.set_version(1)
3395 crl.set_lastUpdate(b'20140601000000Z')
3396 crl.set_nextUpdate(b'20180601000000Z')
3397 crl.sign(issuer_cert, issuer_key, digest=b'sha512')
3398 return crl
3399
3400 def test_verify_with_revoked(self):
3401 """
Alex Chan7be83a52017-01-24 15:19:29 +00003402 `verify_certificate` raises error when an intermediate certificate is
3403 revoked.
Dan Sully44e767a2016-06-04 18:05:27 -07003404 """
3405 store = X509Store()
3406 store.add_cert(self.root_cert)
3407 store.add_cert(self.intermediate_cert)
3408 root_crl = self._make_test_crl(
3409 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3410 intermediate_crl = self._make_test_crl(
3411 self.intermediate_cert, self.intermediate_key, certs=[])
3412 store.add_crl(root_crl)
3413 store.add_crl(intermediate_crl)
3414 store.set_flags(
3415 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3416 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003417 with pytest.raises(X509StoreContextError) as err:
3418 store_ctx.verify_certificate()
3419 assert err.value.args[0][2] == 'certificate revoked'
Dan Sully44e767a2016-06-04 18:05:27 -07003420
3421 def test_verify_with_missing_crl(self):
3422 """
Alex Chan7be83a52017-01-24 15:19:29 +00003423 `verify_certificate` raises error when an intermediate certificate's
3424 CRL is missing.
Dan Sully44e767a2016-06-04 18:05:27 -07003425 """
3426 store = X509Store()
3427 store.add_cert(self.root_cert)
3428 store.add_cert(self.intermediate_cert)
3429 root_crl = self._make_test_crl(
3430 self.root_cert, self.root_key, certs=[self.intermediate_cert])
3431 store.add_crl(root_crl)
3432 store.set_flags(
3433 X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
3434 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003435 with pytest.raises(X509StoreContextError) as err:
3436 store_ctx.verify_certificate()
3437 assert err.value.args[0][2] == 'unable to get certificate CRL'
3438 assert err.value.certificate.get_subject().CN == 'intermediate-service'
Dan Sully44e767a2016-06-04 18:05:27 -07003439
Jean-Paul Calderonedc138fa2009-06-27 14:32:07 -04003440
Alex Chan7be83a52017-01-24 15:19:29 +00003441class TestX509StoreContext(object):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003442 """
Alex Chan7be83a52017-01-24 15:19:29 +00003443 Tests for `OpenSSL.crypto.X509StoreContext`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003444 """
3445 root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3446 intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
Alex Gaynor31287502015-09-05 16:11:27 -04003447 intermediate_server_cert = load_certificate(
3448 FILETYPE_PEM, intermediate_server_cert_pem)
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003449
3450 def test_valid(self):
3451 """
Alex Chan7be83a52017-01-24 15:19:29 +00003452 `verify_certificate` returns ``None`` when called with a certificate
3453 and valid chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003454 """
3455 store = X509Store()
3456 store.add_cert(self.root_cert)
3457 store.add_cert(self.intermediate_cert)
3458 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003459 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003460
3461 def test_reuse(self):
3462 """
Alex Chan7be83a52017-01-24 15:19:29 +00003463 `verify_certificate` can be called multiple times with the same
Jean-Paul Calderone06e01b92015-01-18 15:43:13 -05003464 ``X509StoreContext`` instance to produce the same result.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003465 """
3466 store = X509Store()
3467 store.add_cert(self.root_cert)
3468 store.add_cert(self.intermediate_cert)
3469 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003470 assert store_ctx.verify_certificate() is None
3471 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003472
3473 def test_trusted_self_signed(self):
3474 """
Alex Chan7be83a52017-01-24 15:19:29 +00003475 `verify_certificate` returns ``None`` when called with a self-signed
3476 certificate and itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003477 """
3478 store = X509Store()
3479 store.add_cert(self.root_cert)
3480 store_ctx = X509StoreContext(store, self.root_cert)
Alex Chan7be83a52017-01-24 15:19:29 +00003481 assert store_ctx.verify_certificate() is None
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003482
3483 def test_untrusted_self_signed(self):
3484 """
Alex Chan7be83a52017-01-24 15:19:29 +00003485 `verify_certificate` raises error when a self-signed certificate is
3486 verified without itself in the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003487 """
3488 store = X509Store()
3489 store_ctx = X509StoreContext(store, self.root_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003490 with pytest.raises(X509StoreContextError) as exc:
3491 store_ctx.verify_certificate()
3492
3493 assert exc.value.args[0][2] == 'self signed certificate'
3494 assert exc.value.certificate.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003495
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003496 def test_invalid_chain_no_root(self):
3497 """
Alex Chan7be83a52017-01-24 15:19:29 +00003498 `verify_certificate` raises error when a root certificate is missing
3499 from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003500 """
3501 store = X509Store()
3502 store.add_cert(self.intermediate_cert)
3503 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003504
3505 with pytest.raises(X509StoreContextError) as exc:
3506 store_ctx.verify_certificate()
3507
3508 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3509 assert exc.value.certificate.get_subject().CN == 'intermediate'
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003510
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003511 def test_invalid_chain_no_intermediate(self):
3512 """
Alex Chan7be83a52017-01-24 15:19:29 +00003513 `verify_certificate` raises error when an intermediate certificate is
3514 missing from the chain.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003515 """
3516 store = X509Store()
3517 store.add_cert(self.root_cert)
3518 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
Jean-Paul Calderone517816e2015-01-18 15:39:26 -05003519
Alex Gaynor85b49702015-09-05 16:30:59 -04003520 with pytest.raises(X509StoreContextError) as exc:
3521 store_ctx.verify_certificate()
3522
3523 assert exc.value.args[0][2] == 'unable to get local issuer certificate'
3524 assert exc.value.certificate.get_subject().CN == 'intermediate-service'
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07003525
Stephen Holsapple46a09252015-02-12 14:45:43 -08003526 def test_modification_pre_verify(self):
3527 """
Alex Chan7be83a52017-01-24 15:19:29 +00003528 `verify_certificate` can use a store context modified after
Stephen Holsapple46a09252015-02-12 14:45:43 -08003529 instantiation.
3530 """
3531 store_bad = X509Store()
3532 store_bad.add_cert(self.intermediate_cert)
3533 store_good = X509Store()
3534 store_good.add_cert(self.root_cert)
3535 store_good.add_cert(self.intermediate_cert)
3536 store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
Alex Gaynor85b49702015-09-05 16:30:59 -04003537
3538 with pytest.raises(X509StoreContextError) as exc:
3539 store_ctx.verify_certificate()
3540
3541 assert exc.value.args[0][2] == 'unable to get issuer certificate'
3542 assert exc.value.certificate.get_subject().CN == 'intermediate'
3543
Stephen Holsapple46a09252015-02-12 14:45:43 -08003544 store_ctx.set_store(store_good)
Alex Chan7be83a52017-01-24 15:19:29 +00003545 assert store_ctx.verify_certificate() is None
Stephen Holsapple46a09252015-02-12 14:45:43 -08003546
Thomas Sileoe15e60a2016-11-22 18:13:30 +01003547 def test_verify_with_time(self):
3548 """
3549 `verify_certificate` raises error when the verification time is
3550 set at notAfter.
3551 """
3552 store = X509Store()
3553 store.add_cert(self.root_cert)
3554 store.add_cert(self.intermediate_cert)
3555
3556 expire_time = self.intermediate_server_cert.get_notAfter()
3557 expire_datetime = datetime.strptime(
3558 expire_time.decode('utf-8'), '%Y%m%d%H%M%SZ'
3559 )
3560 store.set_time(expire_datetime)
3561
3562 store_ctx = X509StoreContext(store, self.intermediate_server_cert)
3563 with pytest.raises(X509StoreContextError) as exc:
3564 store_ctx.verify_certificate()
3565
3566 assert exc.value.args[0][2] == 'certificate has expired'
3567
Stephen Holsapple46a09252015-02-12 14:45:43 -08003568
Alex Chan7be83a52017-01-24 15:19:29 +00003569class TestSignVerify(object):
James Yonan7c2e5d32010-02-27 05:45:50 -07003570 """
Alex Chan7be83a52017-01-24 15:19:29 +00003571 Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
James Yonan7c2e5d32010-02-27 05:45:50 -07003572 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003573
James Yonan7c2e5d32010-02-27 05:45:50 -07003574 def test_sign_verify(self):
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003575 """
Alex Chan7be83a52017-01-24 15:19:29 +00003576 `sign` generates a cryptographic signature which `verify` can check.
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003577 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003578 content = (
3579 b"It was a bright cold day in April, and the clocks were striking "
3580 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3581 b"effort to escape the vile wind, slipped quickly through the "
3582 b"glass doors of Victory Mansions, though not quickly enough to "
3583 b"prevent a swirl of gritty dust from entering along with him.")
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003584
3585 # sign the content with this private key
Jean-Paul Calderonef3cb9d82010-06-22 10:29:33 -04003586 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
Jean-Paul Calderoneb98ce212010-06-22 09:46:27 -04003587 # verify the content with this cert
3588 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3589 # certificate unrelated to priv_key, used to trigger an error
3590 bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
James Yonan7c2e5d32010-02-27 05:45:50 -07003591
Jean-Paul Calderoned08feb02010-10-12 21:53:24 -04003592 for digest in ['md5', 'sha1']:
James Yonan7c2e5d32010-02-27 05:45:50 -07003593 sig = sign(priv_key, content, digest)
3594
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003595 # Verify the signature of content, will throw an exception if
3596 # error.
James Yonan7c2e5d32010-02-27 05:45:50 -07003597 verify(good_cert, sig, content, digest)
3598
3599 # This should fail because the certificate doesn't match the
3600 # private key that was used to sign the content.
Alex Chan7be83a52017-01-24 15:19:29 +00003601 with pytest.raises(Error):
3602 verify(bad_cert, sig, content, digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003603
3604 # This should fail because we've "tainted" the content after
3605 # signing it.
Alex Chan7be83a52017-01-24 15:19:29 +00003606 with pytest.raises(Error):
3607 verify(good_cert, sig, content + b"tainted", digest)
James Yonan7c2e5d32010-02-27 05:45:50 -07003608
3609 # test that unknown digest types fail
Alex Chan7be83a52017-01-24 15:19:29 +00003610 with pytest.raises(ValueError):
3611 sign(priv_key, content, "strange-digest")
3612 with pytest.raises(ValueError):
3613 verify(good_cert, sig, content, "strange-digest")
James Yonan7c2e5d32010-02-27 05:45:50 -07003614
Abraham Martinc5484ba2015-03-25 15:33:05 +00003615 def test_sign_verify_with_text(self):
3616 """
Alex Chan7be83a52017-01-24 15:19:29 +00003617 `sign` generates a cryptographic signature which
3618 `verify` can check. Deprecation warnings raised because using
Alex Gaynor791212d2015-09-05 15:46:08 -04003619 text instead of bytes as content
Abraham Martinc5484ba2015-03-25 15:33:05 +00003620 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003621 content = (
Jean-Paul Calderone362c1f52015-03-29 08:01:39 -04003622 b"It was a bright cold day in April, and the clocks were striking "
3623 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3624 b"effort to escape the vile wind, slipped quickly through the "
3625 b"glass doors of Victory Mansions, though not quickly enough to "
3626 b"prevent a swirl of gritty dust from entering along with him."
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003627 ).decode("ascii")
Abraham Martinc5484ba2015-03-25 15:33:05 +00003628
3629 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3630 cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3631 for digest in ['md5', 'sha1']:
Alex Chan7be83a52017-01-24 15:19:29 +00003632 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003633 simplefilter("always")
3634 sig = sign(priv_key, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003635 assert (
3636 "{0} for data is no longer accepted, use bytes".format(
3637 WARNING_TYPE_EXPECTED
3638 ) == str(w[-1].message))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003639
Alex Chan7be83a52017-01-24 15:19:29 +00003640 with pytest.warns(DeprecationWarning) as w:
Abraham Martinc5484ba2015-03-25 15:33:05 +00003641 simplefilter("always")
3642 verify(cert, sig, content, digest)
Alex Chan7be83a52017-01-24 15:19:29 +00003643 assert (
3644 "{0} for data is no longer accepted, use bytes".format(
3645 WARNING_TYPE_EXPECTED
3646 ) == str(w[-1].message))
Abraham Martinc5484ba2015-03-25 15:33:05 +00003647
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003648 def test_sign_nulls(self):
3649 """
Alex Chan7be83a52017-01-24 15:19:29 +00003650 `sign` produces a signature for a string with embedded nulls.
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003651 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003652 content = b"Watch out! \0 Did you see it?"
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003653 priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
3654 good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
3655 sig = sign(priv_key, content, "sha1")
3656 verify(good_cert, sig, content, "sha1")
3657
Colleen Murphye09399b2016-03-01 17:40:49 -08003658 def test_sign_with_large_key(self):
3659 """
Alex Chan7be83a52017-01-24 15:19:29 +00003660 `sign` produces a signature for a string when using a long key.
Colleen Murphye09399b2016-03-01 17:40:49 -08003661 """
Alex Gaynore7f51982016-09-11 11:48:14 -04003662 content = (
3663 b"It was a bright cold day in April, and the clocks were striking "
3664 b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
3665 b"effort to escape the vile wind, slipped quickly through the "
3666 b"glass doors of Victory Mansions, though not quickly enough to "
3667 b"prevent a swirl of gritty dust from entering along with him.")
Colleen Murphye09399b2016-03-01 17:40:49 -08003668
3669 priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
3670 sign(priv_key, content, "sha1")
3671
Jean-Paul Calderone9828f662010-12-08 22:57:26 -05003672
Alex Chan63ef9bc2016-12-19 12:02:06 +00003673class TestEllipticCurve(object):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003674 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003675 Tests for `_EllipticCurve`, `get_elliptic_curve`, and
3676 `get_elliptic_curves`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003677 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003678
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003679 def test_set(self):
3680 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003681 `get_elliptic_curves` returns a `set`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003682 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003683 assert isinstance(get_elliptic_curves(), set)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003684
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003685 def test_a_curve(self):
3686 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003687 `get_elliptic_curve` can be used to retrieve a particular supported
3688 curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003689 """
3690 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003691 curve = next(iter(curves))
3692 assert curve.name == get_elliptic_curve(curve.name).name
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003693
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003694 def test_not_a_curve(self):
3695 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003696 `get_elliptic_curve` raises `ValueError` if called with a name which
3697 does not identify a supported curve.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003698 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003699 with pytest.raises(ValueError):
3700 get_elliptic_curve(u"this curve was just invented")
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003701
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003702 def test_repr(self):
3703 """
3704 The string representation of a curve object includes simply states the
3705 object is a curve and what its name is.
3706 """
3707 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003708 curve = next(iter(curves))
3709 assert "<Curve %r>" % (curve.name,) == repr(curve)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003710
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003711 def test_to_EC_KEY(self):
3712 """
3713 The curve object can export a version of itself as an EC_KEY* via the
Alex Chan63ef9bc2016-12-19 12:02:06 +00003714 private `_EllipticCurve._to_EC_KEY`.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003715 """
3716 curves = get_elliptic_curves()
Alex Chan63ef9bc2016-12-19 12:02:06 +00003717 curve = next(iter(curves))
3718 # It's not easy to assert anything about this object. However, see
3719 # leakcheck/crypto.py for a test that demonstrates it at least does
3720 # not leak memory.
3721 curve._to_EC_KEY()
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04003722
3723
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003724class EllipticCurveFactory(object):
3725 """
3726 A helper to get the names of two curves.
3727 """
Alex Gaynoraceb3e22015-09-05 12:00:22 -04003728
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003729 def __init__(self):
3730 curves = iter(get_elliptic_curves())
Alex Chan63ef9bc2016-12-19 12:02:06 +00003731 self.curve_name = next(curves).name
3732 self.another_curve_name = next(curves).name
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003733
3734
Alex Chan63ef9bc2016-12-19 12:02:06 +00003735class TestEllipticCurveEquality(EqualityTestsMixin):
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003736 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003737 Tests `_EllipticCurve`\ 's implementation of ``==`` and ``!=``.
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003738 """
3739 curve_factory = EllipticCurveFactory()
3740
3741 if curve_factory.curve_name is None:
3742 skip = "There are no curves available there can be no curve objects."
3743
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003744 def anInstance(self):
3745 """
3746 Get the curve object for an arbitrary curve supported by the system.
3747 """
3748 return get_elliptic_curve(self.curve_factory.curve_name)
3749
Jean-Paul Calderone1be77082014-04-30 18:17:41 -04003750 def anotherInstance(self):
3751 """
3752 Get the curve object for an arbitrary curve supported by the system -
3753 but not the one returned by C{anInstance}.
3754 """
3755 return get_elliptic_curve(self.curve_factory.another_curve_name)
3756
3757
Alex Chan63ef9bc2016-12-19 12:02:06 +00003758class TestEllipticCurveHash(object):
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003759 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003760 Tests for `_EllipticCurve`'s implementation of hashing (thus use as
3761 an item in a `dict` or `set`).
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003762 """
3763 curve_factory = EllipticCurveFactory()
3764
3765 if curve_factory.curve_name is None:
3766 skip = "There are no curves available there can be no curve objects."
3767
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003768 def test_contains(self):
3769 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003770 The ``in`` operator reports that a `set` containing a curve does
3771 contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003772 """
3773 curve = get_elliptic_curve(self.curve_factory.curve_name)
3774 curves = set([curve])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003775 assert curve in curves
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003776
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003777 def test_does_not_contain(self):
3778 """
Alex Chan63ef9bc2016-12-19 12:02:06 +00003779 The ``in`` operator reports that a `set` not containing a curve
3780 does not contain that curve.
Jean-Paul Calderone22c31242014-05-01 07:49:47 -04003781 """
3782 curve = get_elliptic_curve(self.curve_factory.curve_name)
Alex Gaynor85b49702015-09-05 16:30:59 -04003783 curves = set([
3784 get_elliptic_curve(self.curve_factory.another_curve_name)
3785 ])
Alex Chan63ef9bc2016-12-19 12:02:06 +00003786 assert curve not in curves