Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
56a4739
Switched everything to use cryptography
alex Sep 15, 2014
a46ea81
Added a comment; used a keyword argument, added pypy to travis
alex Sep 16, 2014
b42ff32
Try to update the installation docs
alex Sep 16, 2014
ca63b94
put pypy in tox.ini
alex Sep 18, 2014
6ee3f1a
Merge branch 'master' into switch-to-cryptography
alex Sep 18, 2014
848a720
Merge branch 'master' into switch-to-cryptography
alex Sep 19, 2014
f297704
Note OPenSSL headers as well
alex Sep 19, 2014
18bc966
Add back intro sentence
alex Sep 19, 2014
d563ba2
Document that pyasn1 is required
alex Sep 19, 2014
74d83f2
Merge branch 'master' into switch-to-cryptography
alex Sep 20, 2014
e680634
Merge branch 'master' into switch-to-cryptography
alex Sep 30, 2014
d3d816e
Bump version numbers
alex Sep 30, 2014
08cf9dc
try with one more GC, just to see if it reproduces
alex Sep 30, 2014
e8f1c41
Try removing some unused code?
alex Sep 30, 2014
fb5ea38
2 is really enough
alex Sep 30, 2014
d35e5d9
Document the pyasn1 requirement in teh readme
alex Sep 30, 2014
b16f91e
Skip the tests on PyPy
alex Oct 2, 2014
37756f3
Start porting ECDSA to cryptography. Everything except the to_der see…
alex Nov 8, 2014
b3884d2
Merge branch 'master' into switch-to-cryptography
alex Dec 18, 2014
eb3e117
A bunch of cleanup
alex Dec 18, 2014
8146a07
Missing import and extra import. All things in balance
alex Dec 18, 2014
cd9dee2
Fix EC generate
alex Dec 18, 2014
b764834
Initial work on serializing ecdsa keys
alex Dec 18, 2014
735be2b
py3k friendly
alex Dec 18, 2014
6ecf543
Python3 here as well
alex Dec 18, 2014
e2f1601
This is bytes
alex Dec 18, 2014
0974458
py3k fix
alex Dec 18, 2014
5861cde
Merge branch 'master' into switch-to-cryptography
alex Mar 15, 2015
5130ad1
Update for cryptography 0.8 and general cleanups
alex Mar 15, 2015
6186517
Whoops
alex Mar 15, 2015
04f763d
0.8 doesn't support DER yet, just export PEM, that's what we wanted t…
alex Mar 15, 2015
61777ed
This wants a string, not bytes, apparently
alex Mar 15, 2015
a167da7
Fix these backticks
alex Mar 15, 2015
fc0a231
Removed PyPy from travis, since that's orthagonal to this PR
alex Mar 15, 2015
6ed173a
Rmoeved unused imports
alex Mar 15, 2015
ffcbc09
More progress towards cleanup
alex Mar 18, 2015
95f712b
Fixes. Deleting code
alex Mar 18, 2015
fe2d1cd
No password here
alex Mar 18, 2015
67254b6
fix
alex Mar 18, 2015
7a03c65
fix
alex Mar 18, 2015
a282ec1
doh
alex Mar 18, 2015
339be69
Fixed tests.
alex Mar 19, 2015
29d1acd
Make sure we pass a str under py3k
alex Mar 19, 2015
4c8e157
Fixed extra comma
alex Apr 1, 2015
c52a400
Merge branch 'master' into switch-to-cryptography
alex Aug 1, 2015
9e67e71
removed references to python 3.2, which has basically no usage
alex Aug 1, 2015
30a7afc
Merge branch 'master' into switch-to-cryptography
alex Nov 4, 2015
d98f567
bad merge
alex Nov 4, 2015
c2a06d1
another bad merge
alex Nov 4, 2015
f5ba7d5
add this back in
alex Nov 4, 2015
7dbb01c
Merge branch 'master' into switch-to-cryptography
alex Dec 4, 2015
b41a265
Merge branch 'master' into switch-to-cryptography
alex Dec 17, 2015
b8f27b4
remove the duplicate readme
alex Dec 17, 2015
0a368f8
syntax fix
alex Dec 17, 2015
578ae9d
Merge branch 'master' into switch-to-cryptography
alex Dec 18, 2015
2d350c1
Merge branch 'master' into switch-to-cryptography
alex Feb 28, 2016
ecc04e5
removed the whitespace as was done on master
alex Feb 28, 2016
eac11dc
Merge branch 'master' into switch-to-cryptography
alex Apr 23, 2016
f133db6
handle invalid keys
alex Apr 23, 2016
57c1635
handle invalid keys in ecdsa
alex Apr 23, 2016
ff07a67
remove unused thing
alex Apr 23, 2016
d1e43c1
Merge branch 'master' into switch-to-cryptography
alex Apr 23, 2016
900b426
Merge branch 'master' into switch-to-cryptography
alex Apr 25, 2016
69b995a
crypto our crypto
alex Apr 25, 2016
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,9 @@ that should have come with this archive.
Requirements
------------

- `Python <http://www.python.org/>`_ 2.6, 2.7, or 3.3+ (3.2 should also work,
but it is not recommended)
- `pycrypto <https://www.dlitz.net/software/pycrypto/>`_ 2.1+
- `ecdsa <https://pypi.python.org/pypi/ecdsa>`_ 0.11+
- `Python <http://www.python.org/>`_ 2.6, 2.7, or 3.3+
- `Cryptography <https://cryptography.io>`_ 0.8 or better
- `pyasn1 <https://pypi.python.org/pypi/pyasn1>`_ 0.1.7 or better


Installation
Expand All @@ -66,13 +65,6 @@ Paramiko primarily supports POSIX platforms with standard OpenSSH
implementations, and is most frequently tested on Linux and OS X. Windows is
supported as well, though it may not be as straightforward.

Some Windows users whose Python is 64-bit have found that the PyCrypto
dependency ``winrandom`` may not install properly, leading to an
``ImportError``. In this scenario, you may need to compile ``winrandom``
yourself. See `Fabric #194 <https://github.com/fabric/fabric/issues/194>`_
for info.


Bugs & Support
--------------

Expand Down
123 changes: 87 additions & 36 deletions paramiko/dsskey.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,23 @@
DSS keys.
"""

import os
from hashlib import sha1

from Crypto.PublicKey import DSA
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives.asymmetric.utils import (
decode_rfc6979_signature, encode_rfc6979_signature
)

from paramiko import util
from paramiko.common import zero_byte
from paramiko.py3compat import long
from paramiko.ssh_exception import SSHException
from paramiko.message import Message
from paramiko.ber import BER, BERException
from paramiko.pkey import PKey


class DSSKey (PKey):
class DSSKey(PKey):
"""
Representation of a DSS key which can be used to sign an verify SSH2
data.
Expand Down Expand Up @@ -98,15 +100,21 @@ def can_sign(self):
return self.x is not None

def sign_ssh_data(self, data):
digest = sha1(data).digest()
dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q), long(self.x)))
# generate a suitable k
qsize = len(util.deflate_long(self.q, 0))
while True:
k = util.inflate_long(os.urandom(qsize), 1)
if (k > 2) and (k < self.q):
break
r, s = dss.sign(util.inflate_long(digest, 1), k)
key = dsa.DSAPrivateNumbers(
x=self.x,
public_numbers=dsa.DSAPublicNumbers(
y=self.y,
parameter_numbers=dsa.DSAParameterNumbers(
p=self.p,
q=self.q,
g=self.g
)
)
).private_key(backend=default_backend())
signer = key.signer(hashes.SHA1())
signer.update(data)
r, s = decode_rfc6979_signature(signer.finalize())

m = Message()
m.add_string('ssh-dss')
# apparently, in rare cases, r or s may be shorter than 20 bytes!
Expand All @@ -132,27 +140,65 @@ def verify_ssh_sig(self, data, msg):
# pull out (r, s) which are NOT encoded as mpints
sigR = util.inflate_long(sig[:20], 1)
sigS = util.inflate_long(sig[20:], 1)
sigM = util.inflate_long(sha1(data).digest(), 1)

dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q)))
return dss.verify(sigM, (sigR, sigS))

def _encode_key(self):
if self.x is None:
raise SSHException('Not enough key information')
keylist = [0, self.p, self.q, self.g, self.y, self.x]
signature = encode_rfc6979_signature(sigR, sigS)

key = dsa.DSAPublicNumbers(
y=self.y,
parameter_numbers=dsa.DSAParameterNumbers(
p=self.p,
q=self.q,
g=self.g
)
).public_key(backend=default_backend())
verifier = key.verifier(signature, hashes.SHA1())
verifier.update(data)
try:
b = BER()
b.encode(keylist)
except BERException:
raise SSHException('Unable to create ber encoding of key')
return b.asbytes()
verifier.verify()
except InvalidSignature:
return False
else:
return True

def write_private_key_file(self, filename, password=None):
self._write_private_key_file('DSA', filename, self._encode_key(), password)
key = dsa.DSAPrivateNumbers(
x=self.x,
public_numbers=dsa.DSAPublicNumbers(
y=self.y,
parameter_numbers=dsa.DSAParameterNumbers(
p=self.p,
q=self.q,
g=self.g
)
)
).private_key(backend=default_backend())

self._write_private_key_file(
filename,
key,
serialization.PrivateFormat.TraditionalOpenSSL,
password=password
)

def write_private_key(self, file_obj, password=None):
self._write_private_key('DSA', file_obj, self._encode_key(), password)
key = dsa.DSAPrivateNumbers(
x=self.x,
public_numbers=dsa.DSAPublicNumbers(
y=self.y,
parameter_numbers=dsa.DSAParameterNumbers(
p=self.p,
q=self.q,
g=self.g
)
)
).private_key(backend=default_backend())

self._write_private_key(
file_obj,
key,
serialization.PrivateFormat.TraditionalOpenSSL,
password=password
)

@staticmethod
def generate(bits=1024, progress_func=None):
Expand All @@ -161,14 +207,19 @@ def generate(bits=1024, progress_func=None):
generate a new host key or authentication key.

:param int bits: number of bits the generated key should be.
:param function progress_func:
an optional function to call at key points in key generation (used
by ``pyCrypto.PublicKey``).
:param function progress_func: Unused
:return: new `.DSSKey` private key
"""
dsa = DSA.generate(bits, os.urandom, progress_func)
key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y))
key.x = dsa.x
numbers = dsa.generate_private_key(
bits, backend=default_backend()
).private_numbers()
key = DSSKey(vals=(
numbers.public_numbers.parameter_numbers.p,
numbers.public_numbers.parameter_numbers.q,
numbers.public_numbers.parameter_numbers.g,
numbers.public_numbers.y
))
key.x = numbers.x
return key

### internals...
Expand Down
113 changes: 72 additions & 41 deletions paramiko/ecdsakey.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,23 @@
"""

import binascii
from hashlib import sha256

from ecdsa import SigningKey, VerifyingKey, der, curves
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import (
decode_rfc6979_signature, encode_rfc6979_signature
)

from paramiko.common import four_byte, one_byte
from paramiko.common import four_byte
from paramiko.message import Message
from paramiko.pkey import PKey
from paramiko.py3compat import byte_chr, u
from paramiko.ssh_exception import SSHException
from paramiko.util import deflate_long, inflate_long


class ECDSAKey (PKey):
class ECDSAKey(PKey):
"""
Representation of an ECDSA key which can be used to sign and verify SSH2
data.
Expand Down Expand Up @@ -65,9 +70,13 @@ def __init__(self, msg=None, data=None, filename=None, password=None,
if pointinfo[0:1] != four_byte:
raise SSHException('Point compression is being used: %s' %
binascii.hexlify(pointinfo))
self.verifying_key = VerifyingKey.from_string(pointinfo[1:],
curve=curves.NIST256p,
validate_point=validate_point)
curve = ec.SECP256R1()
numbers = ec.EllipticCurvePublicNumbers(
x=inflate_long(pointinfo[1:1 + curve.key_size // 8], always_positive=True),
y=inflate_long(pointinfo[1 + curve.key_size // 8:], always_positive=True),
curve=curve
)
self.verifying_key = numbers.public_key(backend=default_backend())
self.size = 256

def asbytes(self):
Expand All @@ -76,8 +85,15 @@ def asbytes(self):
m.add_string('ecdsa-sha2-nistp256')
m.add_string('nistp256')

point_str = four_byte + key.to_string()
numbers = key.public_numbers()

x_bytes = deflate_long(numbers.x, add_sign_padding=False)
x_bytes = b'\x00' * (len(x_bytes) - key.curve.key_size // 8) + x_bytes

y_bytes = deflate_long(numbers.y, add_sign_padding=False)
y_bytes = b'\x00' * (len(y_bytes) - key.curve.key_size // 8) + y_bytes

point_str = four_byte + x_bytes + y_bytes
m.add_string(point_str)
return m.asbytes()

Expand All @@ -86,8 +102,8 @@ def __str__(self):

def __hash__(self):
h = hash(self.get_name())
h = h * 37 + hash(self.verifying_key.pubkey.point.x())
h = h * 37 + hash(self.verifying_key.pubkey.point.y())
h = h * 37 + hash(self.verifying_key.public_numbers().x)
h = h * 37 + hash(self.verifying_key.public_numbers().y)
return hash(h)

def get_name(self):
Expand All @@ -100,44 +116,61 @@ def can_sign(self):
return self.signing_key is not None

def sign_ssh_data(self, data):
sig = self.signing_key.sign_deterministic(
data, sigencode=self._sigencode, hashfunc=sha256)
signer = self.signing_key.signer(ec.ECDSA(hashes.SHA256()))
signer.update(data)
sig = signer.finalize()
r, s = decode_rfc6979_signature(sig)

m = Message()
m.add_string('ecdsa-sha2-nistp256')
m.add_string(sig)
m.add_string(self._sigencode(r, s))
return m

def verify_ssh_sig(self, data, msg):
if msg.get_text() != 'ecdsa-sha2-nistp256':
return False
sig = msg.get_binary()

# verify the signature by SHA'ing the data and encrypting it
# using the public key.
hash_obj = sha256(data).digest()
return self.verifying_key.verify_digest(sig, hash_obj,
sigdecode=self._sigdecode)
sigR, sigS = self._sigdecode(sig)
signature = encode_rfc6979_signature(sigR, sigS)

verifier = self.verifying_key.verifier(
signature, ec.ECDSA(hashes.SHA256())
)
verifier.update(data)
try:
verifier.verify()
except InvalidSignature:
return False
else:
return True

def write_private_key_file(self, filename, password=None):
key = self.signing_key or self.verifying_key
self._write_private_key_file('EC', filename, key.to_der(), password)
self._write_private_key_file(
filename,
self.signing_key,
serialization.PrivateFormat.TraditionalOpenSSL,
password=password
)

def write_private_key(self, file_obj, password=None):
key = self.signing_key or self.verifying_key
self._write_private_key('EC', file_obj, key.to_der(), password)
self._write_private_key(
file_obj,
self.signing_key,
serialization.PrivateFormat.TraditionalOpenSSL,
password=password
)

@staticmethod
def generate(curve=curves.NIST256p, progress_func=None):
def generate(curve=ec.SECP256R1(), progress_func=None):
"""
Generate a new private ECDSA key. This factory function can be used to
generate a new host key or authentication key.

:param function progress_func: Not used for this type of key.
:returns: A new private key (`.ECDSAKey`) object
"""
signing_key = SigningKey.generate(curve)
key = ECDSAKey(vals=(signing_key, signing_key.get_verifying_key()))
return key
private_key = ec.generate_private_key(curve, backend=default_backend())
return ECDSAKey(vals=(private_key, private_key.public_key()))

### internals...

Expand All @@ -149,27 +182,25 @@ def _from_private_key(self, file_obj, password):
data = self._read_private_key('EC', file_obj, password)
self._decode_key(data)

ALLOWED_PADDINGS = [one_byte, byte_chr(2) * 2, byte_chr(3) * 3, byte_chr(4) * 4,
byte_chr(5) * 5, byte_chr(6) * 6, byte_chr(7) * 7]

def _decode_key(self, data):
s, padding = der.remove_sequence(data)
if padding:
if padding not in self.ALLOWED_PADDINGS:
raise ValueError("weird padding: %s" % u(binascii.hexlify(data)))
data = data[:-len(padding)]
key = SigningKey.from_der(data)
try:
key = serialization.load_der_private_key(
data, password=None, backend=default_backend()
)
except ValueError as e:
raise SSHException(str(e))

self.signing_key = key
self.verifying_key = key.get_verifying_key()
self.size = 256
self.verifying_key = key.public_key()
self.size = key.curve.key_size

def _sigencode(self, r, s, order):
def _sigencode(self, r, s):
msg = Message()
msg.add_mpint(r)
msg.add_mpint(s)
return msg.asbytes()

def _sigdecode(self, sig, order):
def _sigdecode(self, sig):
msg = Message(sig)
r = msg.get_mpint()
s = msg.get_mpint()
Expand Down
Loading