-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
_sslverify.py
1961 lines (1506 loc) · 67 KB
/
_sslverify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- test-case-name: twisted.test.test_sslverify -*-
# Copyright (c) 2005 Divmod, Inc.
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import division, absolute_import
import itertools
import warnings
from binascii import a2b_base64
from hashlib import md5
import OpenSSL
from OpenSSL import SSL, crypto
try:
from OpenSSL.SSL import SSL_CB_HANDSHAKE_DONE, SSL_CB_HANDSHAKE_START
except ImportError:
SSL_CB_HANDSHAKE_START = 0x10
SSL_CB_HANDSHAKE_DONE = 0x20
from twisted.python import log
def _cantSetHostnameIndication(connection, hostname):
"""
The option to set SNI is not available, so do nothing.
@param connection: the connection
@type connection: L{OpenSSL.SSL.Connection}
@param hostname: the server's host name
@type: hostname: L{bytes}
"""
def _setHostNameIndication(connection, hostname):
"""
Set the server name indication on the given client connection to the given
value.
@param connection: the connection
@type connection: L{OpenSSL.SSL.Connection}
@param hostname: the server's host name
@type: hostname: L{bytes}
"""
connection.set_tlsext_host_name(hostname)
if getattr(SSL.Connection, "set_tlsext_host_name", None) is None:
_maybeSetHostNameIndication = _cantSetHostnameIndication
else:
_maybeSetHostNameIndication = _setHostNameIndication
class SimpleVerificationError(Exception):
"""
Not a very useful verification error.
"""
def _idnaBytes(text):
"""
Convert some text typed by a human into some ASCII bytes.
This is provided to allow us to use the U{partially-broken IDNA
implementation in the standard library <http://bugs.python.org/issue17305>}
if the more-correct U{idna <https://pypi.python.org/pypi/idna>} package is
not available; C{service_identity} is somewhat stricter about this.
@param text: A domain name, hopefully.
@type text: L{unicode}
@return: The domain name's IDNA representation, encoded as bytes.
@rtype: L{bytes}
"""
try:
import idna
except ImportError:
return text.encode("idna")
else:
return idna.encode(text)
def _idnaText(octets):
"""
Convert some IDNA-encoded octets into some human-readable text.
Currently only used by the tests.
@param octets: Some bytes representing a hostname.
@type octets: L{bytes}
@return: A human-readable domain name.
@rtype: L{unicode}
"""
try:
import idna
except ImportError:
return octets.decode("idna")
else:
return idna.decode(octets)
def simpleVerifyHostname(connection, hostname):
"""
Check only the common name in the certificate presented by the peer and
only for an exact match.
This is to provide I{something} in the way of hostname verification to
users who haven't upgraded past OpenSSL 0.12 or installed
C{service_identity}. This check is overly strict, relies on a deprecated
TLS feature (you're supposed to ignore the commonName if the
subjectAlternativeName extensions are present, I believe), and lots of
valid certificates will fail.
@param connection: the OpenSSL connection to verify.
@type connection: L{OpenSSL.SSL.Connection}
@param hostname: The hostname expected by the user.
@type hostname: L{unicode}
@raise twisted.internet.ssl.VerificationError: if the common name and
hostname don't match.
"""
commonName = connection.get_peer_certificate().get_subject().commonName
if commonName != hostname:
raise SimpleVerificationError(repr(commonName) + "!=" +
repr(hostname))
def _usablePyOpenSSL(version):
"""
Check pyOpenSSL version string whether we can use it for host verification.
@param version: A pyOpenSSL version string.
@type version: L{str}
@rtype: L{bool}
"""
major, minor = (int(part) for part in version.split(".")[:2])
return (major, minor) >= (0, 12)
def _selectVerifyImplementation(lib):
"""
U{service_identity <https://pypi.python.org/pypi/service_identity>}
requires pyOpenSSL 0.12 or better but our dependency is still back at 0.10.
Determine if pyOpenSSL has the requisite feature, and whether
C{service_identity} is installed. If so, use it. If not, use simplistic
and incorrect checking as implemented in L{simpleVerifyHostname}.
@param lib: The L{OpenSSL} module. This is necessary to determine whether
certain fallback implementation strategies will be necessary.
@type lib: L{types.ModuleType}
@return: 2-tuple of (C{verify_hostname}, C{VerificationError})
@rtype: L{tuple}
"""
whatsWrong = (
"Without the service_identity module and a recent enough pyOpenSSL to "
"support it, Twisted can perform only rudimentary TLS client hostname "
"verification. Many valid certificate/hostname mappings may be "
"rejected."
)
if _usablePyOpenSSL(lib.__version__):
try:
from service_identity import VerificationError
from service_identity.pyopenssl import verify_hostname
return verify_hostname, VerificationError
except ImportError as e:
warnings.warn_explicit(
"You do not have a working installation of the "
"service_identity module: '" + str(e) + "'. "
"Please install it from "
"<https://pypi.python.org/pypi/service_identity> and make "
"sure all of its dependencies are satisfied. "
+ whatsWrong,
# Unfortunately the lineno is required.
category=UserWarning, filename="", lineno=0)
else:
warnings.warn_explicit(
"Your version of pyOpenSSL, {0}, is out of date. "
"Please upgrade to at least 0.12 and install service_identity "
"from <https://pypi.python.org/pypi/service_identity>. "
.format(lib.__version__) + whatsWrong,
# Unfortunately the lineno is required.
category=UserWarning, filename="", lineno=0)
return simpleVerifyHostname, SimpleVerificationError
verifyHostname, VerificationError = _selectVerifyImplementation(OpenSSL)
from zope.interface import Interface, implementer
from twisted.internet.defer import Deferred
from twisted.internet.error import VerifyError, CertificateError
from twisted.internet.interfaces import (
IAcceptableCiphers, ICipher, IOpenSSLClientConnectionCreator
)
from twisted.python import reflect, util
from twisted.python.deprecate import _mutuallyExclusiveArguments
from twisted.python.compat import nativeString, networkString, unicode
from twisted.python.constants import Flags, FlagConstant
from twisted.python.failure import Failure
from twisted.python.util import FancyEqMixin
from twisted.python.deprecate import deprecated
from twisted.python.versions import Version
def _sessionCounter(counter=itertools.count()):
"""
Private - shared between all OpenSSLCertificateOptions, counts up to
provide a unique session id for each context.
"""
return next(counter)
class ProtocolNegotiationSupport(Flags):
"""
L{ProtocolNegotiationSupport} defines flags which are used to indicate the
level of NPN/ALPN support provided by the TLS backend.
@cvar NOSUPPORT: There is no support for NPN or ALPN. This is exclusive
with both L{NPN} and L{ALPN}.
@cvar NPN: The implementation supports Next Protocol Negotiation.
@cvar ALPN: The implementation supports Application Layer Protocol
Negotiation.
"""
NPN = FlagConstant(0x0001)
ALPN = FlagConstant(0x0002)
# FIXME: https://twistedmatrix.com/trac/ticket/8074
# Currently flags with literal zero values behave incorrectly. However,
# creating a flag by NOTing a flag with itself appears to work totally fine, so
# do that instead.
ProtocolNegotiationSupport.NOSUPPORT = (
ProtocolNegotiationSupport.NPN ^ ProtocolNegotiationSupport.NPN
)
def protocolNegotiationMechanisms():
"""
Checks whether your versions of PyOpenSSL and OpenSSL are recent enough to
support protocol negotiation, and if they are, what kind of protocol
negotiation is supported.
@return: A combination of flags from L{ProtocolNegotiationSupport} that
indicate which mechanisms for protocol negotiation are supported.
@rtype: L{FlagConstant}
"""
support = ProtocolNegotiationSupport.NOSUPPORT
ctx = SSL.Context(SSL.SSLv23_METHOD)
try:
ctx.set_npn_advertise_callback(lambda c: None)
except (AttributeError, NotImplementedError):
pass
else:
support |= ProtocolNegotiationSupport.NPN
try:
ctx.set_alpn_select_callback(lambda c: None)
except (AttributeError, NotImplementedError):
pass
else:
support |= ProtocolNegotiationSupport.ALPN
return support
_x509names = {
'CN': 'commonName',
'commonName': 'commonName',
'O': 'organizationName',
'organizationName': 'organizationName',
'OU': 'organizationalUnitName',
'organizationalUnitName': 'organizationalUnitName',
'L': 'localityName',
'localityName': 'localityName',
'ST': 'stateOrProvinceName',
'stateOrProvinceName': 'stateOrProvinceName',
'C': 'countryName',
'countryName': 'countryName',
'emailAddress': 'emailAddress'}
class DistinguishedName(dict):
"""
Identify and describe an entity.
Distinguished names are used to provide a minimal amount of identifying
information about a certificate issuer or subject. They are commonly
created with one or more of the following fields::
commonName (CN)
organizationName (O)
organizationalUnitName (OU)
localityName (L)
stateOrProvinceName (ST)
countryName (C)
emailAddress
A L{DistinguishedName} should be constructed using keyword arguments whose
keys can be any of the field names above (as a native string), and the
values are either Unicode text which is encodable to ASCII, or C{bytes}
limited to the ASCII subset. Any fields passed to the constructor will be
set as attributes, accessible using both their extended name and their
shortened acronym. The attribute values will be the ASCII-encoded
bytes. For example::
>>> dn = DistinguishedName(commonName=b'www.example.com',
... C='US')
>>> dn.C
b'US'
>>> dn.countryName
b'US'
>>> hasattr(dn, "organizationName")
False
L{DistinguishedName} instances can also be used as dictionaries; the keys
are extended name of the fields::
>>> dn.keys()
['countryName', 'commonName']
>>> dn['countryName']
b'US'
"""
__slots__ = ()
def __init__(self, **kw):
for k, v in kw.items():
setattr(self, k, v)
def _copyFrom(self, x509name):
for name in _x509names:
value = getattr(x509name, name, None)
if value is not None:
setattr(self, name, value)
def _copyInto(self, x509name):
for k, v in self.items():
setattr(x509name, k, nativeString(v))
def __repr__(self):
return '<DN %s>' % (dict.__repr__(self)[1:-1])
def __getattr__(self, attr):
try:
return self[_x509names[attr]]
except KeyError:
raise AttributeError(attr)
def __setattr__(self, attr, value):
if attr not in _x509names:
raise AttributeError("%s is not a valid OpenSSL X509 name field" % (attr,))
realAttr = _x509names[attr]
if not isinstance(value, bytes):
value = value.encode("ascii")
self[realAttr] = value
def inspect(self):
"""
Return a multi-line, human-readable representation of this DN.
@rtype: C{str}
"""
l = []
lablen = 0
def uniqueValues(mapping):
return set(mapping.values())
for k in sorted(uniqueValues(_x509names)):
label = util.nameToLabel(k)
lablen = max(len(label), lablen)
v = getattr(self, k, None)
if v is not None:
l.append((label, nativeString(v)))
lablen += 2
for n, (label, attr) in enumerate(l):
l[n] = (label.rjust(lablen)+': '+ attr)
return '\n'.join(l)
DN = DistinguishedName
class CertBase:
"""
Base class for public (certificate only) and private (certificate + key
pair) certificates.
@ivar original: The underlying OpenSSL certificate object.
@type original: L{OpenSSL.crypto.X509}
"""
def __init__(self, original):
self.original = original
def _copyName(self, suffix):
dn = DistinguishedName()
dn._copyFrom(getattr(self.original, 'get_'+suffix)())
return dn
def getSubject(self):
"""
Retrieve the subject of this certificate.
@return: A copy of the subject of this certificate.
@rtype: L{DistinguishedName}
"""
return self._copyName('subject')
def __conform__(self, interface):
"""
Convert this L{CertBase} into a provider of the given interface.
@param interface: The interface to conform to.
@type interface: L{zope.interface.interfaces.IInterface}
@return: an L{IOpenSSLTrustRoot} provider or L{NotImplemented}
@rtype: C{interface} or L{NotImplemented}
"""
if interface is IOpenSSLTrustRoot:
return OpenSSLCertificateAuthorities([self.original])
return NotImplemented
def _handleattrhelper(Class, transport, methodName):
"""
(private) Helper for L{Certificate.peerFromTransport} and
L{Certificate.hostFromTransport} which checks for incompatible handle types
and null certificates and raises the appropriate exception or returns the
appropriate certificate object.
"""
method = getattr(transport.getHandle(),
"get_%s_certificate" % (methodName,), None)
if method is None:
raise CertificateError(
"non-TLS transport %r did not have %s certificate" % (transport, methodName))
cert = method()
if cert is None:
raise CertificateError(
"TLS transport %r did not have %s certificate" % (transport, methodName))
return Class(cert)
class Certificate(CertBase):
"""
An x509 certificate.
"""
def __repr__(self):
return '<%s Subject=%s Issuer=%s>' % (self.__class__.__name__,
self.getSubject().commonName,
self.getIssuer().commonName)
def __eq__(self, other):
if isinstance(other, Certificate):
return self.dump() == other.dump()
return False
def __ne__(self, other):
return not self.__eq__(other)
def load(Class, requestData, format=crypto.FILETYPE_ASN1, args=()):
"""
Load a certificate from an ASN.1- or PEM-format string.
@rtype: C{Class}
"""
return Class(crypto.load_certificate(format, requestData), *args)
load = classmethod(load)
_load = load
def dumpPEM(self):
"""
Dump this certificate to a PEM-format data string.
@rtype: C{str}
"""
return self.dump(crypto.FILETYPE_PEM)
def loadPEM(Class, data):
"""
Load a certificate from a PEM-format data string.
@rtype: C{Class}
"""
return Class.load(data, crypto.FILETYPE_PEM)
loadPEM = classmethod(loadPEM)
def peerFromTransport(Class, transport):
"""
Get the certificate for the remote end of the given transport.
@type: L{ISystemHandle}
@rtype: C{Class}
@raise: L{CertificateError}, if the given transport does not have a peer
certificate.
"""
return _handleattrhelper(Class, transport, 'peer')
peerFromTransport = classmethod(peerFromTransport)
def hostFromTransport(Class, transport):
"""
Get the certificate for the local end of the given transport.
@param transport: an L{ISystemHandle} provider; the transport we will
@rtype: C{Class}
@raise: L{CertificateError}, if the given transport does not have a host
certificate.
"""
return _handleattrhelper(Class, transport, 'host')
hostFromTransport = classmethod(hostFromTransport)
def getPublicKey(self):
"""
Get the public key for this certificate.
@rtype: L{PublicKey}
"""
return PublicKey(self.original.get_pubkey())
def dump(self, format=crypto.FILETYPE_ASN1):
return crypto.dump_certificate(format, self.original)
def serialNumber(self):
"""
Retrieve the serial number of this certificate.
@rtype: C{int}
"""
return self.original.get_serial_number()
def digest(self, method='md5'):
"""
Return a digest hash of this certificate using the specified hash
algorithm.
@param method: One of C{'md5'} or C{'sha'}.
@rtype: C{str}
"""
return self.original.digest(method)
def _inspect(self):
return '\n'.join(['Certificate For Subject:',
self.getSubject().inspect(),
'\nIssuer:',
self.getIssuer().inspect(),
'\nSerial Number: %d' % self.serialNumber(),
'Digest: %s' % nativeString(self.digest())])
def inspect(self):
"""
Return a multi-line, human-readable representation of this
Certificate, including information about the subject, issuer, and
public key.
"""
return '\n'.join((self._inspect(), self.getPublicKey().inspect()))
def getIssuer(self):
"""
Retrieve the issuer of this certificate.
@rtype: L{DistinguishedName}
@return: A copy of the issuer of this certificate.
"""
return self._copyName('issuer')
def options(self, *authorities):
raise NotImplementedError('Possible, but doubtful we need this yet')
class CertificateRequest(CertBase):
"""
An x509 certificate request.
Certificate requests are given to certificate authorities to be signed and
returned resulting in an actual certificate.
"""
def load(Class, requestData, requestFormat=crypto.FILETYPE_ASN1):
req = crypto.load_certificate_request(requestFormat, requestData)
dn = DistinguishedName()
dn._copyFrom(req.get_subject())
if not req.verify(req.get_pubkey()):
raise VerifyError("Can't verify that request for %r is self-signed." % (dn,))
return Class(req)
load = classmethod(load)
def dump(self, format=crypto.FILETYPE_ASN1):
return crypto.dump_certificate_request(format, self.original)
class PrivateCertificate(Certificate):
"""
An x509 certificate and private key.
"""
def __repr__(self):
return Certificate.__repr__(self) + ' with ' + repr(self.privateKey)
def _setPrivateKey(self, privateKey):
if not privateKey.matches(self.getPublicKey()):
raise VerifyError(
"Certificate public and private keys do not match.")
self.privateKey = privateKey
return self
def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
"""
Create a new L{PrivateCertificate} from the given certificate data and
this instance's private key.
"""
return self.load(newCertData, self.privateKey, format)
def load(Class, data, privateKey, format=crypto.FILETYPE_ASN1):
return Class._load(data, format)._setPrivateKey(privateKey)
load = classmethod(load)
def inspect(self):
return '\n'.join([Certificate._inspect(self),
self.privateKey.inspect()])
def dumpPEM(self):
"""
Dump both public and private parts of a private certificate to
PEM-format data.
"""
return self.dump(crypto.FILETYPE_PEM) + self.privateKey.dump(crypto.FILETYPE_PEM)
def loadPEM(Class, data):
"""
Load both private and public parts of a private certificate from a
chunk of PEM-format data.
"""
return Class.load(data, KeyPair.load(data, crypto.FILETYPE_PEM),
crypto.FILETYPE_PEM)
loadPEM = classmethod(loadPEM)
def fromCertificateAndKeyPair(Class, certificateInstance, privateKey):
privcert = Class(certificateInstance.original)
return privcert._setPrivateKey(privateKey)
fromCertificateAndKeyPair = classmethod(fromCertificateAndKeyPair)
def options(self, *authorities):
"""
Create a context factory using this L{PrivateCertificate}'s certificate
and private key.
@param authorities: A list of L{Certificate} object
@return: A context factory.
@rtype: L{CertificateOptions <twisted.internet.ssl.CertificateOptions>}
"""
options = dict(privateKey=self.privateKey.original,
certificate=self.original)
if authorities:
options.update(dict(trustRoot=OpenSSLCertificateAuthorities(
[auth.original for auth in authorities]
)))
return OpenSSLCertificateOptions(**options)
def certificateRequest(self, format=crypto.FILETYPE_ASN1,
digestAlgorithm='sha256'):
return self.privateKey.certificateRequest(
self.getSubject(),
format,
digestAlgorithm)
def signCertificateRequest(self,
requestData,
verifyDNCallback,
serialNumber,
requestFormat=crypto.FILETYPE_ASN1,
certificateFormat=crypto.FILETYPE_ASN1):
issuer = self.getSubject()
return self.privateKey.signCertificateRequest(
issuer,
requestData,
verifyDNCallback,
serialNumber,
requestFormat,
certificateFormat)
def signRequestObject(self, certificateRequest, serialNumber,
secondsToExpiry=60 * 60 * 24 * 365, # One year
digestAlgorithm='sha256'):
return self.privateKey.signRequestObject(self.getSubject(),
certificateRequest,
serialNumber,
secondsToExpiry,
digestAlgorithm)
class PublicKey:
"""
A L{PublicKey} is a representation of the public part of a key pair.
You can't do a whole lot with it aside from comparing it to other
L{PublicKey} objects.
@note: If constructing a L{PublicKey} manually, be sure to pass only a
L{OpenSSL.crypto.PKey} that does not contain a private key!
@ivar original: The original private key.
"""
def __init__(self, osslpkey):
"""
@param osslpkey: The underlying pyOpenSSL key object.
@type osslpkey: L{OpenSSL.crypto.PKey}
"""
self.original = osslpkey
def matches(self, otherKey):
"""
Does this L{PublicKey} contain the same value as another L{PublicKey}?
@param otherKey: The key to compare C{self} to.
@type otherKey: L{PublicKey}
@return: L{True} if these keys match, L{False} if not.
@rtype: L{bool}
"""
return self.keyHash() == otherKey.keyHash()
# XXX This could be a useful method, but sometimes it triggers a segfault,
# so we'll steer clear for now.
# def verifyCertificate(self, certificate):
# """
# returns None, or raises a VerifyError exception if the certificate
# could not be verified.
# """
# if not certificate.original.verify(self.original):
# raise VerifyError("We didn't sign that certificate.")
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.keyHash())
def keyHash(self):
"""
Compute a hash of the underlying PKey object.
The purpose of this method is to allow you to determine if two
certificates share the same public key; it is not really useful for
anything else.
In versions of Twisted prior to 15.0, C{keyHash} used a technique
involving certificate requests for computing the hash that was not
stable in the face of changes to the underlying OpenSSL library.
The technique currently being used - using Netscape SPKI APIs in
OpenSSL - is still somewhat dubious, but due to limitations in both
pyOpenSSL and OpenSSL APIs, it is not currently possible to compute a
reliable hash of the public key in isolation (i.e. not paired with a
specific certificate).
@return: Return a 32-character hexadecimal string uniquely identifying
this public key, I{for this version of Twisted}.
@rtype: native L{str}
"""
nsspki = crypto.NetscapeSPKI()
nsspki.set_pubkey(self.original)
encoded = nsspki.b64_encode()
raw = a2b_base64(encoded)
h = md5()
h.update(raw)
return h.hexdigest()
def inspect(self):
return 'Public Key with Hash: %s' % (self.keyHash(),)
class KeyPair(PublicKey):
def load(Class, data, format=crypto.FILETYPE_ASN1):
return Class(crypto.load_privatekey(format, data))
load = classmethod(load)
def dump(self, format=crypto.FILETYPE_ASN1):
return crypto.dump_privatekey(format, self.original)
def __getstate__(self):
return self.dump()
def __setstate__(self, state):
self.__init__(crypto.load_privatekey(crypto.FILETYPE_ASN1, state))
def inspect(self):
t = self.original.type()
if t == crypto.TYPE_RSA:
ts = 'RSA'
elif t == crypto.TYPE_DSA:
ts = 'DSA'
else:
ts = '(Unknown Type!)'
L = (self.original.bits(), ts, self.keyHash())
return '%s-bit %s Key Pair with Hash: %s' % L
def generate(Class, kind=crypto.TYPE_RSA, size=1024):
pkey = crypto.PKey()
pkey.generate_key(kind, size)
return Class(pkey)
def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
return PrivateCertificate.load(newCertData, self, format)
generate = classmethod(generate)
def requestObject(self, distinguishedName, digestAlgorithm='sha256'):
req = crypto.X509Req()
req.set_pubkey(self.original)
distinguishedName._copyInto(req.get_subject())
req.sign(self.original, digestAlgorithm)
return CertificateRequest(req)
def certificateRequest(self, distinguishedName,
format=crypto.FILETYPE_ASN1,
digestAlgorithm='sha256'):
"""Create a certificate request signed with this key.
@return: a string, formatted according to the 'format' argument.
"""
return self.requestObject(distinguishedName, digestAlgorithm).dump(format)
def signCertificateRequest(self,
issuerDistinguishedName,
requestData,
verifyDNCallback,
serialNumber,
requestFormat=crypto.FILETYPE_ASN1,
certificateFormat=crypto.FILETYPE_ASN1,
secondsToExpiry=60 * 60 * 24 * 365, # One year
digestAlgorithm='sha256'):
"""
Given a blob of certificate request data and a certificate authority's
DistinguishedName, return a blob of signed certificate data.
If verifyDNCallback returns a Deferred, I will return a Deferred which
fires the data when that Deferred has completed.
"""
hlreq = CertificateRequest.load(requestData, requestFormat)
dn = hlreq.getSubject()
vval = verifyDNCallback(dn)
def verified(value):
if not value:
raise VerifyError("DN callback %r rejected request DN %r" % (verifyDNCallback, dn))
return self.signRequestObject(issuerDistinguishedName, hlreq,
serialNumber, secondsToExpiry, digestAlgorithm).dump(certificateFormat)
if isinstance(vval, Deferred):
return vval.addCallback(verified)
else:
return verified(vval)
def signRequestObject(self,
issuerDistinguishedName,
requestObject,
serialNumber,
secondsToExpiry=60 * 60 * 24 * 365, # One year
digestAlgorithm='sha256'):
"""
Sign a CertificateRequest instance, returning a Certificate instance.
"""
req = requestObject.original
cert = crypto.X509()
issuerDistinguishedName._copyInto(cert.get_issuer())
cert.set_subject(req.get_subject())
cert.set_pubkey(req.get_pubkey())
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(secondsToExpiry)
cert.set_serial_number(serialNumber)
cert.sign(self.original, digestAlgorithm)
return Certificate(cert)
def selfSignedCert(self, serialNumber, **kw):
dn = DN(**kw)
return PrivateCertificate.fromCertificateAndKeyPair(
self.signRequestObject(dn, self.requestObject(dn), serialNumber),
self)
KeyPair.__getstate__ = deprecated(Version("Twisted", 15, 0, 0),
"a real persistence system")(KeyPair.__getstate__)
KeyPair.__setstate__ = deprecated(Version("Twisted", 15, 0, 0),
"a real persistence system")(KeyPair.__setstate__)
class IOpenSSLTrustRoot(Interface):
"""
Trust settings for an OpenSSL context.
Note that this interface's methods are private, so things outside of
Twisted shouldn't implement it.
"""
def _addCACertsToContext(context):
"""
Add certificate-authority certificates to an SSL context whose
connections should trust those authorities.
@param context: An SSL context for a connection which should be
verified by some certificate authority.
@type context: L{OpenSSL.SSL.Context}
@return: L{None}
"""
@implementer(IOpenSSLTrustRoot)
class OpenSSLCertificateAuthorities(object):
"""
Trust an explicitly specified set of certificates, represented by a list of
L{OpenSSL.crypto.X509} objects.
"""
def __init__(self, caCerts):
"""