Skip to content

Commit

Permalink
parsing of DSA keys from X.509 certificates
Browse files Browse the repository at this point in the history
  • Loading branch information
FrantisekKrenzelok committed Aug 25, 2020
1 parent b4b1339 commit b06fd33
Show file tree
Hide file tree
Showing 7 changed files with 339 additions and 5 deletions.
1 change: 1 addition & 0 deletions tlslite/utils/__init__.py
Expand Up @@ -22,6 +22,7 @@
"python_aes",
"python_rc4",
"python_rsakey",
"python_dsakey",
"rc4",
"rijndael",
"rsakey",
Expand Down
33 changes: 33 additions & 0 deletions tlslite/utils/dsakey.py
@@ -0,0 +1,33 @@
"""Abstract class for DSA."""

class DSAKey(object):
"""This is an abstract base class for DSA keys.
Particular implementations of DSA keys, such as
:py:class:`~.python_dsakey.Python_DSAKey`
... more coming
inherit from this.
To create or parse an DSA key, don't use one of these classes
directly. Instead, use the factory functions in
:py:class:`~tlslite.utils.keyfactory`.
"""

def __init__(self, p, q, g, x, y):
raise NotImplementedError()

def __len__(self):
raise NotImplementedError()

def hasPrivateKey(self):
raise NotImplementedError()

def hashAndSign(self, data, hAlg):
raise NotImplementedError()

def verify(self, signature, hash_bytes):
raise NotImplementedError()

@staticmethod
def generate(L, N):
raise NotImplementedError()
26 changes: 26 additions & 0 deletions tlslite/utils/keyfactory.py
Expand Up @@ -8,6 +8,7 @@
from .rsakey import RSAKey
from .python_rsakey import Python_RSAKey
from .python_ecdsakey import Python_ECDSAKey
from .python_dsakey import Python_DSAKey
from tlslite.utils import cryptomath

if cryptomath.m2cryptoLoaded:
Expand Down Expand Up @@ -233,3 +234,28 @@ def _create_public_ecdsa_key(point_x, point_y, curve_name,
if impl == "python":
return Python_ECDSAKey(point_x, point_y, curve_name)
raise ValueError("No acceptable implementation")

def _create_public_dsa_key(p, q, g, y,
implementations=("python",)):
"""
Convert public key parameters into concrete implementation of verifier.
The public key in DSA consists of four integers.
:type p: int
:param p: domain parameter, prime num defining Gaolis Field
:type q: int
:param q: domain parameter, prime factor of p-1
:type g: int
:param g: domain parameter, generator of q-order cyclic group GP(p)
:type y: int
:param y: public key
:type implementations: iterable of str
:param implementations: list of implementations that can be used as the
concrete implementation of the verifying key (only 'python' is
supported currently)
"""
for impl in implementations:
if impl == "python":
return Python_DSAKey(p=p, q=q, g=g, y=y)
raise ValueError("No acceptable implementation")
87 changes: 87 additions & 0 deletions tlslite/utils/python_dsakey.py
@@ -0,0 +1,87 @@
from ecdsa.der import encode_sequence, encode_integer, \
remove_sequence, remove_integer

from .cryptomath import getRandomNumber, getRandomPrime, \
powMod, numBits, bytesToNumber, invMod, secureHash

from .dsakey import DSAKey

class Python_DSAKey(DSAKey):

def __init__(self, p=0, q=0, g=0, x=0, y=0):
self.p = p
self.q = q
self.g = g
self.private_key = x
self.public_key = y
self.key_type = "dsa"

def __len__(self):
return numBits(self.p)

def hasPrivateKey(self):
return bool(self.private_key)

@staticmethod
def generate(L, N):
assert (L, N) in [(1024, 160), (2048, 224), (2048, 256), (3072, 256)]
key = Python_DSAKey()
(q, p) = Python_DSAKey.generate_qp(L, N)

index = getRandomNumber(1, (p-1))
g = powMod(index, int((p-1)/q), p)
x = getRandomNumber(1, q-1)
y = powMod(g, x, p)
key.q = q
key.p = p
key.g = g
key.private_key = x
key.public_key = y
return key

@staticmethod
def generate_qp(L, N):
assert (L, N) in [(1024, 160), (2048, 224), (2048, 256), (3072, 256)]

# TODO: optimize, docstring, implement Shawe-Taylor Random_Prime
q = int(getRandomPrime(N))
while True:
p = int(getRandomPrime(L))
if (p-1) % q:
break
return (q, p)

def hashAndSign(self, data, hAlg="sha1"):
# TODO: add assert for hash size < (q-1) constrain, docstring
digest = bytesToNumber(secureHash(bytearray(data), hAlg))
digest_size = numBits(digest)
N = numBits(self.q)
if N < digest_size:
digest &= ~(~0 << (digest_size - N))
k = getRandomNumber(1, (self.q-1))
r = powMod(self.g, k, self.p) % self.q
s = invMod(k, self.q) * (digest + self.private_key * r) % self.q
return encode_sequence(encode_integer(r), encode_integer(s))

def hashAndVerify(self, signature, data, hAlg="sha1"):
# Get r, s components from signature
digest = bytesToNumber(secureHash(bytearray(data), hAlg))
digest_size = numBits(digest)
N = numBits(self.q)
if N < digest_size:
digest &= ~(~0 << (digest_size - N))

# get r, s keys
body, rest = remove_sequence(signature)
assert bytesToNumber(rest) == 0
r, rest = remove_integer(body)
s, rest = remove_integer(rest)
assert bytesToNumber(rest) == 0

# check the signature
if 0 < r < self.q and 0 < s < self.q:
w = invMod(s, self.q)
u1 = (digest * w) % self.q
u2 = (r * w) % self.q
v = ((powMod(self.g, u1, self.p) * powMod(self.public_key, u2, self.p)) % self.p) % self.q
return r == v
36 changes: 33 additions & 3 deletions tlslite/utils/python_key.py
Expand Up @@ -2,6 +2,7 @@

from .python_rsakey import Python_RSAKey
from .python_ecdsakey import Python_ECDSAKey
from .python_dsakey import Python_DSAKey
from .pem import dePem, pemSniff
from .asn1parser import ASN1Parser
from .cryptomath import bytesToNumber
Expand All @@ -25,7 +26,10 @@ def parsePEM(s, passwordCallback=None):
return Python_Key._parse_pkcs8(bytes)
elif pemSniff(s, "RSA PRIVATE KEY"):
bytes = dePem(s, "RSA PRIVATE KEY")
return Python_Key._parse_ssleay(bytes)
return Python_Key._parse_ssleay(bytes, "rsa")
elif pemSniff(s, "DSA PRIVATE KEY"):
bytes = dePem(s, "DSA PRIVATE KEY")
return Python_Key._parse_dsa_ssleay(bytes)
elif pemSniff(s, "EC PRIVATE KEY"):
bytes = dePem(s, "EC PRIVATE KEY")
return Python_Key._parse_ecc_ssleay(bytes)
Expand All @@ -51,6 +55,8 @@ def _parse_pkcs8(bytes):
key_type = "rsa"
elif list(oid.value) == [42, 134, 72, 134, 247, 13, 1, 1, 10]:
key_type = "rsa-pss"
elif list(oid.value) == [42, 134, 72, 206, 56, 4, 1]:
key_type = "dsa"
elif list(oid.value) == [42, 134, 72, 206, 61, 2, 1]:
key_type = "ecdsa"
else:
Expand All @@ -64,6 +70,8 @@ def _parse_pkcs8(bytes):
parameters = alg_ident.getChild(1)
if parameters.value != bytearray(0):
raise SyntaxError("RSA parameters are not NULL")
if key_type == "dsa":
parameters = alg_ident.getChild(1)
elif key_type == "ecdsa":
if seq_len != 2:
raise SyntaxError("Invalid encoding of algorithm identifier")
Expand Down Expand Up @@ -91,20 +99,32 @@ def _parse_pkcs8(bytes):
if key_type == "ecdsa":
return Python_Key._parse_ecdsa_private_key(private_key_parser,
curve)
elif key_type == "dsa":
return Python_Key._parse_dsa_private_key(private_key_parser)
else:
return Python_Key._parse_asn1_private_key(private_key_parser,
key_type)

@staticmethod
def _parse_ssleay(data):
def _parse_ssleay(data, key_type="rsa"):
"""
Parse binary structure of the old SSLeay file format used by OpenSSL.
For RSA keys.
"""
private_key_parser = ASN1Parser(data)
# "rsa" type as old format doesn't support rsa-pss parameters
return Python_Key._parse_asn1_private_key(private_key_parser, "rsa")
return Python_Key._parse_asn1_private_key(private_key_parser, key_type)

@staticmethod
def _parse_dsa_ssleay(data):
"""
Parse binary structure of the old SSLeay file format used by OpenSSL.
For DSA keys.
"""
private_key_parser = ASN1Parser(data)
return Python_Key._parse_dsa_private_key(private_key_parser)

@staticmethod
def _parse_ecc_ssleay(data):
Expand Down Expand Up @@ -167,3 +187,13 @@ def _parse_asn1_private_key(private_key_parser, key_type):
qInv = bytesToNumber(private_key_parser.getChild(8).value)
return Python_RSAKey(n, e, d, p, q, dP, dQ, qInv, key_type)


@staticmethod
def _parse_dsa_private_key(private_key_parser):
p = bytesToNumber(private_key_parser.getChild(1).value)
q = bytesToNumber(private_key_parser.getChild(2).value)
g = bytesToNumber(private_key_parser.getChild(3).value)
y = bytesToNumber(private_key_parser.getChild(4).value)
x = bytesToNumber(private_key_parser.getChild(5).value)
return Python_DSAKey(p, q, g, x, y)

45 changes: 43 additions & 2 deletions tlslite/x509.py
@@ -1,4 +1,4 @@
# Authors:
# Authors:
# Trevor Perrin
# Google - parsing subject field
#
Expand Down Expand Up @@ -114,12 +114,14 @@ def parseBinary(self, bytes):
self.certAlg = "rsa"
elif list(alg_oid) == [42, 134, 72, 134, 247, 13, 1, 1, 10]:
self.certAlg = "rsa-pss"
elif list(alg_oid) == [42, 134, 72, 206, 56, 4, 1]:
self.certAlg = "dsa"
elif list(alg_oid) == [42, 134, 72, 206, 61, 2, 1]:
self.certAlg = "ecdsa"
else:
raise SyntaxError("Unrecognized AlgorithmIdentifier")

# for RSA the parameters of AlgorithmIdentifier should be a NULL
# for RSA the parameters of AlgorithmIdentifier shuld be a NULL
if self.certAlg == "rsa":
if alg_identifier_len != 2:
raise SyntaxError("Missing parameters in AlgorithmIdentifier")
Expand All @@ -131,6 +133,10 @@ def parseBinary(self, bytes):
self._ecdsa_pubkey_parsing(
tbs_certificate.getChildBytes(subject_public_key_info_index))
return
elif self.certAlg == "dsa":
self._ecdsa_pubkey_parsing(
tbs_certificate.getChildBytes(subject_public_key_info_index))
return
else: # rsa-pss
pass # ignore parameters, if any - don't apply key restrictions

Expand Down Expand Up @@ -189,6 +195,41 @@ def _ecdsa_pubkey_parsing(self, subject_public_key_info):
curve_name = public_key.curve.name
self.publicKey = _create_public_ecdsa_key(x, y, curve_name)

def _dsa_pubkey_parsing(self, subject_public_key_info):

# Get the subjectPublicKey
subject_public_key = subject_public_key_info.getChild(1)
self.subject_public_key = subject_public_key_info.getChildBytes(1)
self.subject_public_key = ASN1Parser(self.subject_public_key).value[1:]

# Adjust for BIT STRING encapsulation
if subject_public_key.value[0]:
raise SyntaxError()
subject_public_key = ASN1Parser(subject_public_key.value[1:])

# Get the {A, p, q}
A = subject_public_key.getChild(0)
p = subject_public_key.getChild(1)
g = subject_public_key.getChild(2)

# q member is in the third element of subject_public_key_info
subject_public_key = subject_public_key_info.getChild(2)
# Adjust for BIT STRING encapsulation
if subject_public_key.value[0]:
raise SyntaxError()
subject_public_key = ASN1Parser(subject_public_key.value[1:])
# Get the {q}
q = subject_public_key.getChild(0)

# Decode them into numbers
A = bytesToNumber(A.value)
p = bytesToNumber(p.value)
q = bytesToNumber(q.value)
g = bytesToNumber(g.value)

# Create a public key instance
self.publicKey = _createPublicDSAKey(p, q, g, A)

def getFingerprint(self):
"""
Get the hex-encoded fingerprint of this certificate.
Expand Down

0 comments on commit b06fd33

Please sign in to comment.