electrum-bitcoinprivate/lib/x509.py

342 lines
11 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python
#
2019-12-24 03:21:35 -08:00
# Electrum - lightweight bitcoinprivate client
# Copyright (C) 2014 Thomas Voegtlin
#
2016-02-23 02:36:42 -08:00
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
2016-02-23 02:36:42 -08:00
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
2016-02-23 02:36:42 -08:00
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
2017-01-22 10:25:24 -08:00
from . import util
from .util import profiler, bh2u
import ecdsa
import hashlib
2014-09-18 14:38:30 -07:00
# algo OIDs
2017-01-22 10:25:24 -08:00
ALGO_RSA_SHA1 = '1.2.840.113549.1.1.5'
2015-04-14 06:04:04 -07:00
ALGO_RSA_SHA256 = '1.2.840.113549.1.1.11'
ALGO_RSA_SHA384 = '1.2.840.113549.1.1.12'
ALGO_RSA_SHA512 = '1.2.840.113549.1.1.13'
2015-04-30 08:51:51 -07:00
ALGO_ECDSA_SHA256 = '1.2.840.10045.4.3.2'
# prefixes, see http://stackoverflow.com/questions/3713774/c-sharp-how-to-calculate-asn-1-der-encoding-of-a-particular-hash-algorithm
2017-01-22 10:25:24 -08:00
PREFIX_RSA_SHA256 = bytearray(
[0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20])
PREFIX_RSA_SHA384 = bytearray(
[0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30])
PREFIX_RSA_SHA512 = bytearray(
[0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40])
2016-02-23 02:35:08 -08:00
# types used in ASN1 structured data
ASN1_TYPES = {
2017-01-22 10:25:24 -08:00
'BOOLEAN' : 0x01,
'INTEGER' : 0x02,
'BIT STRING' : 0x03,
'OCTET STRING' : 0x04,
'NULL' : 0x05,
2016-02-23 02:35:08 -08:00
'OBJECT IDENTIFIER': 0x06,
2017-01-22 10:25:24 -08:00
'SEQUENCE' : 0x70,
'SET' : 0x71,
'PrintableString' : 0x13,
'IA5String' : 0x16,
'UTCTime' : 0x17,
2017-02-05 02:38:44 -08:00
'GeneralizedTime' : 0x18,
2017-01-22 10:25:24 -08:00
'ENUMERATED' : 0x0A,
'UTF8String' : 0x0C,
2016-02-23 02:35:08 -08:00
}
2017-01-22 10:25:24 -08:00
class CertificateError(Exception):
pass
2016-02-23 02:35:08 -08:00
2017-01-22 10:25:24 -08:00
# helper functions
2016-02-23 02:35:08 -08:00
def bitstr_to_bytestr(s):
2017-01-30 01:36:56 -08:00
if s[0] != 0x00:
2017-02-05 02:38:44 -08:00
raise TypeError('no padding')
2016-02-23 02:35:08 -08:00
return s[1:]
2017-01-22 10:25:24 -08:00
2016-02-23 02:35:08 -08:00
def bytestr_to_int(s):
i = 0
for char in s:
i <<= 8
2017-01-30 01:36:56 -08:00
i |= char
2016-02-23 02:35:08 -08:00
return i
2017-01-22 10:25:24 -08:00
2016-02-23 02:35:08 -08:00
def decode_OID(s):
r = []
2017-01-30 01:36:56 -08:00
r.append(s[0] // 40)
2016-02-23 02:35:08 -08:00
r.append(s[0] % 40)
k = 0
for i in s[1:]:
if i < 128:
2017-01-22 10:25:24 -08:00
r.append(i + 128 * k)
2016-02-23 02:35:08 -08:00
k = 0
else:
2017-01-22 10:25:24 -08:00
k = (i - 128) + 128 * k
2016-02-23 02:35:08 -08:00
return '.'.join(map(str, r))
def encode_OID(oid):
2017-01-30 01:36:56 -08:00
x = [int(i) for i in oid.split('.')]
2017-01-22 10:25:24 -08:00
s = chr(x[0] * 40 + x[1])
2016-02-23 02:35:08 -08:00
for i in x[2:]:
ss = chr(i % 128)
while i > 128:
2017-01-22 10:25:24 -08:00
i //= 128
2016-02-23 02:35:08 -08:00
ss = chr(128 + i % 128) + ss
s += ss
return s
2017-01-30 01:36:56 -08:00
class ASN1_Node(bytes):
2016-02-23 02:35:08 -08:00
def get_node(self, ix):
# return index of first byte, first content byte and last byte.
2017-01-30 01:36:56 -08:00
first = self[ix + 1]
2017-02-05 02:38:44 -08:00
if (first & 0x80) == 0:
2016-02-23 02:35:08 -08:00
length = first
ixf = ix + 2
ixl = ixf + length - 1
2017-01-22 10:25:24 -08:00
else:
2016-02-23 02:35:08 -08:00
lengthbytes = first & 0x7F
2017-01-22 10:25:24 -08:00
length = bytestr_to_int(self[ix + 2:ix + 2 + lengthbytes])
2016-02-23 02:35:08 -08:00
ixf = ix + 2 + lengthbytes
2017-01-22 10:25:24 -08:00
ixl = ixf + length - 1
return ix, ixf, ixl
2017-01-30 01:36:56 -08:00
def root(self):
return self.get_node(0)
def next_node(self, node):
ixs, ixf, ixl = node
return self.get_node(ixl + 1)
def first_child(self, node):
ixs, ixf, ixl = node
if self[ixs] & 0x20 != 0x20:
2017-02-05 02:38:44 -08:00
raise TypeError('Can only open constructed types.', hex(self[ixs]))
2017-01-30 01:36:56 -08:00
return self.get_node(ixf)
def is_child_of(node1, node2):
ixs, ixf, ixl = node1
jxs, jxf, jxl = node2
return ((ixf <= jxs) and (jxl <= ixl)) or ((jxf <= ixs) and (ixl <= jxl))
def get_all(self, node):
# return type + length + value
ixs, ixf, ixl = node
return self[ixs:ixl + 1]
def get_value_of_type(self, node, asn1_type):
# verify type byte and return content
ixs, ixf, ixl = node
if ASN1_TYPES[asn1_type] != self[ixs]:
2017-02-05 02:38:44 -08:00
raise TypeError('Wrong type:', hex(self[ixs]), hex(ASN1_TYPES[asn1_type]))
2017-01-30 01:36:56 -08:00
return self[ixf:ixl + 1]
def get_value(self, node):
ixs, ixf, ixl = node
return self[ixf:ixl + 1]
def get_children(self, node):
nodes = []
ii = self.first_child(node)
2016-02-23 02:35:08 -08:00
nodes.append(ii)
2017-01-30 01:36:56 -08:00
while ii[2] < node[2]:
ii = self.next_node(ii)
nodes.append(ii)
return nodes
def get_sequence(self):
return list(map(lambda j: self.get_value(j), self.get_children(self.root())))
def get_dict(self, node):
p = {}
for ii in self.get_children(node):
for iii in self.get_children(ii):
iiii = self.first_child(iii)
oid = decode_OID(self.get_value_of_type(iiii, 'OBJECT IDENTIFIER'))
iiii = self.next_node(iiii)
value = self.get_value(iiii)
p[oid] = value
return p
2017-01-22 10:25:24 -08:00
class X509(object):
2015-08-07 02:39:30 -07:00
def __init__(self, b):
2015-04-14 06:04:04 -07:00
self.bytes = bytearray(b)
2015-04-14 06:04:04 -07:00
2017-01-30 01:36:56 -08:00
der = ASN1_Node(b)
2016-02-23 02:35:08 -08:00
root = der.root()
cert = der.first_child(root)
2015-04-14 06:04:04 -07:00
# data for signature
2016-02-23 02:35:08 -08:00
self.data = der.get_all(cert)
2015-04-14 06:04:04 -07:00
# optional version field
2017-01-30 01:36:56 -08:00
if der.get_value(cert)[0] == 0xa0:
2016-02-23 02:35:08 -08:00
version = der.first_child(cert)
serial_number = der.next_node(version)
2015-04-14 06:04:04 -07:00
else:
2016-02-23 02:35:08 -08:00
serial_number = der.first_child(cert)
self.serial_number = bytestr_to_int(der.get_value_of_type(serial_number, 'INTEGER'))
2015-04-14 06:04:04 -07:00
# signature algorithm
2016-02-23 02:35:08 -08:00
sig_algo = der.next_node(serial_number)
ii = der.first_child(sig_algo)
self.sig_algo = decode_OID(der.get_value_of_type(ii, 'OBJECT IDENTIFIER'))
2015-04-14 06:04:04 -07:00
# issuer
2016-02-23 02:35:08 -08:00
issuer = der.next_node(sig_algo)
self.issuer = der.get_dict(issuer)
2015-04-14 06:04:04 -07:00
# validity
2016-02-23 02:35:08 -08:00
validity = der.next_node(issuer)
ii = der.first_child(validity)
2017-02-05 02:38:44 -08:00
try:
self.notBefore = der.get_value_of_type(ii, 'UTCTime')
except TypeError:
self.notBefore = der.get_value_of_type(ii, 'GeneralizedTime')[2:] # strip year
2016-02-23 02:35:08 -08:00
ii = der.next_node(ii)
2017-02-05 02:38:44 -08:00
try:
self.notAfter = der.get_value_of_type(ii, 'UTCTime')
except TypeError:
self.notAfter = der.get_value_of_type(ii, 'GeneralizedTime')[2:] # strip year
2015-04-14 06:04:04 -07:00
# subject
2016-02-23 02:35:08 -08:00
subject = der.next_node(validity)
self.subject = der.get_dict(subject)
subject_pki = der.next_node(subject)
public_key_algo = der.first_child(subject_pki)
ii = der.first_child(public_key_algo)
self.public_key_algo = decode_OID(der.get_value_of_type(ii, 'OBJECT IDENTIFIER'))
2017-02-05 02:38:44 -08:00
if self.public_key_algo != '1.2.840.10045.2.1': # for non EC public key
# pubkey modulus and exponent
subject_public_key = der.next_node(public_key_algo)
spk = der.get_value_of_type(subject_public_key, 'BIT STRING')
spk = ASN1_Node(bitstr_to_bytestr(spk))
r = spk.root()
modulus = spk.first_child(r)
exponent = spk.next_node(modulus)
rsa_n = spk.get_value_of_type(modulus, 'INTEGER')
rsa_e = spk.get_value_of_type(exponent, 'INTEGER')
self.modulus = ecdsa.util.string_to_number(rsa_n)
self.exponent = ecdsa.util.string_to_number(rsa_e)
else:
subject_public_key = der.next_node(public_key_algo)
spk = der.get_value_of_type(subject_public_key, 'BIT STRING')
self.ec_public_key = spk
# extensions
2015-04-14 06:04:04 -07:00
self.CA = False
self.AKI = None
self.SKI = None
i = subject_pki
while i[2] < cert[2]:
2016-02-23 02:35:08 -08:00
i = der.next_node(i)
d = der.get_dict(i)
for oid, value in d.items():
2016-02-23 02:35:08 -08:00
value = ASN1_Node(value)
if oid == '2.5.29.19':
# Basic Constraints
self.CA = bool(value)
elif oid == '2.5.29.14':
# Subject Key Identifier
2016-02-23 02:35:08 -08:00
r = value.root()
value = value.get_value_of_type(r, 'OCTET STRING')
2017-01-30 01:36:56 -08:00
self.SKI = bh2u(value)
elif oid == '2.5.29.35':
# Authority Key Identifier
2017-01-30 01:36:56 -08:00
self.AKI = bh2u(value.get_sequence()[0])
else:
pass
2015-04-14 06:04:04 -07:00
# cert signature
2016-02-23 02:35:08 -08:00
cert_sig_algo = der.next_node(cert)
ii = der.first_child(cert_sig_algo)
self.cert_sig_algo = decode_OID(der.get_value_of_type(ii, 'OBJECT IDENTIFIER'))
cert_sig = der.next_node(cert_sig_algo)
self.signature = der.get_value(cert_sig)[1:]
def get_keyID(self):
# http://security.stackexchange.com/questions/72077/validating-an-ssl-certificate-chain-according-to-rfc-5280-am-i-understanding-th
return self.SKI if self.SKI else repr(self.subject)
def get_issuer_keyID(self):
return self.AKI if self.AKI else repr(self.issuer)
def get_common_name(self):
return self.subject.get('2.5.4.3', b'unknown').decode()
2015-04-14 06:04:04 -07:00
def get_signature(self):
return self.cert_sig_algo, self.signature, self.data
def check_ca(self):
2015-04-14 06:04:04 -07:00
return self.CA
def check_date(self):
2015-04-14 06:04:04 -07:00
import time
now = time.time()
TIMESTAMP_FMT = '%y%m%d%H%M%SZ'
2017-01-30 01:36:56 -08:00
not_before = time.mktime(time.strptime(self.notBefore.decode('ascii'), TIMESTAMP_FMT))
not_after = time.mktime(time.strptime(self.notAfter.decode('ascii'), TIMESTAMP_FMT))
if not_before > now:
2017-01-22 10:25:24 -08:00
raise CertificateError('Certificate has not entered its valid date range. (%s)' % self.get_common_name())
if not_after <= now:
2017-01-22 10:25:24 -08:00
raise CertificateError('Certificate has expired. (%s)' % self.get_common_name())
def getFingerprint(self):
return hashlib.sha1(self.bytes).digest()
2015-02-15 12:27:11 -08:00
2015-04-14 06:04:04 -07:00
@profiler
2015-02-15 12:27:11 -08:00
def load_certificates(ca_path):
2017-01-22 10:25:24 -08:00
from . import pem
2015-02-15 12:27:11 -08:00
ca_list = {}
ca_keyID = {}
2017-02-05 02:38:44 -08:00
# ca_path = '/tmp/tmp.txt'
with open(ca_path, 'r', encoding='utf-8') as f:
2017-02-05 02:38:44 -08:00
s = f.read()
bList = pem.dePemList(s, "CERTIFICATE")
2015-02-15 12:27:11 -08:00
for b in bList:
try:
2015-08-07 02:39:30 -07:00
x = X509(b)
2015-04-14 06:04:04 -07:00
x.check_date()
except BaseException as e:
2017-02-05 02:38:44 -08:00
# with open('/tmp/tmp.txt', 'w') as f:
# f.write(pem.pem(b, 'CERTIFICATE').decode('ascii'))
2015-04-14 06:04:04 -07:00
util.print_error("cert error:", e)
2015-02-15 12:27:11 -08:00
continue
2015-04-14 06:04:04 -07:00
fp = x.getFingerprint()
ca_list[fp] = x
ca_keyID[x.get_keyID()] = fp
2015-04-14 06:04:04 -07:00
return ca_list, ca_keyID
2016-02-23 02:35:08 -08:00
if __name__ == "__main__":
import requests
2017-01-22 10:25:24 -08:00
2016-02-23 02:35:08 -08:00
util.set_verbosity(True)
ca_path = requests.certs.where()
ca_list, ca_keyID = load_certificates(ca_path)