From 66cfa97cce92b1d60383d178887b18dddb999fc1 Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Wed, 30 Oct 2013 16:19:30 -0700 Subject: Fix imports --- tests/test_packetizer.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'tests/test_packetizer.py') diff --git a/tests/test_packetizer.py b/tests/test_packetizer.py index 1f5bec05..c39fc455 100644 --- a/tests/test_packetizer.py +++ b/tests/test_packetizer.py @@ -21,10 +21,11 @@ Some unit tests for the ssh2 protocol in Transport. """ import unittest -from loop import LoopSocket +from tests.loop import LoopSocket from Crypto.Cipher import AES from Crypto.Hash import SHA, HMAC from paramiko import Message, Packetizer, util +from paramiko.py3compat import byte_chr class PacketizerTest (unittest.TestCase): -- cgit v1.2.3 From 0e4ce3762a5b25c5d3eb89335495d3bb9054e3e7 Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Wed, 30 Oct 2013 17:09:34 -0700 Subject: Fix message sending Create constants for byte messages, implement asbytes so many methods can take Message and key objects directly and split get_string into get_text and get_binary. Also, change int handling to use mpint with a flag whenever the int is greater than 32 bits. --- paramiko/agent.py | 24 ++++++---- paramiko/auth_handler.py | 68 ++++++++++++++-------------- paramiko/ber.py | 11 +++-- paramiko/channel.py | 48 ++++++++++---------- paramiko/dsskey.py | 19 ++++---- paramiko/ecdsakey.py | 29 ++++++------ paramiko/hostkeys.py | 2 +- paramiko/kex_gex.py | 22 +++++----- paramiko/kex_group1.py | 16 +++---- paramiko/message.py | 112 +++++++++++++++++++++++++++++++++-------------- paramiko/pkey.py | 22 ++++++---- paramiko/rsakey.py | 15 ++++--- paramiko/sftp.py | 5 ++- paramiko/sftp_client.py | 20 ++++----- paramiko/sftp_file.py | 4 +- paramiko/sftp_server.py | 52 +++++++++++----------- paramiko/transport.py | 72 +++++++++++++++--------------- tests/test_auth.py | 2 +- tests/test_client.py | 10 ++--- tests/test_hostkeys.py | 16 +++---- tests/test_kex.py | 26 ++++++----- tests/test_message.py | 60 ++++++++++++++----------- tests/test_packetizer.py | 2 +- tests/test_pkey.py | 24 +++++----- tests/test_sftp.py | 3 +- tests/test_sftp_big.py | 2 +- tests/test_transport.py | 8 ++-- 27 files changed, 388 insertions(+), 306 deletions(-) (limited to 'tests/test_packetizer.py') diff --git a/paramiko/agent.py b/paramiko/agent.py index f50a7c00..a6a177db 100644 --- a/paramiko/agent.py +++ b/paramiko/agent.py @@ -37,8 +37,11 @@ from paramiko.channel import Channel from paramiko.common import * from paramiko.util import retry_on_signal -SSH2_AGENTC_REQUEST_IDENTITIES, SSH2_AGENT_IDENTITIES_ANSWER, \ - SSH2_AGENTC_SIGN_REQUEST, SSH2_AGENT_SIGN_RESPONSE = range(11, 15) +cSSH2_AGENTC_REQUEST_IDENTITIES = byte_chr(11) +SSH2_AGENT_IDENTITIES_ANSWER = 12 +cSSH2_AGENTC_SIGN_REQUEST = byte_chr(13) +SSH2_AGENT_SIGN_RESPONSE = 14 + class AgentSSH(object): """ @@ -68,12 +71,12 @@ class AgentSSH(object): def _connect(self, conn): self._conn = conn - ptype, result = self._send_message(chr(SSH2_AGENTC_REQUEST_IDENTITIES)) + ptype, result = self._send_message(cSSH2_AGENTC_REQUEST_IDENTITIES) if ptype != SSH2_AGENT_IDENTITIES_ANSWER: raise SSHException('could not get keys from ssh-agent') keys = [] for i in range(result.get_int()): - keys.append(AgentKey(self, result.get_string())) + keys.append(AgentKey(self, result.get_binary())) result.get_string() self._keys = tuple(keys) @@ -83,7 +86,7 @@ class AgentSSH(object): self._keys = () def _send_message(self, msg): - msg = str(msg) + msg = asbytes(msg) self._conn.send(struct.pack('>I', len(msg)) + msg) l = self._read_all(4) msg = Message(self._read_all(struct.unpack('>I', l)[0])) @@ -360,21 +363,24 @@ class AgentKey(PKey): def __init__(self, agent, blob): self.agent = agent self.blob = blob - self.name = Message(blob).get_string() + self.name = Message(blob).get_text() - def __str__(self): + def asbytes(self): return self.blob + def __str__(self): + return self.asbytes() + def get_name(self): return self.name def sign_ssh_data(self, rng, data): msg = Message() - msg.add_byte(chr(SSH2_AGENTC_SIGN_REQUEST)) + msg.add_byte(cSSH2_AGENTC_SIGN_REQUEST) msg.add_string(self.blob) msg.add_string(data) msg.add_int(0) ptype, result = self.agent._send_message(msg) if ptype != SSH2_AGENT_SIGN_RESPONSE: raise SSHException('key cannot be used for signing') - return result.get_string() + return result.get_binary() diff --git a/paramiko/auth_handler.py b/paramiko/auth_handler.py index de0b2057..2a65355e 100644 --- a/paramiko/auth_handler.py +++ b/paramiko/auth_handler.py @@ -119,13 +119,13 @@ class AuthHandler (object): def _request_auth(self): m = Message() - m.add_byte(chr(MSG_SERVICE_REQUEST)) + m.add_byte(cMSG_SERVICE_REQUEST) m.add_string('ssh-userauth') self.transport._send_message(m) def _disconnect_service_not_available(self): m = Message() - m.add_byte(chr(MSG_DISCONNECT)) + m.add_byte(cMSG_DISCONNECT) m.add_int(DISCONNECT_SERVICE_NOT_AVAILABLE) m.add_string('Service not available') m.add_string('en') @@ -134,7 +134,7 @@ class AuthHandler (object): def _disconnect_no_more_auth(self): m = Message() - m.add_byte(chr(MSG_DISCONNECT)) + m.add_byte(cMSG_DISCONNECT) m.add_int(DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) m.add_string('No more auth methods available') m.add_string('en') @@ -144,14 +144,14 @@ class AuthHandler (object): def _get_session_blob(self, key, service, username): m = Message() m.add_string(self.transport.session_id) - m.add_byte(chr(MSG_USERAUTH_REQUEST)) + m.add_byte(cMSG_USERAUTH_REQUEST) m.add_string(username) m.add_string(service) m.add_string('publickey') m.add_boolean(1) m.add_string(key.get_name()) - m.add_string(str(key)) - return str(m) + m.add_string(key) + return m.asbytes() def wait_for_response(self, event): while True: @@ -175,11 +175,11 @@ class AuthHandler (object): return [] def _parse_service_request(self, m): - service = m.get_string() + service = m.get_text() if self.transport.server_mode and (service == 'ssh-userauth'): # accepted m = Message() - m.add_byte(chr(MSG_SERVICE_ACCEPT)) + m.add_byte(cMSG_SERVICE_ACCEPT) m.add_string(service) self.transport._send_message(m) return @@ -187,27 +187,25 @@ class AuthHandler (object): self._disconnect_service_not_available() def _parse_service_accept(self, m): - service = m.get_string() + service = m.get_text() if service == 'ssh-userauth': self.transport._log(DEBUG, 'userauth is OK') m = Message() - m.add_byte(chr(MSG_USERAUTH_REQUEST)) + m.add_byte(cMSG_USERAUTH_REQUEST) m.add_string(self.username) m.add_string('ssh-connection') m.add_string(self.auth_method) if self.auth_method == 'password': m.add_boolean(False) - password = self.password - if isinstance(password, unicode): - password = password.encode('UTF-8') + password = bytestring(self.password) m.add_string(password) elif self.auth_method == 'publickey': m.add_boolean(True) m.add_string(self.private_key.get_name()) - m.add_string(str(self.private_key)) + m.add_string(self.private_key) blob = self._get_session_blob(self.private_key, 'ssh-connection', self.username) sig = self.private_key.sign_ssh_data(self.transport.rng, blob) - m.add_string(str(sig)) + m.add_string(sig) elif self.auth_method == 'keyboard-interactive': m.add_string('') m.add_string(self.submethods) @@ -224,11 +222,11 @@ class AuthHandler (object): m = Message() if result == AUTH_SUCCESSFUL: self.transport._log(INFO, 'Auth granted (%s).' % method) - m.add_byte(chr(MSG_USERAUTH_SUCCESS)) + m.add_byte(cMSG_USERAUTH_SUCCESS) self.authenticated = True else: self.transport._log(INFO, 'Auth rejected (%s).' % method) - m.add_byte(chr(MSG_USERAUTH_FAILURE)) + m.add_byte(cMSG_USERAUTH_FAILURE) m.add_string(self.transport.server_object.get_allowed_auths(username)) if result == AUTH_PARTIALLY_SUCCESSFUL: m.add_boolean(1) @@ -244,7 +242,7 @@ class AuthHandler (object): def _interactive_query(self, q): # make interactive query instead of response m = Message() - m.add_byte(chr(MSG_USERAUTH_INFO_REQUEST)) + m.add_byte(cMSG_USERAUTH_INFO_REQUEST) m.add_string(q.name) m.add_string(q.instructions) m.add_string('') @@ -258,7 +256,7 @@ class AuthHandler (object): if not self.transport.server_mode: # er, uh... what? m = Message() - m.add_byte(chr(MSG_USERAUTH_FAILURE)) + m.add_byte(cMSG_USERAUTH_FAILURE) m.add_string('none') m.add_boolean(0) self.transport._send_message(m) @@ -266,9 +264,9 @@ class AuthHandler (object): if self.authenticated: # ignore return - username = m.get_string() - service = m.get_string() - method = m.get_string() + username = m.get_text() + service = m.get_text() + method = m.get_text() self.transport._log(DEBUG, 'Auth request (type=%s) service=%s, username=%s' % (method, service, username)) if service != 'ssh-connection': self._disconnect_service_not_available() @@ -283,7 +281,7 @@ class AuthHandler (object): result = self.transport.server_object.check_auth_none(username) elif method == 'password': changereq = m.get_boolean() - password = m.get_string() + password = m.get_binary() try: password = password.decode('UTF-8') except UnicodeError: @@ -294,7 +292,7 @@ class AuthHandler (object): # always treated as failure, since we don't support changing passwords, but collect # the list of valid auth types from the callback anyway self.transport._log(DEBUG, 'Auth request to change passwords (rejected)') - newpassword = m.get_string() + newpassword = m.get_binary() try: newpassword = newpassword.decode('UTF-8', 'replace') except UnicodeError: @@ -304,8 +302,8 @@ class AuthHandler (object): result = self.transport.server_object.check_auth_password(username, password) elif method == 'publickey': sig_attached = m.get_boolean() - keytype = m.get_string() - keyblob = m.get_string() + keytype = m.get_text() + keyblob = m.get_binary() try: key = self.transport._key_info[keytype](Message(keyblob)) except SSHException: @@ -326,12 +324,12 @@ class AuthHandler (object): # client wants to know if this key is acceptable, before it # signs anything... send special "ok" message m = Message() - m.add_byte(chr(MSG_USERAUTH_PK_OK)) + m.add_byte(cMSG_USERAUTH_PK_OK) m.add_string(keytype) m.add_string(keyblob) self.transport._send_message(m) return - sig = Message(m.get_string()) + sig = Message(m.get_binary()) blob = self._get_session_blob(key, service, username) if not key.verify_ssh_sig(blob, sig): self.transport._log(INFO, 'Auth rejected: invalid signature') @@ -383,17 +381,17 @@ class AuthHandler (object): def _parse_userauth_info_request(self, m): if self.auth_method != 'keyboard-interactive': raise SSHException('Illegal info request from server') - title = m.get_string() - instructions = m.get_string() - m.get_string() # lang + title = m.get_text() + instructions = m.get_text() + m.get_binary() # lang prompts = m.get_int() prompt_list = [] for i in range(prompts): - prompt_list.append((m.get_string(), m.get_boolean())) + prompt_list.append((m.get_text(), m.get_boolean())) response_list = self.interactive_handler(title, instructions, prompt_list) m = Message() - m.add_byte(chr(MSG_USERAUTH_INFO_RESPONSE)) + m.add_byte(cMSG_USERAUTH_INFO_RESPONSE) m.add_int(len(response_list)) for r in response_list: m.add_string(r) @@ -405,14 +403,14 @@ class AuthHandler (object): n = m.get_int() responses = [] for i in range(n): - responses.append(m.get_string()) + responses.append(m.get_text()) result = self.transport.server_object.check_auth_interactive_response(responses) if isinstance(type(result), InteractiveQuery): # make interactive query instead of response self._interactive_query(result) return self._send_auth_result(self.auth_username, 'keyboard-interactive', result) - + _handler_table = { MSG_SERVICE_REQUEST: _parse_service_request, diff --git a/paramiko/ber.py b/paramiko/ber.py index f3b4b37e..45372fc4 100644 --- a/paramiko/ber.py +++ b/paramiko/ber.py @@ -30,13 +30,16 @@ class BER(object): Robey's tiny little attempt at a BER decoder. """ - def __init__(self, content=''): - self.content = content + def __init__(self, content=bytes()): + self.content = b(content) self.idx = 0 - def __str__(self): + def asbytes(self): return self.content + def __str__(self): + return self.asbytes() + def __repr__(self): return 'BER(\'' + repr(self.content) + '\')' @@ -126,5 +129,5 @@ class BER(object): b = BER() for item in data: b.encode(item) - return str(b) + return b.asbytes() encode_sequence = staticmethod(encode_sequence) diff --git a/paramiko/channel.py b/paramiko/channel.py index d3517680..422986dd 100644 --- a/paramiko/channel.py +++ b/paramiko/channel.py @@ -148,7 +148,7 @@ class Channel (object): if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException('Channel is not open') m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('pty-req') m.add_boolean(True) @@ -181,7 +181,7 @@ class Channel (object): if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException('Channel is not open') m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('shell') m.add_boolean(1) @@ -208,7 +208,7 @@ class Channel (object): if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException('Channel is not open') m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('exec') m.add_boolean(True) @@ -235,7 +235,7 @@ class Channel (object): if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException('Channel is not open') m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('subsystem') m.add_boolean(True) @@ -264,7 +264,7 @@ class Channel (object): if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException('Channel is not open') m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('window-change') m.add_boolean(False) @@ -319,7 +319,7 @@ class Channel (object): # in many cases, the channel will not still be open here. # that's fine. m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('exit-status') m.add_boolean(False) @@ -375,7 +375,7 @@ class Channel (object): auth_cookie = binascii.hexlify(self.transport.rng.read(16)) m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('x11-req') m.add_boolean(True) @@ -406,7 +406,7 @@ class Channel (object): raise SSHException('Channel is not open') m = Message() - m.add_byte(chr(MSG_CHANNEL_REQUEST)) + m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('auth-agent-req@openssh.com') m.add_boolean(False) @@ -491,7 +491,7 @@ class Channel (object): self._feed(data) return old - + ### socket API @@ -622,7 +622,7 @@ class Channel (object): # no need to hold the channel lock when sending this if ack > 0: m = Message() - m.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST)) + m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST) m.add_int(self.remote_chanid) m.add_int(ack) self.transport._send_user_message(m) @@ -672,7 +672,7 @@ class Channel (object): # no need to hold the channel lock when sending this if ack > 0: m = Message() - m.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST)) + m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST) m.add_int(self.remote_chanid) m.add_int(ack) self.transport._send_user_message(m) @@ -724,7 +724,7 @@ class Channel (object): # eof or similar return 0 m = Message() - m.add_byte(chr(MSG_CHANNEL_DATA)) + m.add_byte(cMSG_CHANNEL_DATA) m.add_int(self.remote_chanid) m.add_string(s[:size]) finally: @@ -761,7 +761,7 @@ class Channel (object): # eof or similar return 0 m = Message() - m.add_byte(chr(MSG_CHANNEL_EXTENDED_DATA)) + m.add_byte(cMSG_CHANNEL_EXTENDED_DATA) m.add_int(self.remote_chanid) m.add_int(1) m.add_string(s[:size]) @@ -973,12 +973,12 @@ class Channel (object): # passed from _feed_extended s = m else: - s = m.get_string() + s = m.get_binary() self.in_buffer.feed(s) def _feed_extended(self, m): code = m.get_int() - s = m.get_string() + s = m.get_text() if code != 1: self._log(ERROR, 'unknown extended_data type %d; discarding' % code) return @@ -999,7 +999,7 @@ class Channel (object): self.lock.release() def _handle_request(self, m): - key = m.get_string() + key = m.get_text() want_reply = m.get_boolean() server = self.transport.server_object ok = False @@ -1035,13 +1035,13 @@ class Channel (object): else: ok = server.check_channel_env_request(self, name, value) elif key == 'exec': - cmd = m.get_string() + cmd = m.get_text() if server is None: ok = False else: ok = server.check_channel_exec_request(self, cmd) elif key == 'subsystem': - name = m.get_string() + name = m.get_text() if server is None: ok = False else: @@ -1058,8 +1058,8 @@ class Channel (object): pixelheight) elif key == 'x11-req': single_connection = m.get_boolean() - auth_proto = m.get_string() - auth_cookie = m.get_string() + auth_proto = m.get_text() + auth_cookie = m.get_text() screen_number = m.get_int() if server is None: ok = False @@ -1077,9 +1077,9 @@ class Channel (object): if want_reply: m = Message() if ok: - m.add_byte(chr(MSG_CHANNEL_SUCCESS)) + m.add_byte(cMSG_CHANNEL_SUCCESS) else: - m.add_byte(chr(MSG_CHANNEL_FAILURE)) + m.add_byte(cMSG_CHANNEL_FAILURE) m.add_int(self.remote_chanid) self.transport._send_user_message(m) @@ -1145,7 +1145,7 @@ class Channel (object): if self.eof_sent: return None m = Message() - m.add_byte(chr(MSG_CHANNEL_EOF)) + m.add_byte(cMSG_CHANNEL_EOF) m.add_int(self.remote_chanid) self.eof_sent = True self._log(DEBUG, 'EOF sent (%s)', self._name) @@ -1157,7 +1157,7 @@ class Channel (object): return None, None m1 = self._send_eof() m2 = Message() - m2.add_byte(chr(MSG_CHANNEL_CLOSE)) + m2.add_byte(cMSG_CHANNEL_CLOSE) m2.add_int(self.remote_chanid) self._set_closed() # can't unlink from the Transport yet -- the remote side may still diff --git a/paramiko/dsskey.py b/paramiko/dsskey.py index ff744888..715f9f60 100644 --- a/paramiko/dsskey.py +++ b/paramiko/dsskey.py @@ -56,7 +56,7 @@ class DSSKey (PKey): else: if msg is None: raise SSHException('Key object may not be empty') - if msg.get_string() != 'ssh-dss': + if msg.get_text() != 'ssh-dss': raise SSHException('Invalid key') self.p = msg.get_mpint() self.q = msg.get_mpint() @@ -64,14 +64,17 @@ class DSSKey (PKey): self.y = msg.get_mpint() self.size = util.bit_length(self.p) - def __str__(self): + def asbytes(self): m = Message() m.add_string('ssh-dss') m.add_mpint(self.p) m.add_mpint(self.q) m.add_mpint(self.g) m.add_mpint(self.y) - return str(m) + return m.asbytes() + + def __str__(self): + return self.asbytes() def __hash__(self): h = hash(self.get_name()) @@ -114,14 +117,14 @@ class DSSKey (PKey): return m def verify_ssh_sig(self, data, msg): - if len(str(msg)) == 40: + if len(msg.asbytes()) == 40: # spies.com bug: signature has no header - sig = str(msg) + sig = msg.asbytes() else: - kind = msg.get_string() + kind = msg.get_text() if kind != 'ssh-dss': return 0 - sig = msg.get_string() + sig = msg.get_binary() # pull out (r, s) which are NOT encoded as mpints sigR = util.inflate_long(sig[:20], 1) @@ -140,7 +143,7 @@ class DSSKey (PKey): b.encode(keylist) except BERException: raise SSHException('Unable to create ber encoding of key') - return str(b) + return b.asbytes() def write_private_key_file(self, filename, password=None): self._write_private_key_file('DSA', filename, self._encode_key(), password) diff --git a/paramiko/ecdsakey.py b/paramiko/ecdsakey.py index ac840ab7..c3d2a736 100644 --- a/paramiko/ecdsakey.py +++ b/paramiko/ecdsakey.py @@ -56,30 +56,33 @@ class ECDSAKey (PKey): else: if msg is None: raise SSHException('Key object may not be empty') - if msg.get_string() != 'ecdsa-sha2-nistp256': + if msg.get_text() != 'ecdsa-sha2-nistp256': raise SSHException('Invalid key') - curvename = msg.get_string() + curvename = msg.get_text() if curvename != 'nistp256': raise SSHException("Can't handle curve of type %s" % curvename) - pointinfo = msg.get_string() - if pointinfo[0] != "\x04": - raise SSHException('Point compression is being used: %s'% + pointinfo = msg.get_binary() + if pointinfo[0] != four_byte: + raise SSHException('Point compression is being used: %s' % binascii.hexlify(pointinfo)) self.verifying_key = VerifyingKey.from_string(pointinfo[1:], - curve=curves.NIST256p) + curve=curves.NIST256p) self.size = 256 - def __str__(self): + def asbytes(self): key = self.verifying_key m = Message() m.add_string('ecdsa-sha2-nistp256') m.add_string('nistp256') - point_str = "\x04" + key.to_string() + point_str = four_byte + key.to_string() m.add_string(point_str) - return str(m) + return m.asbytes() + + def __str__(self): + return self.asbytes() def __hash__(self): h = hash(self.get_name()) @@ -106,9 +109,9 @@ class ECDSAKey (PKey): return m def verify_ssh_sig(self, data, msg): - if msg.get_string() != 'ecdsa-sha2-nistp256': + if msg.get_text() != 'ecdsa-sha2-nistp256': return False - sig = msg.get_string() + sig = msg.get_binary() # verify the signature by SHA'ing the data and encrypting it # using the public key. @@ -161,7 +164,7 @@ class ECDSAKey (PKey): s, padding = der.remove_sequence(data) if padding: if padding not in self.ALLOWED_PADDINGS: - raise ValueError, "weird padding: %s" % (binascii.hexlify(empty)) + raise ValueError("weird padding: %s" % (binascii.hexlify(empty))) data = data[:-len(padding)] key = SigningKey.from_der(data) self.signing_key = key @@ -172,7 +175,7 @@ class ECDSAKey (PKey): msg = Message() msg.add_mpint(r) msg.add_mpint(s) - return str(msg) + return msg.asbytes() def _sigdecode(self, sig, order): msg = Message(sig) diff --git a/paramiko/hostkeys.py b/paramiko/hostkeys.py index f548263c..17ee8084 100644 --- a/paramiko/hostkeys.py +++ b/paramiko/hostkeys.py @@ -289,7 +289,7 @@ class HostKeys (MutableMapping): host_key = k.get(key.get_name(), None) if host_key is None: return False - return str(host_key) == str(key) + return host_key.asbytes() == key.asbytes() def clear(self): """ diff --git a/paramiko/kex_gex.py b/paramiko/kex_gex.py index 669bd34e..d2ef15ca 100644 --- a/paramiko/kex_gex.py +++ b/paramiko/kex_gex.py @@ -33,6 +33,8 @@ from paramiko.ssh_exception import SSHException _MSG_KEXDH_GEX_REQUEST_OLD, _MSG_KEXDH_GEX_GROUP, _MSG_KEXDH_GEX_INIT, \ _MSG_KEXDH_GEX_REPLY, _MSG_KEXDH_GEX_REQUEST = range(30, 35) +c_MSG_KEXDH_GEX_REQUEST_OLD, c_MSG_KEXDH_GEX_GROUP, c_MSG_KEXDH_GEX_INIT, \ + c_MSG_KEXDH_GEX_REPLY, c_MSG_KEXDH_GEX_REQUEST = [byte_chr(c) for c in range(30, 35)] class KexGex (object): @@ -62,11 +64,11 @@ class KexGex (object): m = Message() if _test_old_style: # only used for unit tests: we shouldn't ever send this - m.add_byte(chr(_MSG_KEXDH_GEX_REQUEST_OLD)) + m.add_byte(c_MSG_KEXDH_GEX_REQUEST_OLD) m.add_int(self.preferred_bits) self.old_style = True else: - m.add_byte(chr(_MSG_KEXDH_GEX_REQUEST)) + m.add_byte(c_MSG_KEXDH_GEX_REQUEST) m.add_int(self.min_bits) m.add_int(self.preferred_bits) m.add_int(self.max_bits) @@ -135,7 +137,7 @@ class KexGex (object): self.transport._log(DEBUG, 'Picking p (%d <= %d <= %d bits)' % (minbits, preferredbits, maxbits)) self.g, self.p = pack.get_modulus(minbits, preferredbits, maxbits) m = Message() - m.add_byte(chr(_MSG_KEXDH_GEX_GROUP)) + m.add_byte(c_MSG_KEXDH_GEX_GROUP) m.add_mpint(self.p) m.add_mpint(self.g) self.transport._send_message(m) @@ -156,7 +158,7 @@ class KexGex (object): self.transport._log(DEBUG, 'Picking p (~ %d bits)' % (self.preferred_bits,)) self.g, self.p = pack.get_modulus(self.min_bits, self.preferred_bits, self.max_bits) m = Message() - m.add_byte(chr(_MSG_KEXDH_GEX_GROUP)) + m.add_byte(c_MSG_KEXDH_GEX_GROUP) m.add_mpint(self.p) m.add_mpint(self.g) self.transport._send_message(m) @@ -175,7 +177,7 @@ class KexGex (object): # now compute e = g^x mod p self.e = pow(self.g, self.x, self.p) m = Message() - m.add_byte(chr(_MSG_KEXDH_GEX_INIT)) + m.add_byte(c_MSG_KEXDH_GEX_INIT) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet(_MSG_KEXDH_GEX_REPLY) @@ -187,7 +189,7 @@ class KexGex (object): self._generate_x() self.f = pow(self.g, self.x, self.p) K = pow(self.e, self.x, self.p) - key = str(self.transport.get_server_key()) + key = self.transport.get_server_key().asbytes() # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K) hm = Message() hm.add(self.transport.remote_version, self.transport.local_version, @@ -203,16 +205,16 @@ class KexGex (object): hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) - H = SHA.new(str(hm)).digest() + H = SHA.new(hm.asbytes()).digest() self.transport._set_K_H(K, H) # sign it sig = self.transport.get_server_key().sign_ssh_data(self.transport.rng, H) # send reply m = Message() - m.add_byte(chr(_MSG_KEXDH_GEX_REPLY)) + m.add_byte(c_MSG_KEXDH_GEX_REPLY) m.add_string(key) m.add_mpint(self.f) - m.add_string(str(sig)) + m.add_string(sig) self.transport._send_message(m) self.transport._activate_outbound() @@ -238,6 +240,6 @@ class KexGex (object): hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) - self.transport._set_K_H(K, SHA.new(str(hm)).digest()) + self.transport._set_K_H(K, SHA.new(hm.asbytes()).digest()) self.transport._verify_key(host_key, sig) self.transport._activate_outbound() diff --git a/paramiko/kex_group1.py b/paramiko/kex_group1.py index 6e89b6dc..83fb87de 100644 --- a/paramiko/kex_group1.py +++ b/paramiko/kex_group1.py @@ -56,7 +56,7 @@ class KexGroup1(object): # compute e = g^x mod p (where g=2), and send it self.e = pow(G, self.x, P) m = Message() - m.add_byte(chr(_MSG_KEXDH_INIT)) + m.add_byte(c_MSG_KEXDH_INIT) m.add_mpint(self.e) self.transport._send_message(m) self.transport._expect_packet(_MSG_KEXDH_REPLY) @@ -67,7 +67,7 @@ class KexGroup1(object): elif not self.transport.server_mode and (ptype == _MSG_KEXDH_REPLY): return self._parse_kexdh_reply(m) raise SSHException('KexGroup1 asked to handle packet type %d' % ptype) - + ### internals... @@ -92,7 +92,7 @@ class KexGroup1(object): self.f = m.get_mpint() if (self.f < 1) or (self.f > P - 1): raise SSHException('Server kex "f" is out of range') - sig = m.get_string() + sig = m.get_binary() K = pow(self.f, self.x, P) # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() @@ -102,7 +102,7 @@ class KexGroup1(object): hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) - self.transport._set_K_H(K, SHA.new(str(hm)).digest()) + self.transport._set_K_H(K, SHA.new(hm.asbytes()).digest()) self.transport._verify_key(host_key, sig) self.transport._activate_outbound() @@ -112,7 +112,7 @@ class KexGroup1(object): if (self.e < 1) or (self.e > P - 1): raise SSHException('Client kex "e" is out of range') K = pow(self.e, self.x, P) - key = str(self.transport.get_server_key()) + key = self.transport.get_server_key().asbytes() # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add(self.transport.remote_version, self.transport.local_version, @@ -121,15 +121,15 @@ class KexGroup1(object): hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) - H = SHA.new(str(hm)).digest() + H = SHA.new(hm.asbytes()).digest() self.transport._set_K_H(K, H) # sign it sig = self.transport.get_server_key().sign_ssh_data(self.transport.rng, H) # send reply m = Message() - m.add_byte(chr(_MSG_KEXDH_REPLY)) + m.add_byte(c_MSG_KEXDH_REPLY) m.add_string(key) m.add_mpint(self.f) - m.add_string(str(sig)) + m.add_string(sig) self.transport._send_message(m) self.transport._activate_outbound() diff --git a/paramiko/message.py b/paramiko/message.py index d579a167..8e81e69b 100644 --- a/paramiko/message.py +++ b/paramiko/message.py @@ -37,6 +37,8 @@ class Message (object): paramiko doesn't support yet. """ + big_int = long(0xff000000) + def __init__(self, content=None): """ Create a new SSH2 Message. @@ -46,18 +48,12 @@ class Message (object): @type content: string """ if content != None: - self.packet = cStringIO.StringIO(content) + self.packet = BytesIO(content) else: - self.packet = cStringIO.StringIO() + self.packet = BytesIO() def __str__(self): - """ - Return the byte stream content of this Message, as a string. - - @return: the contents of this Message. - @rtype: string - """ - return self.packet.getvalue() + return self.asbytes() def __repr__(self): """ @@ -67,6 +63,15 @@ class Message (object): """ return 'paramiko.Message(' + repr(self.packet.getvalue()) + ')' + def asbytes(self): + """ + Return the byte stream content of this Message, as bytes. + + @return: the contents of this Message. + @rtype: bytes + """ + return self.packet.getvalue() + def rewind(self): """ Rewind the message to the beginning as if no items had been parsed @@ -112,7 +117,7 @@ class Message (object): b = self.packet.read(n) max_pad_size = 1<<20 # Limit padding to 1 MB if len(b) < n and n < max_pad_size: - return b + '\x00' * (n - len(b)) + return b + zero_byte * (n - len(b)) return b def get_byte(self): @@ -134,12 +139,25 @@ class Message (object): @rtype: bool """ b = self.get_bytes(1) - return b != '\x00' + return b != zero_byte def get_int(self): """ Fetch an int from the stream. + @return: a 32-bit unsigned integer. + @rtype: int + """ + byte = self.get_bytes(1) + if byte == max_byte: + return util.inflate_long(self.get_binary()) + byte += self.get_bytes(3) + return struct.unpack('>I', byte)[0] + + def get_size(self): + """ + Fetch an int from the stream. + @return: a 32-bit unsigned integer. @rtype: int """ @@ -152,7 +170,7 @@ class Message (object): @return: a 64-bit unsigned integer. @rtype: long """ - return struct.unpack('>Q', self.get_bytes(8))[0] + return self.get_int() def get_mpint(self): """ @@ -161,7 +179,7 @@ class Message (object): @return: an arbitrary-length integer. @rtype: long """ - return util.inflate_long(self.get_string()) + return util.inflate_long(self.get_binary()) def get_string(self): """ @@ -172,7 +190,30 @@ class Message (object): @return: a string. @rtype: string """ - return self.get_bytes(self.get_int()) + return self.get_bytes(self.get_size()) + + def get_text(self): + """ + Fetch a string from the stream. This could be a byte string and may + contain unprintable characters. (It's not unheard of for a string to + contain another byte-stream Message.) + + @return: a string. + @rtype: string + """ + return u(self.get_bytes(self.get_size())) + #return self.get_bytes(self.get_size()) + + def get_binary(self): + """ + Fetch a string from the stream. This could be a byte string and may + contain unprintable characters. (It's not unheard of for a string to + contain another byte-stream Message.) + + @return: a string. + @rtype: string + """ + return self.get_bytes(self.get_size()) def get_list(self): """ @@ -182,7 +223,7 @@ class Message (object): @return: a list of strings. @rtype: list of strings """ - return self.get_string().split(',') + return self.get_text().split(',') def add_bytes(self, b): """ @@ -212,12 +253,12 @@ class Message (object): @type b: bool """ if b: - self.add_byte('\x01') + self.packet.write(one_byte) else: - self.add_byte('\x00') + self.packet.write(zero_byte) return self - def add_int(self, n): + def add_size(self, n): """ Add an integer to the stream. @@ -227,6 +268,20 @@ class Message (object): self.packet.write(struct.pack('>I', n)) return self + def add_int(self, n): + """ + Add an integer to the stream. + + @param n: integer to add + @type n: int + """ + if n >= Message.big_int: + self.packet.write(max_byte) + self.add_string(util.deflate_long(n)) + else: + self.packet.write(struct.pack('>I', n)) + return self + def add_int64(self, n): """ Add a 64-bit int to the stream. @@ -234,8 +289,7 @@ class Message (object): @param n: long int to add @type n: long """ - self.packet.write(struct.pack('>Q', n)) - return self + return self.add_int(n) def add_mpint(self, z): """ @@ -255,7 +309,8 @@ class Message (object): @param s: string to add @type s: str """ - self.add_int(len(s)) + s = asbytes(s) + self.add_size(len(s)) self.packet.write(s) return self @@ -272,21 +327,14 @@ class Message (object): return self def _add(self, i): - if type(i) is str: - return self.add_string(i) - elif type(i) is int: - return self.add_int(i) - elif type(i) is long: - if i > 0xffffffffL: - return self.add_mpint(i) - else: - return self.add_int(i) - elif type(i) is bool: + if type(i) is bool: return self.add_boolean(i) + elif isinstance(i, integer_types): + return self.add_int(i) elif type(i) is list: return self.add_list(i) else: - raise Exception('Unknown type') + return self.add_string(i) def add(self, *seq): """ diff --git a/paramiko/pkey.py b/paramiko/pkey.py index d61809f1..9c59dad4 100644 --- a/paramiko/pkey.py +++ b/paramiko/pkey.py @@ -63,7 +63,7 @@ class PKey (object): """ pass - def __str__(self): + def asbytes(self): """ Return a string of an SSH L{Message} made up of the public part(s) of this key. This string is suitable for passing to L{__init__} to @@ -72,7 +72,10 @@ class PKey (object): @return: string representation of an SSH key message. @rtype: str """ - return '' + return bytes() + + def __str__(self): + return self.asbytes() def __cmp__(self, other): """ @@ -90,7 +93,10 @@ class PKey (object): ho = hash(other) if hs != ho: return cmp(hs, ho) - return cmp(str(self), str(other)) + return cmp(self.asbytes(), other.asbytes()) + + def __eq__(self, other): + return hash(self) == hash(other) def get_name(self): """ @@ -131,7 +137,7 @@ class PKey (object): format. @rtype: str """ - return MD5.new(str(self)).digest() + return MD5.new(self.asbytes()).digest() def get_base64(self): """ @@ -142,7 +148,7 @@ class PKey (object): @return: a base64 string containing the public part of the key. @rtype: str """ - return base64.encodestring(str(self)).replace('\n', '') + return base64.encodestring(self.asbytes()).replace('\n', '') def sign_ssh_data(self, rng, data): """ @@ -156,7 +162,7 @@ class PKey (object): @return: an SSH signature message. @rtype: L{Message} """ - return '' + return bytes() def verify_ssh_sig(self, data, msg): """ @@ -303,7 +309,7 @@ class PKey (object): end += 1 # if we trudged to the end of the file, just try to cope. try: - data = base64.decodestring(''.join(lines[start:end])) + data = base64.decodestring(b(''.join(lines[start:end]))) except base64.binascii.Error: raise SSHException('base64 decoding error: ' + str(sys.exc_info()[1])) if 'proc-type' not in headers: @@ -356,7 +362,7 @@ class PKey (object): f.write('-----BEGIN %s PRIVATE KEY-----\n' % tag) if password is not None: # since we only support one cipher here, use it - cipher_name = self._CIPHER_TABLE.keys()[0] + cipher_name = list(self._CIPHER_TABLE.keys())[0] cipher = self._CIPHER_TABLE[cipher_name]['cipher'] keysize = self._CIPHER_TABLE[cipher_name]['keysize'] blocksize = self._CIPHER_TABLE[cipher_name]['blocksize'] diff --git a/paramiko/rsakey.py b/paramiko/rsakey.py index c7500f85..cb7b30b1 100644 --- a/paramiko/rsakey.py +++ b/paramiko/rsakey.py @@ -57,18 +57,21 @@ class RSAKey (PKey): else: if msg is None: raise SSHException('Key object may not be empty') - if msg.get_string() != 'ssh-rsa': + if msg.get_text() != 'ssh-rsa': raise SSHException('Invalid key') self.e = msg.get_mpint() self.n = msg.get_mpint() self.size = util.bit_length(self.n) - def __str__(self): + def asbytes(self): m = Message() m.add_string('ssh-rsa') m.add_mpint(self.e) m.add_mpint(self.n) - return str(m) + return m.asbytes() + + def __str__(self): + return self.asbytes() def __hash__(self): h = hash(self.get_name()) @@ -95,9 +98,9 @@ class RSAKey (PKey): return m def verify_ssh_sig(self, data, msg): - if msg.get_string() != 'ssh-rsa': + if msg.get_text() != 'ssh-rsa': return False - sig = util.inflate_long(msg.get_string(), True) + sig = util.inflate_long(msg.get_binary(), True) # verify the signature by SHA'ing the data and encrypting it using the # public key. some wackiness ensues where we "pkcs1imify" the 20-byte # hash into a string as long as the RSA key. @@ -116,7 +119,7 @@ class RSAKey (PKey): b.encode(keylist) except BERException: raise SSHException('Unable to create ber encoding of key') - return str(b) + return b.asbytes() def write_private_key_file(self, filename, password=None): self._write_private_key_file('RSA', filename, self._encode_key(), password) diff --git a/paramiko/sftp.py b/paramiko/sftp.py index a97c300f..0d1287a5 100644 --- a/paramiko/sftp.py +++ b/paramiko/sftp.py @@ -86,7 +86,7 @@ CMD_NAMES = { CMD_ATTRS: 'attrs', CMD_EXTENDED: 'extended', CMD_EXTENDED_REPLY: 'extended_reply' - } +} class SFTPError (Exception): @@ -125,7 +125,7 @@ class BaseSFTP (object): msg = Message() msg.add_int(_VERSION) msg.add(*extension_pairs) - self._send_packet(CMD_VERSION, str(msg)) + self._send_packet(CMD_VERSION, msg) return version def _log(self, level, msg, *args): @@ -167,6 +167,7 @@ class BaseSFTP (object): def _send_packet(self, t, packet): #self._log(DEBUG2, 'write: %s (len=%d)' % (CMD_NAMES.get(t, '0x%02x' % t), len(packet))) out = struct.pack('>I', len(packet) + 1) + chr(t) + packet + packet = asbytes(packet) if self.ultra_debug: self._log(DEBUG, util.format_binary(out, 'OUT: ')) self._write_all(out) diff --git a/paramiko/sftp_client.py b/paramiko/sftp_client.py index 954cfa0d..0e3d6c81 100644 --- a/paramiko/sftp_client.py +++ b/paramiko/sftp_client.py @@ -173,7 +173,7 @@ class SFTPClient (BaseSFTP): t, msg = self._request(CMD_OPENDIR, path) if t != CMD_HANDLE: raise SFTPError('Expected handle') - handle = msg.get_string() + handle = msg.get_binary() filelist = [] while True: try: @@ -245,7 +245,7 @@ class SFTPClient (BaseSFTP): t, msg = self._request(CMD_OPEN, filename, imode, attrblock) if t != CMD_HANDLE: raise SFTPError('Expected handle') - handle = msg.get_string() + handle = msg.get_binary() self._log(DEBUG, 'open(%r, %r) -> %s' % (filename, mode, hexlify(handle))) return SFTPFile(self, handle, mode, bufsize) @@ -369,8 +369,7 @@ class SFTPClient (BaseSFTP): """ dest = self._adjust_cwd(dest) self._log(DEBUG, 'symlink(%r, %r)' % (source, dest)) - if type(source) is unicode: - source = source.encode('utf-8') + source = bytestring(source) self._request(CMD_SYMLINK, source, dest) def chmod(self, path, mode): @@ -610,7 +609,7 @@ class SFTPClient (BaseSFTP): @since: 1.4 """ file_size = os.stat(localpath).st_size - fl = file(localpath, 'rb') + fl = open(localpath, 'rb') try: return self.putfo(fl, remotepath, os.stat(localpath).st_size, callback, confirm) finally: @@ -636,7 +635,7 @@ class SFTPClient (BaseSFTP): @since: 1.4 """ - fr = self.file(remotepath, 'rb') + fr = self.open(remotepath, 'rb') file_size = self.stat(remotepath).st_size fr.prefetch() try: @@ -671,7 +670,7 @@ class SFTPClient (BaseSFTP): @since: 1.4 """ file_size = self.stat(remotepath).st_size - fl = file(localpath, 'wb') + fl = open(localpath, 'wb') try: size = self.getfo(remotepath, fl, callback) finally: @@ -707,7 +706,7 @@ class SFTPClient (BaseSFTP): raise Exception('unknown type for %r type %r' % (item, type(item))) num = self.request_number self._expecting[num] = fileobj - self._send_packet(t, str(msg)) + self._send_packet(t, msg) self.request_number += 1 finally: self._lock.release() @@ -752,7 +751,7 @@ class SFTPClient (BaseSFTP): Raises EOFError or IOError on error status; otherwise does nothing. """ code = msg.get_int() - text = msg.get_string() + text = msg.get_text() if code == SFTP_OK: return elif code == SFTP_EOF: @@ -770,8 +769,7 @@ class SFTPClient (BaseSFTP): Return an adjusted path if we're emulating a "current working directory" for the server. """ - if type(path) is unicode: - path = path.encode('utf-8') + path = bytestring(path) if self._cwd is None: return path if (len(path) > 0) and (path[0] == '/'): diff --git a/paramiko/sftp_file.py b/paramiko/sftp_file.py index c0bc898f..8cc72336 100644 --- a/paramiko/sftp_file.py +++ b/paramiko/sftp_file.py @@ -348,8 +348,8 @@ class SFTPFile (BufferedFile): """ t, msg = self.sftp._request(CMD_EXTENDED, 'check-file', self.handle, hash_algorithm, long(offset), long(length), block_size) - ext = msg.get_string() - alg = msg.get_string() + ext = msg.get_text() + alg = msg.get_text() data = msg.get_remainder() return data diff --git a/paramiko/sftp_server.py b/paramiko/sftp_server.py index ec340089..96c1f04b 100644 --- a/paramiko/sftp_server.py +++ b/paramiko/sftp_server.py @@ -189,7 +189,7 @@ class SFTPServer (BaseSFTP, SubsystemHandler): item._pack(msg) else: raise Exception('unknown type for ' + repr(item) + ' type ' + repr(type(item))) - self._send_packet(t, str(msg)) + self._send_packet(t, msg) def _send_handle_response(self, request_number, handle, folder=False): if not issubclass(type(handle), SFTPHandle): @@ -236,14 +236,14 @@ class SFTPServer (BaseSFTP, SubsystemHandler): msg.add_string(attr.filename) msg.add_string(str(attr)) attr._pack(msg) - self._send_packet(CMD_NAME, str(msg)) + self._send_packet(CMD_NAME, msg) def _check_file(self, request_number, msg): # this extension actually comes from v6 protocol, but since it's an # extension, i feel like we can reasonably support it backported. # it's very useful for verifying uploaded files or checking for # rsync-like differences between local and remote files. - handle = msg.get_string() + handle = msg.get_binary() alg_list = msg.get_list() start = msg.get_int64() length = msg.get_int64() @@ -295,7 +295,7 @@ class SFTPServer (BaseSFTP, SubsystemHandler): msg.add_string('check-file') msg.add_string(algname) msg.add_bytes(sum_out) - self._send_packet(CMD_EXTENDED_REPLY, str(msg)) + self._send_packet(CMD_EXTENDED_REPLY, msg) def _convert_pflags(self, pflags): "convert SFTP-style open() flags to python's os.open() flags" @@ -318,12 +318,12 @@ class SFTPServer (BaseSFTP, SubsystemHandler): def _process(self, t, request_number, msg): self._log(DEBUG, 'Request: %s' % CMD_NAMES[t]) if t == CMD_OPEN: - path = msg.get_string() + path = msg.get_text() flags = self._convert_pflags(msg.get_int()) attr = SFTPAttributes._from_msg(msg) self._send_handle_response(request_number, self.server.open(path, flags, attr)) elif t == CMD_CLOSE: - handle = msg.get_string() + handle = msg.get_binary() if handle in self.folder_table: del self.folder_table[handle] self._send_status(request_number, SFTP_OK) @@ -335,7 +335,7 @@ class SFTPServer (BaseSFTP, SubsystemHandler): return self._send_status(request_number, SFTP_BAD_MESSAGE, 'Invalid handle') elif t == CMD_READ: - handle = msg.get_string() + handle = msg.get_binary() offset = msg.get_int64() length = msg.get_int() if handle not in self.file_table: @@ -350,54 +350,54 @@ class SFTPServer (BaseSFTP, SubsystemHandler): else: self._send_status(request_number, data) elif t == CMD_WRITE: - handle = msg.get_string() + handle = msg.get_binary() offset = msg.get_int64() - data = msg.get_string() + data = msg.get_binary() if handle not in self.file_table: self._send_status(request_number, SFTP_BAD_MESSAGE, 'Invalid handle') return self._send_status(request_number, self.file_table[handle].write(offset, data)) elif t == CMD_REMOVE: - path = msg.get_string() + path = msg.get_text() self._send_status(request_number, self.server.remove(path)) elif t == CMD_RENAME: - oldpath = msg.get_string() - newpath = msg.get_string() + oldpath = msg.get_text() + newpath = msg.get_text() self._send_status(request_number, self.server.rename(oldpath, newpath)) elif t == CMD_MKDIR: - path = msg.get_string() + path = msg.get_text() attr = SFTPAttributes._from_msg(msg) self._send_status(request_number, self.server.mkdir(path, attr)) elif t == CMD_RMDIR: - path = msg.get_string() + path = msg.get_text() self._send_status(request_number, self.server.rmdir(path)) elif t == CMD_OPENDIR: - path = msg.get_string() + path = msg.get_text() self._open_folder(request_number, path) return elif t == CMD_READDIR: - handle = msg.get_string() + handle = msg.get_binary() if handle not in self.folder_table: self._send_status(request_number, SFTP_BAD_MESSAGE, 'Invalid handle') return folder = self.folder_table[handle] self._read_folder(request_number, folder) elif t == CMD_STAT: - path = msg.get_string() + path = msg.get_text() resp = self.server.stat(path) if issubclass(type(resp), SFTPAttributes): self._response(request_number, CMD_ATTRS, resp) else: self._send_status(request_number, resp) elif t == CMD_LSTAT: - path = msg.get_string() + path = msg.get_text() resp = self.server.lstat(path) if issubclass(type(resp), SFTPAttributes): self._response(request_number, CMD_ATTRS, resp) else: self._send_status(request_number, resp) elif t == CMD_FSTAT: - handle = msg.get_string() + handle = msg.get_binary() if handle not in self.file_table: self._send_status(request_number, SFTP_BAD_MESSAGE, 'Invalid handle') return @@ -407,18 +407,18 @@ class SFTPServer (BaseSFTP, SubsystemHandler): else: self._send_status(request_number, resp) elif t == CMD_SETSTAT: - path = msg.get_string() + path = msg.get_text() attr = SFTPAttributes._from_msg(msg) self._send_status(request_number, self.server.chattr(path, attr)) elif t == CMD_FSETSTAT: - handle = msg.get_string() + handle = msg.get_binary() attr = SFTPAttributes._from_msg(msg) if handle not in self.file_table: self._response(request_number, SFTP_BAD_MESSAGE, 'Invalid handle') return self._send_status(request_number, self.file_table[handle].chattr(attr)) elif t == CMD_READLINK: - path = msg.get_string() + path = msg.get_text() resp = self.server.readlink(path) if type(resp) is str: self._response(request_number, CMD_NAME, 1, resp, '', SFTPAttributes()) @@ -426,15 +426,15 @@ class SFTPServer (BaseSFTP, SubsystemHandler): self._send_status(request_number, resp) elif t == CMD_SYMLINK: # the sftp 2 draft is incorrect here! path always follows target_path - target_path = msg.get_string() - path = msg.get_string() + target_path = msg.get_text() + path = msg.get_text() self._send_status(request_number, self.server.symlink(target_path, path)) elif t == CMD_REALPATH: - path = msg.get_string() + path = msg.get_text() rpath = self.server.canonicalize(path) self._response(request_number, CMD_NAME, 1, rpath, '', SFTPAttributes()) elif t == CMD_EXTENDED: - tag = msg.get_string() + tag = msg.get_text() if tag == 'check-file': self._check_file(request_number, msg) else: diff --git a/paramiko/transport.py b/paramiko/transport.py index c8a693ed..c9e81fa7 100644 --- a/paramiko/transport.py +++ b/paramiko/transport.py @@ -112,8 +112,8 @@ class SecurityOptions (object): x = tuple(x) if type(x) is not tuple: raise TypeError('expected tuple or list') - possible = getattr(self._transport, orig).keys() - forbidden = filter(lambda n: n not in possible, x) + possible = list(getattr(self._transport, orig).keys()) + forbidden = [n for n in x if n not in possible] if len(forbidden) > 0: raise ValueError('unknown cipher') setattr(self._transport, name, x) @@ -276,7 +276,7 @@ class Transport (threading.Thread): @param sock: a socket or socket-like object to create the session over. @type sock: socket """ - if isinstance(sock, (str, unicode)): + if isinstance(sock, string_types): # convert "host:port" into (host, port) hl = sock.split(':', 1) if len(hl) == 1: @@ -735,7 +735,7 @@ class Transport (threading.Thread): try: chanid = self._next_channel() m = Message() - m.add_byte(chr(MSG_CHANNEL_OPEN)) + m.add_byte(cMSG_CHANNEL_OPEN) m.add_string(kind) m.add_int(chanid) m.add_int(self.window_size) @@ -861,7 +861,7 @@ class Transport (threading.Thread): @type byte_count: int """ m = Message() - m.add_byte(chr(MSG_IGNORE)) + m.add_byte(cMSG_IGNORE) if byte_count is None: byte_count = (byte_ord(rng.read(1)) % 32) + 10 m.add_bytes(rng.read(byte_count)) @@ -927,7 +927,7 @@ class Transport (threading.Thread): if wait: self.completion_event = threading.Event() m = Message() - m.add_byte(chr(MSG_GLOBAL_REQUEST)) + m.add_byte(cMSG_GLOBAL_REQUEST) m.add_string(kind) m.add_boolean(wait) if data is not None: @@ -1013,10 +1013,10 @@ class Transport (threading.Thread): # check host key if we were given one if (hostkey is not None): key = self.get_remote_server_key() - if (key.get_name() != hostkey.get_name()) or (str(key) != str(hostkey)): + if (key.get_name() != hostkey.get_name()) or (key.asbytes() != hostkey.asbytes()): self._log(DEBUG, 'Bad host key from server') - self._log(DEBUG, 'Expected: %s: %s' % (hostkey.get_name(), repr(str(hostkey)))) - self._log(DEBUG, 'Got : %s: %s' % (key.get_name(), repr(str(key)))) + self._log(DEBUG, 'Expected: %s: %s' % (hostkey.get_name(), repr(hostkey.asbytes()))) + self._log(DEBUG, 'Got : %s: %s' % (key.get_name(), repr(key.asbytes()))) raise SSHException('Bad host key from server') self._log(DEBUG, 'Host key verified (%s)' % hostkey.get_name()) @@ -1476,15 +1476,15 @@ class Transport (threading.Thread): m = Message() m.add_mpint(self.K) m.add_bytes(self.H) - m.add_byte(id) + m.add_byte(b(id)) m.add_bytes(self.session_id) - out = sofar = SHA.new(str(m)).digest() + out = sofar = SHA.new(m.asbytes()).digest() while len(out) < nbytes: m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_bytes(sofar) - digest = SHA.new(str(m)).digest() + digest = SHA.new(m.asbytes()).digest() out += digest sofar += digest return out[:nbytes] @@ -1606,7 +1606,7 @@ class Transport (threading.Thread): else: self._log(WARNING, 'Oops, unhandled type %d' % ptype) msg = Message() - msg.add_byte(chr(MSG_UNIMPLEMENTED)) + msg.add_byte(cMSG_UNIMPLEMENTED) msg.add_int(m.seqno) self._send_message(msg) except SSHException: @@ -1633,7 +1633,7 @@ class Transport (threading.Thread): self._log(ERROR, util.tb_strings()) self.saved_exception = e _active_threads.remove(self) - for chan in self._channels.values(): + for chan in list(self._channels.values()): chan._unlink() if self.active: self.active = False @@ -1642,7 +1642,7 @@ class Transport (threading.Thread): self.completion_event.set() if self.auth_handler is not None: self.auth_handler.abort() - for event in self.channel_events.values(): + for event in list(self.channel_events.values()): event.set() try: self.lock.acquire() @@ -1731,13 +1731,13 @@ class Transport (threading.Thread): pkex = list(self.get_security_options().kex) pkex.remove('diffie-hellman-group-exchange-sha1') self.get_security_options().kex = pkex - available_server_keys = filter(self.server_key_dict.keys().__contains__, - self._preferred_keys) + available_server_keys = list(filter(list(self.server_key_dict.keys()).__contains__, + self._preferred_keys)) else: available_server_keys = self._preferred_keys m = Message() - m.add_byte(chr(MSG_KEXINIT)) + m.add_byte(cMSG_KEXINIT) m.add_bytes(rng.read(16)) m.add_list(self._preferred_kex) m.add_list(available_server_keys) @@ -1752,7 +1752,7 @@ class Transport (threading.Thread): m.add_boolean(False) m.add_int(0) # save a copy for later (needed to compute a hash) - self.local_kex_init = str(m) + self.local_kex_init = m.asbytes() self._send_message(m) def _parse_kex_init(self, m): @@ -1850,7 +1850,7 @@ class Transport (threading.Thread): # actually some extra bytes (one NUL byte in openssh's case) added to # the end of the packet but not parsed. turns out we need to throw # away those bytes because they aren't part of the hash. - self.remote_kex_init = chr(MSG_KEXINIT) + m.get_so_far() + self.remote_kex_init = cMSG_KEXINIT + m.get_so_far() def _activate_inbound(self): "switch on newly negotiated encryption parameters for inbound traffic" @@ -1879,7 +1879,7 @@ class Transport (threading.Thread): def _activate_outbound(self): "switch on newly negotiated encryption parameters for outbound traffic" m = Message() - m.add_byte(chr(MSG_NEWKEYS)) + m.add_byte(cMSG_NEWKEYS) self._send_message(m) block_size = self._cipher_info[self.local_cipher]['block-size'] if self.server_mode: @@ -1952,20 +1952,20 @@ class Transport (threading.Thread): self._log(INFO, 'Disconnect (code %d): %s' % (code, desc)) def _parse_global_request(self, m): - kind = m.get_string() + kind = m.get_text() self._log(DEBUG, 'Received global request "%s"' % kind) want_reply = m.get_boolean() if not self.server_mode: self._log(DEBUG, 'Rejecting "%s" global request from server.' % kind) ok = False elif kind == 'tcpip-forward': - address = m.get_string() + address = m.get_text() port = m.get_int() ok = self.server_object.check_port_forward_request(address, port) if ok != False: ok = (ok,) elif kind == 'cancel-tcpip-forward': - address = m.get_string() + address = m.get_text() port = m.get_int() self.server_object.cancel_port_forward_request(address, port) ok = True @@ -1978,10 +1978,10 @@ class Transport (threading.Thread): if want_reply: msg = Message() if ok: - msg.add_byte(chr(MSG_REQUEST_SUCCESS)) + msg.add_byte(cMSG_REQUEST_SUCCESS) msg.add(*extra) else: - msg.add_byte(chr(MSG_REQUEST_FAILURE)) + msg.add_byte(cMSG_REQUEST_FAILURE) self._send_message(msg) def _parse_request_success(self, m): @@ -2019,8 +2019,8 @@ class Transport (threading.Thread): def _parse_channel_open_failure(self, m): chanid = m.get_int() reason = m.get_int() - reason_str = m.get_string() - lang = m.get_string() + reason_str = m.get_text() + lang = m.get_text() reason_text = CONNECTION_FAILED_CODE.get(reason, '(unknown code)') self._log(INFO, 'Secsh channel %d open FAILED: %s: %s' % (chanid, reason_str, reason_text)) self.lock.acquire() @@ -2036,7 +2036,7 @@ class Transport (threading.Thread): return def _parse_channel_open(self, m): - kind = m.get_string() + kind = m.get_text() chanid = m.get_int() initial_window_size = m.get_int() max_packet_size = m.get_int() @@ -2049,7 +2049,7 @@ class Transport (threading.Thread): finally: self.lock.release() elif (kind == 'x11') and (self._x11_handler is not None): - origin_addr = m.get_string() + origin_addr = m.get_text() origin_port = m.get_int() self._log(DEBUG, 'Incoming x11 connection from %s:%d' % (origin_addr, origin_port)) self.lock.acquire() @@ -2058,9 +2058,9 @@ class Transport (threading.Thread): finally: self.lock.release() elif (kind == 'forwarded-tcpip') and (self._tcp_handler is not None): - server_addr = m.get_string() + server_addr = m.get_text() server_port = m.get_int() - origin_addr = m.get_string() + origin_addr = m.get_text() origin_port = m.get_int() self._log(DEBUG, 'Incoming tcp forwarded connection from %s:%d' % (origin_addr, origin_port)) self.lock.acquire() @@ -2080,9 +2080,9 @@ class Transport (threading.Thread): self.lock.release() if kind == 'direct-tcpip': # handle direct-tcpip requests comming from the client - dest_addr = m.get_string() + dest_addr = m.get_text() dest_port = m.get_int() - origin_addr = m.get_string() + origin_addr = m.get_text() origin_port = m.get_int() reason = self.server_object.check_channel_direct_tcpip_request( my_chanid, (origin_addr, origin_port), @@ -2094,7 +2094,7 @@ class Transport (threading.Thread): reject = True if reject: msg = Message() - msg.add_byte(chr(MSG_CHANNEL_OPEN_FAILURE)) + msg.add_byte(cMSG_CHANNEL_OPEN_FAILURE) msg.add_int(chanid) msg.add_int(reason) msg.add_string('') @@ -2113,7 +2113,7 @@ class Transport (threading.Thread): finally: self.lock.release() m = Message() - m.add_byte(chr(MSG_CHANNEL_OPEN_SUCCESS)) + m.add_byte(cMSG_CHANNEL_OPEN_SUCCESS) m.add_int(chanid) m.add_int(my_chanid) m.add_int(self.window_size) diff --git a/tests/test_auth.py b/tests/test_auth.py index ea9b2bdd..a7c9e61b 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -111,8 +111,8 @@ class AuthTest (unittest.TestCase): self.sockc.close() def start_server(self): - self.public_host_key = RSAKey(data=str(host_key)) host_key = RSAKey.from_private_key_file(test_path('test_rsa.key')) + self.public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) self.event = threading.Event() self.server = NullServer() diff --git a/tests/test_client.py b/tests/test_client.py index 91aac334..0959ac9a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -86,8 +86,8 @@ class SSHClientTest (unittest.TestCase): """ verify that the SSHClient stuff works too. """ - public_host_key = paramiko.RSAKey(data=str(host_key)) host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = paramiko.RSAKey(data=host_key.asbytes()) self.tc = paramiko.SSHClient() self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port), 'ssh-rsa', public_host_key) @@ -119,8 +119,8 @@ class SSHClientTest (unittest.TestCase): """ verify that SSHClient works with a DSA key. """ - public_host_key = paramiko.RSAKey(data=str(host_key)) host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = paramiko.RSAKey(data=host_key.asbytes()) self.tc = paramiko.SSHClient() self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port), 'ssh-rsa', public_host_key) @@ -152,8 +152,8 @@ class SSHClientTest (unittest.TestCase): """ verify that SSHClient accepts and tries multiple key files. """ - public_host_key = paramiko.RSAKey(data=str(host_key)) host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = paramiko.RSAKey(data=host_key.asbytes()) self.tc = paramiko.SSHClient() self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port), 'ssh-rsa', public_host_key) @@ -169,8 +169,8 @@ class SSHClientTest (unittest.TestCase): """ verify that SSHClient's AutoAddPolicy works. """ - public_host_key = paramiko.RSAKey(data=str(host_key)) host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = paramiko.RSAKey(data=host_key.asbytes()) self.tc = paramiko.SSHClient() self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy()) @@ -190,8 +190,8 @@ class SSHClientTest (unittest.TestCase): verify that when an SSHClient is collected, its transport (and the transport's packetizer) is closed. """ - public_host_key = paramiko.RSAKey(data=str(host_key)) host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = paramiko.RSAKey(data=host_key.asbytes()) self.tc = paramiko.SSHClient() self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy()) diff --git a/tests/test_hostkeys.py b/tests/test_hostkeys.py index 44070cbe..fd873e25 100644 --- a/tests/test_hostkeys.py +++ b/tests/test_hostkeys.py @@ -65,8 +65,8 @@ class HostKeysTest (unittest.TestCase): def test_1_load(self): hostdict = paramiko.HostKeys('hostfile.temp') self.assertEquals(2, len(hostdict)) - self.assertEquals(1, len(hostdict.values()[0])) - self.assertEquals(1, len(hostdict.values()[1])) + self.assertEquals(1, len(list(hostdict.values())[0])) + self.assertEquals(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp) @@ -75,7 +75,7 @@ class HostKeysTest (unittest.TestCase): hh = '|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c=' key = paramiko.RSAKey(data=base64.decodestring(keyblob)) hostdict.add(hh, 'ssh-rsa', key) - self.assertEquals(3, len(hostdict)) + self.assertEquals(3, len(list(hostdict))) x = hostdict['foo.example.com'] fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() self.assertEquals('7EC91BB336CB6D810B124B1353C32396', fp) @@ -85,8 +85,8 @@ class HostKeysTest (unittest.TestCase): hostdict = paramiko.HostKeys('hostfile.temp') self.assert_('secure.example.com' in hostdict) self.assert_('not.example.com' not in hostdict) - self.assert_(hostdict.has_key('secure.example.com')) - self.assert_(not hostdict.has_key('not.example.com')) + self.assert_('secure.example.com' in hostdict) + self.assert_('not.example.com' not in hostdict) x = hostdict.get('secure.example.com', None) self.assert_(x is not None) fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() @@ -108,9 +108,9 @@ class HostKeysTest (unittest.TestCase): hostdict['fake.example.com']['ssh-rsa'] = key self.assertEquals(3, len(hostdict)) - self.assertEquals(2, len(hostdict.values()[0])) - self.assertEquals(1, len(hostdict.values()[1])) - self.assertEquals(1, len(hostdict.values()[2])) + self.assertEquals(2, len(list(hostdict.values())[0])) + self.assertEquals(1, len(list(hostdict.values())[1])) + self.assertEquals(1, len(list(hostdict.values())[2])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() self.assertEquals('7EC91BB336CB6D810B124B1353C32396', fp) fp = hexlify(hostdict['secure.example.com']['ssh-dss'].get_fingerprint()).upper() diff --git a/tests/test_kex.py b/tests/test_kex.py index be8d7f01..21986fcc 100644 --- a/tests/test_kex.py +++ b/tests/test_kex.py @@ -37,6 +37,8 @@ class FakeRng (object): class FakeKey (object): def __str__(self): return 'fake-key' + def asbytes(self): + return b('fake-key') def sign_ssh_data(self, rng, H): return 'fake-sig' @@ -90,7 +92,7 @@ class KexTest (unittest.TestCase): kex = KexGroup1(transport) kex.start_kex() x = '1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect) # fake "reply" @@ -121,7 +123,7 @@ class KexTest (unittest.TestCase): x = '1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' self.assertEquals(self.K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assert_(transport._activated) def test_3_gex_client(self): @@ -130,7 +132,7 @@ class KexTest (unittest.TestCase): kex = KexGex(transport) kex.start_kex() x = '22000004000000080000002000' - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) msg = Message() @@ -139,7 +141,7 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = '20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) msg = Message() @@ -160,7 +162,7 @@ class KexTest (unittest.TestCase): kex = KexGex(transport) kex.start_kex(_test_old_style=True) x = '1E00000800' - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) msg = Message() @@ -169,7 +171,7 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = '20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) msg = Message() @@ -198,19 +200,19 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) x = '1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102' - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) msg = Message() msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) - K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581L + K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 H = 'CE754197C21BF3452863B4F44D0B3951F12516EF' x = '210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' self.assertEquals(K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assert_(transport._activated) def test_6_gex_server_with_old_client(self): @@ -225,17 +227,17 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) x = '1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102' - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) msg = Message() msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) - K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581L + K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 H = 'B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B' x = '210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' self.assertEquals(K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(x, hexlify(str(transport._message)).upper()) + self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assert_(transport._activated) diff --git a/tests/test_message.py b/tests/test_message.py index d0e604e3..2580115e 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -27,10 +27,16 @@ from paramiko.common import * class MessageTest (unittest.TestCase): - __a = '\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01q\x00\x00\x00\x05hello\x00\x00\x03\xe8' + ('x' * 1000) - __b = '\x01\x00\xf3\x00\x3f\x00\x00\x00\x10huey,dewey,louie' - __c = '\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7' - __d = '\x00\x00\x00\x05\x00\x00\x00\x05\x11\x22\x33\x44\x55\x01\x00\x00\x00\x03cat\x00\x00\x00\x03a,b' + if PY3: + __a = b'\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01q\x00\x00\x00\x05hello\x00\x00\x03\xe8' + (b'x' * 1000) + __b = b'\x01\x00\xf3\x00\x3f\x00\x00\x00\x10huey,dewey,louie' + __c = b'\x00\x00\x00\x05\xff\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7' + __d = b'\x00\x00\x00\x05\xff\x00\x00\x00\x05\x11\x22\x33\x44\x55\xff\x00\x00\x00\x0a\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03cat\x00\x00\x00\x03a,b' + else: + __a = '\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01q\x00\x00\x00\x05hello\x00\x00\x03\xe8' + ('x' * 1000) + __b = '\x01\x00\xf3\x00\x3f\x00\x00\x00\x10huey,dewey,louie' + __c = '\x00\x00\x00\x05\xff\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7' + __d = '\x00\x00\x00\x05\xff\x00\x00\x00\x05\x11\x22\x33\x44\x55\xff\x00\x00\x00\x0a\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03cat\x00\x00\x00\x03a,b' def test_1_encode(self): msg = Message() @@ -39,63 +45,65 @@ class MessageTest (unittest.TestCase): msg.add_string('q') msg.add_string('hello') msg.add_string('x' * 1000) - self.assertEquals(str(msg), self.__a) + self.assertEquals(msg.asbytes(), self.__a) msg = Message() msg.add_boolean(True) msg.add_boolean(False) - msg.add_byte('\xf3') - msg.add_bytes('\x00\x3f') + msg.add_byte(byte_chr(0xf3)) + + msg.add_bytes(zero_byte + byte_chr(0x3f)) msg.add_list(['huey', 'dewey', 'louie']) - self.assertEquals(str(msg), self.__b) + self.assertEquals(msg.asbytes(), self.__b) msg = Message() msg.add_int64(5) - msg.add_int64(0xf5e4d3c2b109L) + msg.add_int64(0xf5e4d3c2b109) msg.add_mpint(17) - msg.add_mpint(0xf5e4d3c2b109L) - msg.add_mpint(-0x65e4d3c2b109L) - self.assertEquals(str(msg), self.__c) + msg.add_mpint(0xf5e4d3c2b109) + msg.add_mpint(-0x65e4d3c2b109) + self.assertEquals(msg.asbytes(), self.__c) def test_2_decode(self): msg = Message(self.__a) self.assertEquals(msg.get_int(), 23) self.assertEquals(msg.get_int(), 123789456) - self.assertEquals(msg.get_string(), 'q') - self.assertEquals(msg.get_string(), 'hello') - self.assertEquals(msg.get_string(), 'x' * 1000) + self.assertEquals(msg.get_text(), 'q') + self.assertEquals(msg.get_text(), 'hello') + self.assertEquals(msg.get_text(), 'x' * 1000) msg = Message(self.__b) self.assertEquals(msg.get_boolean(), True) self.assertEquals(msg.get_boolean(), False) - self.assertEquals(msg.get_byte(), '\xf3') - self.assertEquals(msg.get_bytes(2), '\x00\x3f') + self.assertEquals(msg.get_byte(), byte_chr(0xf3)) + self.assertEquals(msg.get_bytes(2), zero_byte + byte_chr(0x3f)) self.assertEquals(msg.get_list(), ['huey', 'dewey', 'louie']) msg = Message(self.__c) self.assertEquals(msg.get_int64(), 5) - self.assertEquals(msg.get_int64(), 0xf5e4d3c2b109L) + self.assertEquals(msg.get_int64(), 0xf5e4d3c2b109) self.assertEquals(msg.get_mpint(), 17) - self.assertEquals(msg.get_mpint(), 0xf5e4d3c2b109L) - self.assertEquals(msg.get_mpint(), -0x65e4d3c2b109L) + self.assertEquals(msg.get_mpint(), 0xf5e4d3c2b109) + self.assertEquals(msg.get_mpint(), -0x65e4d3c2b109) def test_3_add(self): msg = Message() msg.add(5) - msg.add(0x1122334455L) + msg.add(0x1122334455) + msg.add(0xf00000000000000000) msg.add(True) msg.add('cat') msg.add(['a', 'b']) - self.assertEquals(str(msg), self.__d) + self.assertEquals(msg.asbytes(), self.__d) def test_4_misc(self): msg = Message(self.__d) self.assertEquals(msg.get_int(), 5) - self.assertEquals(msg.get_mpint(), 0x1122334455L) - self.assertEquals(msg.get_so_far(), self.__d[:13]) - self.assertEquals(msg.get_remainder(), self.__d[13:]) + self.assertEquals(msg.get_int(), 0x1122334455) + self.assertEquals(msg.get_int(), 0xf00000000000000000) + self.assertEquals(msg.get_so_far(), self.__d[:29]) + self.assertEquals(msg.get_remainder(), self.__d[29:]) msg.rewind() self.assertEquals(msg.get_int(), 5) self.assertEquals(msg.get_so_far(), self.__d[:4]) self.assertEquals(msg.get_remainder(), self.__d[4:]) - diff --git a/tests/test_packetizer.py b/tests/test_packetizer.py index c39fc455..b53b741f 100644 --- a/tests/test_packetizer.py +++ b/tests/test_packetizer.py @@ -42,7 +42,7 @@ class PacketizerTest (unittest.TestCase): # message has to be at least 16 bytes long, so we'll have at least one # block of data encrypted that contains zero random padding bytes m = Message() - m.add_byte(chr(100)) + m.add_byte(byte_chr(100)) m.add_int(100) m.add_int(1) m.add_int(900) diff --git a/tests/test_pkey.py b/tests/test_pkey.py index fe823a77..589a35d8 100644 --- a/tests/test_pkey.py +++ b/tests/test_pkey.py @@ -144,7 +144,7 @@ class KeyTest (unittest.TestCase): # verify that the private & public keys compare equal key = RSAKey.from_private_key_file('tests/test_rsa.key') self.assertEquals(key, key) - pub = RSAKey(data=str(key)) + pub = RSAKey(data=key.asbytes()) self.assert_(key.can_sign()) self.assert_(not pub.can_sign()) self.assertEquals(key, pub) @@ -153,7 +153,7 @@ class KeyTest (unittest.TestCase): # verify that the private & public keys compare equal key = DSSKey.from_private_key_file('tests/test_dss.key') self.assertEquals(key, key) - pub = DSSKey(data=str(key)) + pub = DSSKey(data=key.asbytes()) self.assert_(key.can_sign()) self.assert_(not pub.can_sign()) self.assertEquals(key, pub) @@ -164,11 +164,11 @@ class KeyTest (unittest.TestCase): msg = key.sign_ssh_data(rng, 'ice weasels') self.assert_(type(msg) is Message) msg.rewind() - self.assertEquals('ssh-rsa', msg.get_string()) - sig = ''.join([chr(int(x, 16)) for x in SIGNED_RSA.split(':')]) - self.assertEquals(sig, msg.get_string()) + self.assertEquals('ssh-rsa', msg.get_text()) + sig = bytes().join([byte_chr(int(x, 16)) for x in SIGNED_RSA.split(':')]) + self.assertEquals(sig, msg.get_binary()) msg.rewind() - pub = RSAKey(data=str(key)) + pub = RSAKey(data=key.asbytes()) self.assert_(pub.verify_ssh_sig('ice weasels', msg)) def test_9_sign_dss(self): @@ -177,13 +177,13 @@ class KeyTest (unittest.TestCase): msg = key.sign_ssh_data(rng, 'ice weasels') self.assert_(type(msg) is Message) msg.rewind() - self.assertEquals('ssh-dss', msg.get_string()) + self.assertEquals('ssh-dss', msg.get_text()) # can't do the same test as we do for RSA, because DSS signatures # are usually different each time. but we can test verification # anyway so it's ok. - self.assertEquals(40, len(msg.get_string())) + self.assertEquals(40, len(msg.get_binary())) msg.rewind() - pub = DSSKey(data=str(key)) + pub = DSSKey(data=key.asbytes()) self.assert_(pub.verify_ssh_sig('ice weasels', msg)) def test_A_generate_rsa(self): @@ -227,7 +227,7 @@ class KeyTest (unittest.TestCase): # verify that the private & public keys compare equal key = ECDSAKey.from_private_key_file('tests/test_ecdsa.key') self.assertEquals(key, key) - pub = ECDSAKey(data=str(key)) + pub = ECDSAKey(data=key.asbytes()) self.assert_(key.can_sign()) self.assert_(not pub.can_sign()) self.assertEquals(key, pub) @@ -238,12 +238,12 @@ class KeyTest (unittest.TestCase): msg = key.sign_ssh_data(rng, 'ice weasels') self.assert_(type(msg) is Message) msg.rewind() - self.assertEquals('ecdsa-sha2-nistp256', msg.get_string()) + self.assertEquals('ecdsa-sha2-nistp256', msg.get_text()) # ECDSA signatures, like DSS signatures, tend to be different # each time, so we can't compare against a "known correct" # signature. # Even the length of the signature can change. msg.rewind() - pub = ECDSAKey(data=str(key)) + pub = ECDSAKey(data=key.asbytes()) self.assert_(pub.verify_ssh_sig('ice weasels', msg)) diff --git a/tests/test_sftp.py b/tests/test_sftp.py index a421355e..a4452711 100755 --- a/tests/test_sftp.py +++ b/tests/test_sftp.py @@ -645,7 +645,8 @@ class SFTPTest (unittest.TestCase): try: sftp.rename(FOLDER + '/something', FOLDER + u'/\u00fcnic\u00f8de') sftp.open(FOLDER + '/\xc3\xbcnic\xc3\xb8\x64\x65', 'r') - except Exception, e: + except Exception: + e = sys.exc_info()[1] self.fail('exception ' + e) sftp.unlink(FOLDER + '/\xc3\xbcnic\xc3\xb8\x64\x65') diff --git a/tests/test_sftp_big.py b/tests/test_sftp_big.py index 9a4ea311..94088f78 100644 --- a/tests/test_sftp_big.py +++ b/tests/test_sftp_big.py @@ -73,7 +73,7 @@ class BigSFTPTest (unittest.TestCase): # now make sure every file is there, by creating a list of filenmes # and reading them in random order. - numlist = range(numfiles) + numlist = list(range(numfiles)) while len(numlist) > 0: r = numlist[random.randint(0, len(numlist) - 1)] f = sftp.open('%s/file%d.txt' % (FOLDER, r)) diff --git a/tests/test_transport.py b/tests/test_transport.py index d8cd10d5..6c62b3e3 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -121,8 +121,8 @@ class TransportTest(ParamikoTest): self.sockc.close() def setup_test_server(self, client_options=None, server_options=None): - public_host_key = RSAKey(data=str(host_key)) host_key = RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) if client_options is not None: @@ -171,8 +171,8 @@ class TransportTest(ParamikoTest): loopback sockets. this is hardly "simple" but it's simpler than the later tests. :) """ - public_host_key = RSAKey(data=str(host_key)) host_key = RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() @@ -196,8 +196,8 @@ class TransportTest(ParamikoTest): """ verify that a long banner doesn't mess up the handshake. """ - public_host_key = RSAKey(data=str(host_key)) host_key = RSAKey.from_private_key_file(test_path('test_rsa.key')) + public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() @@ -708,7 +708,7 @@ class TransportTest(ParamikoTest): # Simulate in-transit MSG_CHANNEL_WINDOW_ADJUST by sending it # before responding to the incoming MSG_KEXINIT. m2 = Message() - m2.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST)) + m2.add_byte(cMSG_CHANNEL_WINDOW_ADJUST) m2.add_int(chan.remote_chanid) m2.add_int(1) # bytes to add self._send_message(m2) -- cgit v1.2.3 From fcf56ff9f85653e48db929b4a60460beabad24de Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Thu, 31 Oct 2013 10:01:21 -0700 Subject: Fix bytes/str type in more places --- paramiko/buffered_pipe.py | 3 +- paramiko/ecdsakey.py | 15 ++++++---- paramiko/hostkeys.py | 5 ++-- paramiko/packet.py | 4 +-- paramiko/pkey.py | 4 +-- paramiko/rsakey.py | 29 ++++++++++++++------ paramiko/util.py | 8 +++--- tests/test_buffered_pipe.py | 19 +++++++------ tests/test_hostkeys.py | 19 +++++++------ tests/test_kex.py | 40 +++++++++++++-------------- tests/test_packetizer.py | 34 ++++++++++++++++------- tests/test_pkey.py | 67 +++++++++++++++++++++++++-------------------- tests/test_util.py | 6 ++-- 13 files changed, 147 insertions(+), 106 deletions(-) (limited to 'tests/test_packetizer.py') diff --git a/paramiko/buffered_pipe.py b/paramiko/buffered_pipe.py index 4ef5cf74..0391dee9 100644 --- a/paramiko/buffered_pipe.py +++ b/paramiko/buffered_pipe.py @@ -25,6 +25,7 @@ read operations are blocking and can have a timeout set. import array import threading import time +from paramiko.common import * class PipeTimeout (IOError): @@ -121,7 +122,7 @@ class BufferedPipe (object): @raise PipeTimeout: if a timeout was specified and no data was ready before that timeout """ - out = '' + out = bytes() self._lock.acquire() try: if len(self._buffer) == 0: diff --git a/paramiko/ecdsakey.py b/paramiko/ecdsakey.py index c3d2a736..d15b2ac7 100644 --- a/paramiko/ecdsakey.py +++ b/paramiko/ecdsakey.py @@ -63,7 +63,7 @@ class ECDSAKey (PKey): raise SSHException("Can't handle curve of type %s" % curvename) pointinfo = msg.get_binary() - if pointinfo[0] != four_byte: + 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:], @@ -157,14 +157,19 @@ class ECDSAKey (PKey): data = self._read_private_key('EC', file_obj, password) self._decode_key(data) - ALLOWED_PADDINGS = ['\x01', '\x02\x02', '\x03\x03\x03', '\x04\x04\x04\x04', - '\x05\x05\x05\x05\x05', '\x06\x06\x06\x06\x06\x06', - '\x07\x07\x07\x07\x07\x07\x07'] + if PY3: + ALLOWED_PADDINGS = [b'\x01', b'\x02\x02', b'\x03\x03\x03', b'\x04\x04\x04\x04', + b'\x05\x05\x05\x05\x05', b'\x06\x06\x06\x06\x06\x06', + b'\x07\x07\x07\x07\x07\x07\x07'] + else: + ALLOWED_PADDINGS = ['\x01', '\x02\x02', '\x03\x03\x03', '\x04\x04\x04\x04', + '\x05\x05\x05\x05\x05', '\x06\x06\x06\x06\x06\x06', + '\x07\x07\x07\x07\x07\x07\x07'] 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" % (binascii.hexlify(empty))) + raise ValueError("weird padding: %s" % (binascii.hexlify(data))) data = data[:-len(padding)] key = SigningKey.from_der(data) self.signing_key = key diff --git a/paramiko/hostkeys.py b/paramiko/hostkeys.py index 17ee8084..015b3ba2 100644 --- a/paramiko/hostkeys.py +++ b/paramiko/hostkeys.py @@ -81,6 +81,7 @@ class HostKeyEntry: # Decide what kind of key we're looking at and create an object # to hold it accordingly. try: + key = b(key) if keytype == 'ssh-rsa': key = RSAKey(data=base64.decodestring(key)) elif keytype == 'ssh-dss': @@ -361,9 +362,9 @@ class HostKeys (MutableMapping): else: if salt.startswith('|1|'): salt = salt.split('|')[2] - salt = base64.decodestring(salt) + salt = base64.decodestring(b(salt)) assert len(salt) == SHA.digest_size - hmac = HMAC.HMAC(salt, hostname, SHA).digest() + hmac = HMAC.HMAC(salt, b(hostname), SHA).digest() hostkey = '|1|%s|%s' % (base64.encodestring(salt), base64.encodestring(hmac)) return hostkey.replace('\n', '') hash_host = staticmethod(hash_host) diff --git a/paramiko/packet.py b/paramiko/packet.py index 193acf69..fa5ceffa 100644 --- a/paramiko/packet.py +++ b/paramiko/packet.py @@ -87,8 +87,8 @@ class Packetizer (object): self.__sdctr_out = False self.__mac_engine_out = None self.__mac_engine_in = None - self.__mac_key_out = '' - self.__mac_key_in = '' + self.__mac_key_out = bytes() + self.__mac_key_in = bytes() self.__compress_engine_out = None self.__compress_engine_in = None self.__sequence_number_out = long_zero diff --git a/paramiko/pkey.py b/paramiko/pkey.py index c88e5c85..5baf4502 100644 --- a/paramiko/pkey.py +++ b/paramiko/pkey.py @@ -148,7 +148,7 @@ class PKey (object): @return: a base64 string containing the public part of the key. @rtype: str """ - return base64.encodestring(self.asbytes()).replace('\n', '') + return u(base64.encodestring(self.asbytes())).replace('\n', '') def sign_ssh_data(self, rng, data): """ @@ -378,7 +378,7 @@ class PKey (object): f.write('Proc-Type: 4,ENCRYPTED\n') f.write('DEK-Info: %s,%s\n' % (cipher_name, hexlify(salt).upper())) f.write('\n') - s = base64.encodestring(data) + s = u(base64.encodestring(data)) # re-wrap to 64-char lines s = ''.join(s.split('\n')) s = '\n'.join([s[i : i+64] for i in range(0, len(s), 64)]) diff --git a/paramiko/rsakey.py b/paramiko/rsakey.py index cb7b30b1..90945031 100644 --- a/paramiko/rsakey.py +++ b/paramiko/rsakey.py @@ -152,15 +152,26 @@ class RSAKey (PKey): ### internals... - def _pkcs1imify(self, data): - """ - turn a 20-byte SHA1 hash into a blob of data as large as the key's N, - using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. - """ - SHA1_DIGESTINFO = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' - size = len(util.deflate_long(self.n, 0)) - filler = '\xff' * (size - len(SHA1_DIGESTINFO) - len(data) - 3) - return '\x00\x01' + filler + '\x00' + SHA1_DIGESTINFO + data + if PY3: + def _pkcs1imify(self, data): + """ + turn a 20-byte SHA1 hash into a blob of data as large as the key's N, + using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. + """ + SHA1_DIGESTINFO = b'\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' + size = len(util.deflate_long(self.n, 0)) + filler = b'\xff' * (size - len(SHA1_DIGESTINFO) - len(data) - 3) + return b'\x00\x01' + filler + b'\x00' + SHA1_DIGESTINFO + data + else: + def _pkcs1imify(self, data): + """ + turn a 20-byte SHA1 hash into a blob of data as large as the key's N, + using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. + """ + SHA1_DIGESTINFO = b('\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14') + size = len(util.deflate_long(self.n, 0)) + filler = b('\xff') * (size - len(SHA1_DIGESTINFO) - len(data) - 3) + return b('\x00\x01') + filler + b('\x00') + SHA1_DIGESTINFO + b(data) def _from_private_key_file(self, filename, password): data = self._read_private_key_file('RSA', filename, password) diff --git a/paramiko/util.py b/paramiko/util.py index 61fdcc6a..7844fc68 100644 --- a/paramiko/util.py +++ b/paramiko/util.py @@ -151,7 +151,7 @@ def generate_key_bytes(hashclass, salt, key, nbytes): hashing function (like C{MD5} or C{SHA}). @type hashclass: L{Crypto.Hash} @param salt: data to salt the hash with. - @type salt: string + @type salt: byte string @param key: human-entered password or passphrase. @type key: string @param nbytes: number of bytes to generate. @@ -159,15 +159,15 @@ def generate_key_bytes(hashclass, salt, key, nbytes): @return: key data @rtype: string """ - keydata = '' - digest = '' + keydata = bytes() + digest = bytes() if len(salt) > 8: salt = salt[:8] while nbytes > 0: hash_obj = hashclass.new() if len(digest) > 0: hash_obj.update(digest) - hash_obj.update(key) + hash_obj.update(b(key)) hash_obj.update(salt) digest = hash_obj.digest() size = min(nbytes, len(digest)) diff --git a/tests/test_buffered_pipe.py b/tests/test_buffered_pipe.py index 04d665c4..7f48b705 100644 --- a/tests/test_buffered_pipe.py +++ b/tests/test_buffered_pipe.py @@ -25,6 +25,7 @@ import time import unittest from paramiko.buffered_pipe import BufferedPipe, PipeTimeout from paramiko import pipe +from paramiko.py3compat import b from tests.util import ParamikoTest @@ -48,35 +49,35 @@ class BufferedPipeTest(ParamikoTest): p.feed('hello.') self.assert_(p.read_ready()) data = p.read(6) - self.assertEquals('hello.', data) + self.assertEquals(b('hello.'), data) p.feed('plus/minus') - self.assertEquals('plu', p.read(3)) - self.assertEquals('s/m', p.read(3)) - self.assertEquals('inus', p.read(4)) + self.assertEquals(b('plu'), p.read(3)) + self.assertEquals(b('s/m'), p.read(3)) + self.assertEquals(b('inus'), p.read(4)) p.close() self.assert_(not p.read_ready()) - self.assertEquals('', p.read(1)) + self.assertEquals(b(''), p.read(1)) def test_2_delay(self): p = BufferedPipe() self.assert_(not p.read_ready()) threading.Thread(target=delay_thread, args=(p,)).start() - self.assertEquals('a', p.read(1, 0.1)) + self.assertEquals(b('a'), p.read(1, 0.1)) try: p.read(1, 0.1) self.assert_(False) except PipeTimeout: pass - self.assertEquals('b', p.read(1, 1.0)) - self.assertEquals('', p.read(1)) + self.assertEquals(b('b'), p.read(1, 1.0)) + self.assertEquals(b(''), p.read(1)) def test_3_close_while_reading(self): p = BufferedPipe() threading.Thread(target=close_thread, args=(p,)).start() data = p.read(1, 1.0) - self.assertEquals('', data) + self.assertEquals(b(''), data) def test_4_or_pipe(self): p = pipe.make_pipe() diff --git a/tests/test_hostkeys.py b/tests/test_hostkeys.py index fd873e25..66b41b6f 100644 --- a/tests/test_hostkeys.py +++ b/tests/test_hostkeys.py @@ -25,6 +25,7 @@ from binascii import hexlify import os import unittest import paramiko +from paramiko.py3compat import b test_hosts_file = """\ @@ -36,12 +37,12 @@ BGQ3GQ/Fc7SX6gkpXkwcZryoi4kNFhHu5LvHcZPdxXV1D+uTMfGS1eyd2Yz/DoNWXNAl8TI0cAsW\ 5ymME3bQ4J/k1IKxCtz/bAlAqFgKoc+EolMziDYqWIATtW0rYTJvzGAzTmMj80/QpsFH+Pc2M= """ -keyblob = """\ +keyblob = b("""\ AAAAB3NzaC1yc2EAAAABIwAAAIEA8bP1ZA7DCZDB9J0s50l31MBGQ3GQ/Fc7SX6gkpXkwcZryoi4k\ NFhHu5LvHcZPdxXV1D+uTMfGS1eyd2Yz/DoNWXNAl8TI0cAsW5ymME3bQ4J/k1IKxCtz/bAlAqFgK\ -oc+EolMziDYqWIATtW0rYTJvzGAzTmMj80/QpsFH+Pc2M=""" +oc+EolMziDYqWIATtW0rYTJvzGAzTmMj80/QpsFH+Pc2M=""") -keyblob_dss = """\ +keyblob_dss = b("""\ AAAAB3NzaC1kc3MAAACBAOeBpgNnfRzr/twmAQRu2XwWAp3CFtrVnug6s6fgwj/oLjYbVtjAy6pl/\ h0EKCWx2rf1IetyNsTxWrniA9I6HeDj65X1FyDkg6g8tvCnaNB8Xp/UUhuzHuGsMIipRxBxw9LF60\ 8EqZcj1E3ytktoW5B5OcjrkEoz3xG7C+rpIjYvAAAAFQDwz4UnmsGiSNu5iqjn3uTzwUpshwAAAIE\ @@ -49,7 +50,7 @@ AkxfFeY8P2wZpDjX0MimZl5wkoFQDL25cPzGBuB4OnB8NoUk/yjAHIIpEShw8V+LzouMK5CTJQo5+\ Ngw3qIch/WgRmMHy4kBq1SsXMjQCte1So6HBMvBPIW5SiMTmjCfZZiw4AYHK+B/JaOwaG9yRg2Ejg\ 4Ok10+XFDxlqZo8Y+wAAACARmR7CCPjodxASvRbIyzaVpZoJ/Z6x7dAumV+ysrV1BVYd0lYukmnjO\ 1kKBWApqpH1ve9XDQYN8zgxM4b16L21kpoWQnZtXrY3GZ4/it9kUgyB7+NwacIBlXa8cMDL7Q/69o\ -0d54U0X/NeX5QxuYR6OMJlrkQB7oiW/P/1mwjQgE=""" +0d54U0X/NeX5QxuYR6OMJlrkQB7oiW/P/1mwjQgE=""") class HostKeysTest (unittest.TestCase): @@ -68,7 +69,7 @@ class HostKeysTest (unittest.TestCase): self.assertEquals(1, len(list(hostdict.values())[0])) self.assertEquals(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp) + self.assertEquals(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) def test_2_add(self): hostdict = paramiko.HostKeys('hostfile.temp') @@ -78,7 +79,7 @@ class HostKeysTest (unittest.TestCase): self.assertEquals(3, len(list(hostdict))) x = hostdict['foo.example.com'] fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals('7EC91BB336CB6D810B124B1353C32396', fp) + self.assertEquals(b('7EC91BB336CB6D810B124B1353C32396'), fp) self.assert_(hostdict.check('foo.example.com', key)) def test_3_dict(self): @@ -90,7 +91,7 @@ class HostKeysTest (unittest.TestCase): x = hostdict.get('secure.example.com', None) self.assert_(x is not None) fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp) + self.assertEquals(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) i = 0 for key in hostdict: i += 1 @@ -112,6 +113,6 @@ class HostKeysTest (unittest.TestCase): self.assertEquals(1, len(list(hostdict.values())[1])) self.assertEquals(1, len(list(hostdict.values())[2])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals('7EC91BB336CB6D810B124B1353C32396', fp) + self.assertEquals(b('7EC91BB336CB6D810B124B1353C32396'), fp) fp = hexlify(hostdict['secure.example.com']['ssh-dss'].get_fingerprint()).upper() - self.assertEquals('4478F0B9A23CC5182009FF755BC1D26C', fp) + self.assertEquals(b('4478F0B9A23CC5182009FF755BC1D26C'), fp) diff --git a/tests/test_kex.py b/tests/test_kex.py index c94b777b..f7cb0647 100644 --- a/tests/test_kex.py +++ b/tests/test_kex.py @@ -40,7 +40,7 @@ class FakeKey (object): def asbytes(self): return b('fake-key') def sign_ssh_data(self, rng, H): - return 'fake-sig' + return b('fake-sig') class FakeModulusPack (object): @@ -91,7 +91,7 @@ class KexTest (unittest.TestCase): transport.server_mode = False kex = KexGroup1(transport) kex.start_kex() - x = '1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' + x = b('1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect) @@ -102,10 +102,10 @@ class KexTest (unittest.TestCase): msg.add_string('fake-sig') msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_REPLY, msg) - H = '03079780F3D3AD0B3C6DB30C8D21685F367A86D2' + H = b('03079780F3D3AD0B3C6DB30C8D21685F367A86D2') self.assertEquals(self.K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(('fake-host-key', 'fake-sig'), transport._verify) + self.assertEquals((b('fake-host-key'), b('fake-sig')), transport._verify) self.assert_(transport._activated) def test_2_group1_server(self): @@ -119,8 +119,8 @@ class KexTest (unittest.TestCase): msg.add_mpint(69) msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_INIT, msg) - H = 'B16BF34DD10945EDE84E9C1EF24A14BFDC843389' - x = '1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' + H = b('B16BF34DD10945EDE84E9C1EF24A14BFDC843389') + x = b('1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') self.assertEquals(self.K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) @@ -131,7 +131,7 @@ class KexTest (unittest.TestCase): transport.server_mode = False kex = KexGex(transport) kex.start_kex() - x = '22000004000000080000002000' + x = b('22000004000000080000002000') self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) @@ -140,7 +140,7 @@ class KexTest (unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = '20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' + x = b('20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) @@ -150,10 +150,10 @@ class KexTest (unittest.TestCase): msg.add_string('fake-sig') msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) - H = 'A265563F2FA87F1A89BF007EE90D58BE2E4A4BD0' + H = b('A265563F2FA87F1A89BF007EE90D58BE2E4A4BD0') self.assertEquals(self.K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(('fake-host-key', 'fake-sig'), transport._verify) + self.assertEquals((b('fake-host-key'), b('fake-sig')), transport._verify) self.assert_(transport._activated) def test_4_gex_old_client(self): @@ -161,7 +161,7 @@ class KexTest (unittest.TestCase): transport.server_mode = False kex = KexGex(transport) kex.start_kex(_test_old_style=True) - x = '1E00000800' + x = b('1E00000800') self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) @@ -170,7 +170,7 @@ class KexTest (unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = '20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' + x = b('20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) @@ -180,10 +180,10 @@ class KexTest (unittest.TestCase): msg.add_string('fake-sig') msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) - H = '807F87B269EF7AC5EC7E75676808776A27D5864C' + H = b('807F87B269EF7AC5EC7E75676808776A27D5864C') self.assertEquals(self.K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(('fake-host-key', 'fake-sig'), transport._verify) + self.assertEquals((b('fake-host-key'), b('fake-sig')), transport._verify) self.assert_(transport._activated) def test_5_gex_server(self): @@ -199,7 +199,7 @@ class KexTest (unittest.TestCase): msg.add_int(4096) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) - x = '1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102' + x = b('1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102') self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) @@ -208,8 +208,8 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 - H = 'CE754197C21BF3452863B4F44D0B3951F12516EF' - x = '210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' + H = b('CE754197C21BF3452863B4F44D0B3951F12516EF') + x = b('210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') self.assertEquals(K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) @@ -226,7 +226,7 @@ class KexTest (unittest.TestCase): msg.add_int(2048) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) - x = '1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102' + x = b('1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102') self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) @@ -235,8 +235,8 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 - H = 'B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B' - x = '210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' + H = b('B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B') + x = b('210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') self.assertEquals(K, transport._K) self.assertEquals(H, hexlify(transport._H).upper()) self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) diff --git a/tests/test_packetizer.py b/tests/test_packetizer.py index b53b741f..111ecb96 100644 --- a/tests/test_packetizer.py +++ b/tests/test_packetizer.py @@ -25,7 +25,15 @@ from tests.loop import LoopSocket from Crypto.Cipher import AES from Crypto.Hash import SHA, HMAC from paramiko import Message, Packetizer, util -from paramiko.py3compat import byte_chr +from paramiko.common import * + +if PY3: + x55 = b'\x55' + x1f = b'\x1f' +else: + x55 = '\x55' + x1f = '\x1f' + class PacketizerTest (unittest.TestCase): @@ -36,8 +44,8 @@ class PacketizerTest (unittest.TestCase): p = Packetizer(wsock) p.set_log(util.get_logger('paramiko.transport')) p.set_hexdump(True) - cipher = AES.new('\x00' * 16, AES.MODE_CBC, '\x55' * 16) - p.set_outbound_cipher(cipher, 16, SHA, 12, '\x1f' * 20) + cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16) + p.set_outbound_cipher(cipher, 16, SHA, 12, x1f * 20) # message has to be at least 16 bytes long, so we'll have at least one # block of data encrypted that contains zero random padding bytes @@ -50,8 +58,11 @@ class PacketizerTest (unittest.TestCase): data = rsock.recv(100) # 32 + 12 bytes of MAC = 44 self.assertEquals(44, len(data)) - self.assertEquals('\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0', data[:16]) - + if PY3: + self.assertEquals(b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0', data[:16]) + else: + self.assertEquals('\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0', data[:16]) + def test_2_read (self): rsock = LoopSocket() wsock = LoopSocket() @@ -59,11 +70,14 @@ class PacketizerTest (unittest.TestCase): p = Packetizer(rsock) p.set_log(util.get_logger('paramiko.transport')) p.set_hexdump(True) - cipher = AES.new('\x00' * 16, AES.MODE_CBC, '\x55' * 16) - p.set_inbound_cipher(cipher, 16, SHA, 12, '\x1f' * 20) - - wsock.send('C\x91\x97\xbd[P\xac%\x87\xc2\xc4k\xc7\xe98\xc0' + \ - '\x90\xd2\x16V\rqsa8|L=\xfb\x97}\xe2n\x03\xb1\xa0\xc2\x1c\xd6AAL\xb4Y') + cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16) + p.set_inbound_cipher(cipher, 16, SHA, 12, x1f * 20) + if PY3: + wsock.send(b'C\x91\x97\xbd[P\xac%\x87\xc2\xc4k\xc7\xe98\xc0' + \ + b'\x90\xd2\x16V\rqsa8|L=\xfb\x97}\xe2n\x03\xb1\xa0\xc2\x1c\xd6AAL\xb4Y') + else: + wsock.send('C\x91\x97\xbd[P\xac%\x87\xc2\xc4k\xc7\xe98\xc0' + \ + '\x90\xd2\x16V\rqsa8|L=\xfb\x97}\xe2n\x03\xb1\xa0\xc2\x1c\xd6AAL\xb4Y') cmd, m = p.read_message() self.assertEquals(100, cmd) self.assertEquals(100, m.get_int()) diff --git a/tests/test_pkey.py b/tests/test_pkey.py index c7240db3..b75f9a1e 100644 --- a/tests/test_pkey.py +++ b/tests/test_pkey.py @@ -23,7 +23,8 @@ Some unit tests for public/private key objects. from binascii import hexlify, unhexlify import unittest from paramiko import RSAKey, DSSKey, ECDSAKey, Message, util -from paramiko.common import rng, StringIO, byte_chr +from paramiko.common import rng, StringIO, byte_chr, b, PY3 +from tests.util import test_path # from openssh's ssh-keygen PUB_RSA = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEA049W6geFpmsljTwfvI1UmKWWJPNFI74+vNKTk4dmzkQY2yAMs6FhlvhlI8ysU4oj71ZsRYMecHbBbxdN79+JRFVYTKaLqjwGENeTd+yv4q+V2PvZv3fLnzApI3l7EJCqhWwJUHJ1jAkZzqDx0tyOL4uoZpww3nmE0kb3y21tH4c=' @@ -76,6 +77,12 @@ ADRvOqQ5R98Sxst765CAqXmRtz8vwoD96g== -----END EC PRIVATE KEY----- """ +if PY3: + x1234 = b'\x01\x02\x03\x04' +else: + x1234 = '\x01\x02\x03\x04' + + class KeyTest (unittest.TestCase): def setUp(self): @@ -86,14 +93,14 @@ class KeyTest (unittest.TestCase): def test_1_generate_key_bytes(self): from Crypto.Hash import MD5 - key = util.generate_key_bytes(MD5, '\x01\x02\x03\x04', 'happy birthday', 30) + key = util.generate_key_bytes(MD5, x1234, 'happy birthday', 30) exp = unhexlify('61E1F272F4C1C4561586BD322498C0E924672780F47BB37DDA7D54019E64') self.assertEquals(exp, key) def test_2_load_rsa(self): - key = RSAKey.from_private_key_file('tests/test_rsa.key') + key = RSAKey.from_private_key_file(test_path('test_rsa.key')) self.assertEquals('ssh-rsa', key.get_name()) - exp_rsa = FINGER_RSA.split()[1].replace(':', '') + exp_rsa = b(FINGER_RSA.split()[1].replace(':', '')) my_rsa = hexlify(key.get_fingerprint()) self.assertEquals(exp_rsa, my_rsa) self.assertEquals(PUB_RSA.split()[1], key.get_base64()) @@ -107,18 +114,18 @@ class KeyTest (unittest.TestCase): self.assertEquals(key, key2) def test_3_load_rsa_password(self): - key = RSAKey.from_private_key_file('tests/test_rsa_password.key', 'television') + key = RSAKey.from_private_key_file(test_path('test_rsa_password.key'), 'television') self.assertEquals('ssh-rsa', key.get_name()) - exp_rsa = FINGER_RSA.split()[1].replace(':', '') + exp_rsa = b(FINGER_RSA.split()[1].replace(':', '')) my_rsa = hexlify(key.get_fingerprint()) self.assertEquals(exp_rsa, my_rsa) self.assertEquals(PUB_RSA.split()[1], key.get_base64()) self.assertEquals(1024, key.get_bits()) def test_4_load_dss(self): - key = DSSKey.from_private_key_file('tests/test_dss.key') + key = DSSKey.from_private_key_file(test_path('test_dss.key')) self.assertEquals('ssh-dss', key.get_name()) - exp_dss = FINGER_DSS.split()[1].replace(':', '') + exp_dss = b(FINGER_DSS.split()[1].replace(':', '')) my_dss = hexlify(key.get_fingerprint()) self.assertEquals(exp_dss, my_dss) self.assertEquals(PUB_DSS.split()[1], key.get_base64()) @@ -132,9 +139,9 @@ class KeyTest (unittest.TestCase): self.assertEquals(key, key2) def test_5_load_dss_password(self): - key = DSSKey.from_private_key_file('tests/test_dss_password.key', 'television') + key = DSSKey.from_private_key_file(test_path('test_dss_password.key'), 'television') self.assertEquals('ssh-dss', key.get_name()) - exp_dss = FINGER_DSS.split()[1].replace(':', '') + exp_dss = b(FINGER_DSS.split()[1].replace(':', '')) my_dss = hexlify(key.get_fingerprint()) self.assertEquals(exp_dss, my_dss) self.assertEquals(PUB_DSS.split()[1], key.get_base64()) @@ -142,7 +149,7 @@ class KeyTest (unittest.TestCase): def test_6_compare_rsa(self): # verify that the private & public keys compare equal - key = RSAKey.from_private_key_file('tests/test_rsa.key') + key = RSAKey.from_private_key_file(test_path('test_rsa.key')) self.assertEquals(key, key) pub = RSAKey(data=key.asbytes()) self.assert_(key.can_sign()) @@ -151,7 +158,7 @@ class KeyTest (unittest.TestCase): def test_7_compare_dss(self): # verify that the private & public keys compare equal - key = DSSKey.from_private_key_file('tests/test_dss.key') + key = DSSKey.from_private_key_file(test_path('test_dss.key')) self.assertEquals(key, key) pub = DSSKey(data=key.asbytes()) self.assert_(key.can_sign()) @@ -160,8 +167,8 @@ class KeyTest (unittest.TestCase): def test_8_sign_rsa(self): # verify that the rsa private key can sign and verify - key = RSAKey.from_private_key_file('tests/test_rsa.key') - msg = key.sign_ssh_data(rng, 'ice weasels') + key = RSAKey.from_private_key_file(test_path('test_rsa.key')) + msg = key.sign_ssh_data(rng, b('ice weasels')) self.assert_(type(msg) is Message) msg.rewind() self.assertEquals('ssh-rsa', msg.get_text()) @@ -169,12 +176,12 @@ class KeyTest (unittest.TestCase): self.assertEquals(sig, msg.get_binary()) msg.rewind() pub = RSAKey(data=key.asbytes()) - self.assert_(pub.verify_ssh_sig('ice weasels', msg)) + self.assert_(pub.verify_ssh_sig(b('ice weasels'), msg)) def test_9_sign_dss(self): # verify that the dss private key can sign and verify - key = DSSKey.from_private_key_file('tests/test_dss.key') - msg = key.sign_ssh_data(rng, 'ice weasels') + key = DSSKey.from_private_key_file(test_path('test_dss.key')) + msg = key.sign_ssh_data(rng, b('ice weasels')) self.assert_(type(msg) is Message) msg.rewind() self.assertEquals('ssh-dss', msg.get_text()) @@ -184,24 +191,24 @@ class KeyTest (unittest.TestCase): self.assertEquals(40, len(msg.get_binary())) msg.rewind() pub = DSSKey(data=key.asbytes()) - self.assert_(pub.verify_ssh_sig('ice weasels', msg)) + self.assert_(pub.verify_ssh_sig(b('ice weasels'), msg)) def test_A_generate_rsa(self): key = RSAKey.generate(1024) - msg = key.sign_ssh_data(rng, 'jerri blank') + msg = key.sign_ssh_data(rng, b('jerri blank')) msg.rewind() - self.assert_(key.verify_ssh_sig('jerri blank', msg)) + self.assert_(key.verify_ssh_sig(b('jerri blank'), msg)) def test_B_generate_dss(self): key = DSSKey.generate(1024) - msg = key.sign_ssh_data(rng, 'jerri blank') + msg = key.sign_ssh_data(rng, b('jerri blank')) msg.rewind() - self.assert_(key.verify_ssh_sig('jerri blank', msg)) + self.assert_(key.verify_ssh_sig(b('jerri blank'), msg)) def test_10_load_ecdsa(self): - key = ECDSAKey.from_private_key_file('tests/test_ecdsa.key') + key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) self.assertEquals('ecdsa-sha2-nistp256', key.get_name()) - exp_ecdsa = FINGER_ECDSA.split()[1].replace(':', '') + exp_ecdsa = b(FINGER_ECDSA.split()[1].replace(':', '')) my_ecdsa = hexlify(key.get_fingerprint()) self.assertEquals(exp_ecdsa, my_ecdsa) self.assertEquals(PUB_ECDSA.split()[1], key.get_base64()) @@ -215,9 +222,9 @@ class KeyTest (unittest.TestCase): self.assertEquals(key, key2) def test_11_load_ecdsa_password(self): - key = ECDSAKey.from_private_key_file('tests/test_ecdsa_password.key', 'television') + key = ECDSAKey.from_private_key_file(test_path('test_ecdsa_password.key'), b('television')) self.assertEquals('ecdsa-sha2-nistp256', key.get_name()) - exp_ecdsa = FINGER_ECDSA.split()[1].replace(':', '') + exp_ecdsa = b(FINGER_ECDSA.split()[1].replace(':', '')) my_ecdsa = hexlify(key.get_fingerprint()) self.assertEquals(exp_ecdsa, my_ecdsa) self.assertEquals(PUB_ECDSA.split()[1], key.get_base64()) @@ -225,7 +232,7 @@ class KeyTest (unittest.TestCase): def test_12_compare_ecdsa(self): # verify that the private & public keys compare equal - key = ECDSAKey.from_private_key_file('tests/test_ecdsa.key') + key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) self.assertEquals(key, key) pub = ECDSAKey(data=key.asbytes()) self.assert_(key.can_sign()) @@ -234,8 +241,8 @@ class KeyTest (unittest.TestCase): def test_13_sign_ecdsa(self): # verify that the rsa private key can sign and verify - key = ECDSAKey.from_private_key_file('tests/test_ecdsa.key') - msg = key.sign_ssh_data(rng, 'ice weasels') + key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) + msg = key.sign_ssh_data(rng, b('ice weasels')) self.assert_(type(msg) is Message) msg.rewind() self.assertEquals('ecdsa-sha2-nistp256', msg.get_text()) @@ -246,4 +253,4 @@ class KeyTest (unittest.TestCase): msg.rewind() pub = ECDSAKey(data=key.asbytes()) - self.assert_(pub.verify_ssh_sig('ice weasels', msg)) + self.assert_(pub.verify_ssh_sig(b('ice weasels'), msg)) diff --git a/tests/test_util.py b/tests/test_util.py index 858dedba..84d5e88e 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -27,7 +27,7 @@ import unittest from Crypto.Hash import SHA import paramiko.util from paramiko.util import lookup_ssh_host_config as host_config -from paramiko.py3compat import StringIO, byte_ord +from paramiko.py3compat import StringIO, byte_ord, b from tests.util import ParamikoTest @@ -137,7 +137,7 @@ class UtilTest(ParamikoTest): ) def test_4_generate_key_bytes(self): - x = paramiko.util.generate_key_bytes(SHA, 'ABCDEFGH', 'This is my secret passphrase.', 64) + x = paramiko.util.generate_key_bytes(SHA, b('ABCDEFGH'), 'This is my secret passphrase.', 64) hex = ''.join(['%02x' % byte_ord(c) for c in x]) self.assertEquals(hex, '9110e2f6793b69363e58173e9436b13a5a4b339005741d5c680e505f57d871347b4239f14fb5c46e857d5e100424873ba849ac699cea98d729e57b3e84378e8b') @@ -151,7 +151,7 @@ class UtilTest(ParamikoTest): self.assertEquals(1, len(list(hostdict.values())[0])) self.assertEquals(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals('E6684DB30E109B67B70FF1DC5C7F1363', fp) + self.assertEquals(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) finally: os.unlink('hostfile.temp') -- cgit v1.2.3 From 8a7267beeb3435fa16c06d22c201650e1e593d89 Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Fri, 1 Nov 2013 00:37:11 -0700 Subject: Eliminate all uses of b'' syntax to allow for Python 2.5 support --- paramiko/common.py | 16 ++++++---------- paramiko/ecdsakey.py | 11 +++-------- paramiko/py3compat.py | 4 +++- paramiko/rsakey.py | 30 ++++++++++-------------------- tests/test_message.py | 15 +++++---------- tests/test_packetizer.py | 21 +++++---------------- tests/test_pkey.py | 7 ++----- tests/test_transport.py | 2 +- 8 files changed, 35 insertions(+), 71 deletions(-) (limited to 'tests/test_packetizer.py') diff --git a/paramiko/common.py b/paramiko/common.py index 5d7ab313..37d5ee89 100644 --- a/paramiko/common.py +++ b/paramiko/common.py @@ -123,19 +123,15 @@ else: import logging PY22 = False +zero_byte = byte_chr(0) +one_byte = byte_chr(1) +four_byte = byte_chr(4) +max_byte = byte_chr(0xff) +newline_byte = byte_chr(10) + if PY3: - zero_byte = b'\x00' - one_byte = b'\x01' - four_byte = b'\x04' - max_byte = b'\xff' - newline_byte = b'\n' cr_byte = 13 else: - zero_byte = '\x00' - one_byte = '\x01' - four_byte = '\x04' - max_byte = '\xff' - newline_byte = '\n' cr_byte = '\r' diff --git a/paramiko/ecdsakey.py b/paramiko/ecdsakey.py index d15b2ac7..8585e6f7 100644 --- a/paramiko/ecdsakey.py +++ b/paramiko/ecdsakey.py @@ -21,6 +21,7 @@ L{ECDSAKey} """ import binascii +from binascii import unhexlify from ecdsa import SigningKey, VerifyingKey, der, curves from ecdsa.util import number_to_string, sigencode_string, sigencode_strings, sigdecode_strings from Crypto.Hash import SHA256, MD5 @@ -157,14 +158,8 @@ class ECDSAKey (PKey): data = self._read_private_key('EC', file_obj, password) self._decode_key(data) - if PY3: - ALLOWED_PADDINGS = [b'\x01', b'\x02\x02', b'\x03\x03\x03', b'\x04\x04\x04\x04', - b'\x05\x05\x05\x05\x05', b'\x06\x06\x06\x06\x06\x06', - b'\x07\x07\x07\x07\x07\x07\x07'] - else: - ALLOWED_PADDINGS = ['\x01', '\x02\x02', '\x03\x03\x03', '\x04\x04\x04\x04', - '\x05\x05\x05\x05\x05', '\x06\x06\x06\x06\x06\x06', - '\x07\x07\x07\x07\x07\x07\x07'] + 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: diff --git a/paramiko/py3compat.py b/paramiko/py3compat.py index fd6488d8..8a01ba08 100644 --- a/paramiko/py3compat.py +++ b/paramiko/py3compat.py @@ -1,6 +1,6 @@ import sys -__all__ = ['PY3', 'string_types', 'integer_types', 'text_type', 'bytes_types', 'long', 'input', 'bytestring', 'byte_ord', 'byte_chr', 'byte_mask', 'b', 'u', 'b2s', 'StringIO', 'BytesIO', 'is_callable', 'MAXSIZE', 'next'] +__all__ = ['PY3', 'string_types', 'integer_types', 'text_type', 'bytes_types', 'bytes', 'long', 'input', 'bytestring', 'byte_ord', 'byte_chr', 'byte_mask', 'b', 'u', 'b2s', 'StringIO', 'BytesIO', 'is_callable', 'MAXSIZE', 'next'] PY3 = sys.version_info[0] >= 3 @@ -9,6 +9,7 @@ if PY3: import struct string_types = str text_type = str + bytes = bytes bytes_types = bytes integer_types = int long = int @@ -67,6 +68,7 @@ else: string_types = basestring text_type = unicode bytes_types = str + bytes = str integer_types = (int, long) long = long input = raw_input diff --git a/paramiko/rsakey.py b/paramiko/rsakey.py index 90945031..4bc94e0b 100644 --- a/paramiko/rsakey.py +++ b/paramiko/rsakey.py @@ -20,6 +20,7 @@ L{RSAKey} """ +from binascii import unhexlify from Crypto.PublicKey import RSA from Crypto.Hash import SHA, MD5 from Crypto.Cipher import DES3 @@ -152,26 +153,15 @@ class RSAKey (PKey): ### internals... - if PY3: - def _pkcs1imify(self, data): - """ - turn a 20-byte SHA1 hash into a blob of data as large as the key's N, - using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. - """ - SHA1_DIGESTINFO = b'\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' - size = len(util.deflate_long(self.n, 0)) - filler = b'\xff' * (size - len(SHA1_DIGESTINFO) - len(data) - 3) - return b'\x00\x01' + filler + b'\x00' + SHA1_DIGESTINFO + data - else: - def _pkcs1imify(self, data): - """ - turn a 20-byte SHA1 hash into a blob of data as large as the key's N, - using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. - """ - SHA1_DIGESTINFO = b('\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14') - size = len(util.deflate_long(self.n, 0)) - filler = b('\xff') * (size - len(SHA1_DIGESTINFO) - len(data) - 3) - return b('\x00\x01') + filler + b('\x00') + SHA1_DIGESTINFO + b(data) + def _pkcs1imify(self, data): + """ + turn a 20-byte SHA1 hash into a blob of data as large as the key's N, + using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. + """ + SHA1_DIGESTINFO = unhexlify('3021300906052b0e03021a05000414') + size = len(util.deflate_long(self.n, 0)) + filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) - 3) + return zero_byte + one_byte + filler + zero_byte + SHA1_DIGESTINFO + data def _from_private_key_file(self, filename, password): data = self._read_private_key_file('RSA', filename, password) diff --git a/tests/test_message.py b/tests/test_message.py index 2580115e..dde694f7 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -21,22 +21,17 @@ Some unit tests for ssh protocol message blocks. """ import unittest +from binascii import unhexlify from paramiko.message import Message from paramiko.common import * class MessageTest (unittest.TestCase): - if PY3: - __a = b'\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01q\x00\x00\x00\x05hello\x00\x00\x03\xe8' + (b'x' * 1000) - __b = b'\x01\x00\xf3\x00\x3f\x00\x00\x00\x10huey,dewey,louie' - __c = b'\x00\x00\x00\x05\xff\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7' - __d = b'\x00\x00\x00\x05\xff\x00\x00\x00\x05\x11\x22\x33\x44\x55\xff\x00\x00\x00\x0a\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03cat\x00\x00\x00\x03a,b' - else: - __a = '\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01q\x00\x00\x00\x05hello\x00\x00\x03\xe8' + ('x' * 1000) - __b = '\x01\x00\xf3\x00\x3f\x00\x00\x00\x10huey,dewey,louie' - __c = '\x00\x00\x00\x05\xff\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7' - __d = '\x00\x00\x00\x05\xff\x00\x00\x00\x05\x11\x22\x33\x44\x55\xff\x00\x00\x00\x0a\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03cat\x00\x00\x00\x03a,b' + __a = unhexlify('000000170760e09000000001710000000568656c6c6f000003e8') + (b('x') * 1000) + __b = unhexlify('0100f3003f00000010687565792c64657765792c6c6f756965') + __c = unhexlify('00000005ff0000000700f5e4d3c2b10900000001110000000700f5e4d3c2b109000000069a1b2c3d4ef7') + __d = unhexlify('00000005ff000000051122334455ff0000000a00f00000000000000000010000000363617400000003612c62') def test_1_encode(self): msg = Message() diff --git a/tests/test_packetizer.py b/tests/test_packetizer.py index 111ecb96..b0e8fd42 100644 --- a/tests/test_packetizer.py +++ b/tests/test_packetizer.py @@ -21,18 +21,15 @@ Some unit tests for the ssh2 protocol in Transport. """ import unittest +from binascii import unhexlify from tests.loop import LoopSocket from Crypto.Cipher import AES from Crypto.Hash import SHA, HMAC from paramiko import Message, Packetizer, util from paramiko.common import * -if PY3: - x55 = b'\x55' - x1f = b'\x1f' -else: - x55 = '\x55' - x1f = '\x1f' +x55 = byte_chr(0x55) +x1f = byte_chr(0x1f) class PacketizerTest (unittest.TestCase): @@ -58,10 +55,7 @@ class PacketizerTest (unittest.TestCase): data = rsock.recv(100) # 32 + 12 bytes of MAC = 44 self.assertEquals(44, len(data)) - if PY3: - self.assertEquals(b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0', data[:16]) - else: - self.assertEquals('\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0', data[:16]) + self.assertEquals(unhexlify('439197bd5b50ac2587c2c46bc7e938c0'), data[:16]) def test_2_read (self): rsock = LoopSocket() @@ -72,12 +66,7 @@ class PacketizerTest (unittest.TestCase): p.set_hexdump(True) cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16) p.set_inbound_cipher(cipher, 16, SHA, 12, x1f * 20) - if PY3: - wsock.send(b'C\x91\x97\xbd[P\xac%\x87\xc2\xc4k\xc7\xe98\xc0' + \ - b'\x90\xd2\x16V\rqsa8|L=\xfb\x97}\xe2n\x03\xb1\xa0\xc2\x1c\xd6AAL\xb4Y') - else: - wsock.send('C\x91\x97\xbd[P\xac%\x87\xc2\xc4k\xc7\xe98\xc0' + \ - '\x90\xd2\x16V\rqsa8|L=\xfb\x97}\xe2n\x03\xb1\xa0\xc2\x1c\xd6AAL\xb4Y') + wsock.send(unhexlify('439197bd5b50ac2587c2c46bc7e938c090d216560d717361387c4c3dfb977de26e03b1a0c21cd641414cb459')) cmd, m = p.read_message() self.assertEquals(100, cmd) self.assertEquals(100, m.get_int()) diff --git a/tests/test_pkey.py b/tests/test_pkey.py index b75f9a1e..00001600 100644 --- a/tests/test_pkey.py +++ b/tests/test_pkey.py @@ -23,7 +23,7 @@ Some unit tests for public/private key objects. from binascii import hexlify, unhexlify import unittest from paramiko import RSAKey, DSSKey, ECDSAKey, Message, util -from paramiko.common import rng, StringIO, byte_chr, b, PY3 +from paramiko.common import rng, StringIO, byte_chr, b, PY3, bytes from tests.util import test_path # from openssh's ssh-keygen @@ -77,10 +77,7 @@ ADRvOqQ5R98Sxst765CAqXmRtz8vwoD96g== -----END EC PRIVATE KEY----- """ -if PY3: - x1234 = b'\x01\x02\x03\x04' -else: - x1234 = '\x01\x02\x03\x04' +x1234 = unhexlify('01020304') class KeyTest (unittest.TestCase): diff --git a/tests/test_transport.py b/tests/test_transport.py index 230f4a28..f60c2949 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -33,7 +33,7 @@ from paramiko import Transport, SecurityOptions, ServerInterface, RSAKey, DSSKey SSHException, BadAuthenticationType, InteractiveQuery, ChannelException from paramiko import AUTH_FAILED, AUTH_PARTIALLY_SUCCESSFUL, AUTH_SUCCESSFUL from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED -from paramiko.common import MSG_KEXINIT, MSG_CHANNEL_WINDOW_ADJUST, b +from paramiko.common import MSG_KEXINIT, MSG_CHANNEL_WINDOW_ADJUST, b, bytes from paramiko.message import Message from tests.loop import LoopSocket from tests.util import ParamikoTest, test_path -- cgit v1.2.3 From fee18142a58dce099dd7a9bcb93d124a539cc55c Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Fri, 1 Nov 2013 00:51:00 -0700 Subject: Fixes for Python 2.5 and Python 3.2 support --- paramiko/pkey.py | 2 +- paramiko/rsakey.py | 2 +- tests/test_auth.py | 6 ++---- tests/test_message.py | 8 ++++---- tests/test_packetizer.py | 4 ++-- tests/test_pkey.py | 4 ++-- tests/test_sftp.py | 5 +---- tests/test_transport.py | 2 +- 8 files changed, 14 insertions(+), 19 deletions(-) (limited to 'tests/test_packetizer.py') diff --git a/paramiko/pkey.py b/paramiko/pkey.py index 4cead1c2..53361d02 100644 --- a/paramiko/pkey.py +++ b/paramiko/pkey.py @@ -330,7 +330,7 @@ class PKey (object): cipher = self._CIPHER_TABLE[encryption_type]['cipher'] keysize = self._CIPHER_TABLE[encryption_type]['keysize'] mode = self._CIPHER_TABLE[encryption_type]['mode'] - salt = unhexlify(saltstr) + salt = unhexlify(b(saltstr)) key = util.generate_key_bytes(MD5, salt, password, keysize) return cipher.new(key, mode, salt).decrypt(data) diff --git a/paramiko/rsakey.py b/paramiko/rsakey.py index 4bc94e0b..b4222a35 100644 --- a/paramiko/rsakey.py +++ b/paramiko/rsakey.py @@ -158,7 +158,7 @@ class RSAKey (PKey): turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. """ - SHA1_DIGESTINFO = unhexlify('3021300906052b0e03021a05000414') + SHA1_DIGESTINFO = unhexlify(b('3021300906052b0e03021a05000414')) size = len(util.deflate_long(self.n, 0)) filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) - 3) return zero_byte + one_byte + filler + zero_byte + SHA1_DIGESTINFO + data diff --git a/tests/test_auth.py b/tests/test_auth.py index 5fd0bf5d..586289ba 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -29,13 +29,11 @@ from paramiko import Transport, ServerInterface, RSAKey, DSSKey, \ AuthenticationException from paramiko import AUTH_FAILED, AUTH_PARTIALLY_SUCCESSFUL, AUTH_SUCCESSFUL from paramiko import OPEN_SUCCEEDED, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED +from paramiko.py3compat import u from tests.loop import LoopSocket from tests.util import test_path -try: - _pwd = u'\u2022' -except Exception: - _pwd = '\u2022' +_pwd = u('\u2022') class NullServer (ServerInterface): diff --git a/tests/test_message.py b/tests/test_message.py index dde694f7..0aed88c2 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -28,10 +28,10 @@ from paramiko.common import * class MessageTest (unittest.TestCase): - __a = unhexlify('000000170760e09000000001710000000568656c6c6f000003e8') + (b('x') * 1000) - __b = unhexlify('0100f3003f00000010687565792c64657765792c6c6f756965') - __c = unhexlify('00000005ff0000000700f5e4d3c2b10900000001110000000700f5e4d3c2b109000000069a1b2c3d4ef7') - __d = unhexlify('00000005ff000000051122334455ff0000000a00f00000000000000000010000000363617400000003612c62') + __a = unhexlify(b('000000170760e09000000001710000000568656c6c6f000003e8')) + (b('x') * 1000) + __b = unhexlify(b('0100f3003f00000010687565792c64657765792c6c6f756965')) + __c = unhexlify(b('00000005ff0000000700f5e4d3c2b10900000001110000000700f5e4d3c2b109000000069a1b2c3d4ef7')) + __d = unhexlify(b('00000005ff000000051122334455ff0000000a00f00000000000000000010000000363617400000003612c62')) def test_1_encode(self): msg = Message() diff --git a/tests/test_packetizer.py b/tests/test_packetizer.py index b0e8fd42..a4ada72f 100644 --- a/tests/test_packetizer.py +++ b/tests/test_packetizer.py @@ -55,7 +55,7 @@ class PacketizerTest (unittest.TestCase): data = rsock.recv(100) # 32 + 12 bytes of MAC = 44 self.assertEquals(44, len(data)) - self.assertEquals(unhexlify('439197bd5b50ac2587c2c46bc7e938c0'), data[:16]) + self.assertEquals(unhexlify(b('439197bd5b50ac2587c2c46bc7e938c0')), data[:16]) def test_2_read (self): rsock = LoopSocket() @@ -66,7 +66,7 @@ class PacketizerTest (unittest.TestCase): p.set_hexdump(True) cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16) p.set_inbound_cipher(cipher, 16, SHA, 12, x1f * 20) - wsock.send(unhexlify('439197bd5b50ac2587c2c46bc7e938c090d216560d717361387c4c3dfb977de26e03b1a0c21cd641414cb459')) + wsock.send(unhexlify(b('439197bd5b50ac2587c2c46bc7e938c090d216560d717361387c4c3dfb977de26e03b1a0c21cd641414cb459'))) cmd, m = p.read_message() self.assertEquals(100, cmd) self.assertEquals(100, m.get_int()) diff --git a/tests/test_pkey.py b/tests/test_pkey.py index 00001600..8ab21a3a 100644 --- a/tests/test_pkey.py +++ b/tests/test_pkey.py @@ -77,7 +77,7 @@ ADRvOqQ5R98Sxst765CAqXmRtz8vwoD96g== -----END EC PRIVATE KEY----- """ -x1234 = unhexlify('01020304') +x1234 = unhexlify(b('01020304')) class KeyTest (unittest.TestCase): @@ -91,7 +91,7 @@ class KeyTest (unittest.TestCase): def test_1_generate_key_bytes(self): from Crypto.Hash import MD5 key = util.generate_key_bytes(MD5, x1234, 'happy birthday', 30) - exp = unhexlify('61E1F272F4C1C4561586BD322498C0E924672780F47BB37DDA7D54019E64') + exp = unhexlify(b('61E1F272F4C1C4561586BD322498C0E924672780F47BB37DDA7D54019E64')) self.assertEquals(exp, key) def test_2_load_rsa(self): diff --git a/tests/test_sftp.py b/tests/test_sftp.py index 64c727a6..2b434f8e 100755 --- a/tests/test_sftp.py +++ b/tests/test_sftp.py @@ -72,10 +72,7 @@ FOLDER = os.environ.get('TEST_FOLDER', 'temp-testing000') sftp = None tc = None g_big_file_test = True -try: - unicode_folder = u'\u00fcnic\u00f8de' -except SyntaxError: - unicode_folder = '\u00fcnic\u00f8de' +unicode_folder = u('\u00fcnic\u00f8de') def get_sftp(): global sftp diff --git a/tests/test_transport.py b/tests/test_transport.py index f60c2949..22a02a8e 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -159,7 +159,7 @@ class TransportTest(ParamikoTest): def test_2_compute_key(self): self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929 - self.tc.H = unhexlify('0C8307CDE6856FF30BA93684EB0F04C2520E9ED3') + self.tc.H = unhexlify(b('0C8307CDE6856FF30BA93684EB0F04C2520E9ED3')) self.tc.session_id = self.tc.H key = self.tc._compute_key('C', 32) self.assertEquals(b('207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995'), -- cgit v1.2.3 From 7444a999931cddc1e61bb35270468aa45da2687e Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Sat, 2 Nov 2013 20:18:18 -0700 Subject: Fix some deprecation and resource warnings --- demos/demo_server.py | 4 +- demos/demo_sftp.py | 8 +- paramiko/hostkeys.py | 50 +++++++------ paramiko/pkey.py | 22 +++--- paramiko/primes.py | 20 ++--- paramiko/py3compat.py | 12 ++- tests/test_auth.py | 34 ++++----- tests/test_buffered_pipe.py | 28 +++---- tests/test_client.py | 60 +++++++-------- tests/test_file.py | 12 +-- tests/test_hostkeys.py | 48 ++++++------ tests/test_kex.py | 82 ++++++++++----------- tests/test_message.py | 54 +++++++------- tests/test_packetizer.py | 12 +-- tests/test_pkey.py | 112 ++++++++++++++-------------- tests/test_sftp.py | 4 +- tests/test_sftp_big.py | 1 + tests/test_transport.py | 176 ++++++++++++++++++++++---------------------- tests/test_util.py | 34 ++++----- 19 files changed, 398 insertions(+), 375 deletions(-) (limited to 'tests/test_packetizer.py') diff --git a/demos/demo_server.py b/demos/demo_server.py index deb21387..5a41a714 100644 --- a/demos/demo_server.py +++ b/demos/demo_server.py @@ -27,7 +27,7 @@ import threading import traceback import paramiko -from paramiko.py3compat import b, u +from paramiko.py3compat import b, u, decodebytes # setup logging @@ -46,7 +46,7 @@ class Server (paramiko.ServerInterface): 'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC' + \ 'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT' + \ 'UWT10hcuO4Ks8=') - good_pub_key = paramiko.RSAKey(data=base64.decodestring(data)) + good_pub_key = paramiko.RSAKey(data=decodebytes(data)) def __init__(self): self.event = threading.Event() diff --git a/demos/demo_sftp.py b/demos/demo_sftp.py index 2dba1722..d7f28084 100755 --- a/demos/demo_sftp.py +++ b/demos/demo_sftp.py @@ -20,6 +20,8 @@ # based on code provided by raymond mosteller (thanks!) +from __future__ import with_statement + import base64 import getpass import os @@ -95,13 +97,15 @@ try: except IOError: print('(assuming demo_sftp_folder/ already exists)') sftp.open('demo_sftp_folder/README', 'w').write('This was created by demo_sftp.py.\n') - data = open('demo_sftp.py', 'r').read() + with open('demo_sftp.py', 'r') as f: + data = f.read() sftp.open('demo_sftp_folder/demo_sftp.py', 'w').write(data) print('created demo_sftp_folder/ on the server') # copy the README back here data = sftp.open('demo_sftp_folder/README', 'r').read() - open('README_demo_sftp', 'w').write(data) + with open('README_demo_sftp', 'w') as f: + f.write(data) print('copied README back here') # BETTER: use the get() and put() methods diff --git a/paramiko/hostkeys.py b/paramiko/hostkeys.py index a7f9b430..9da883e6 100644 --- a/paramiko/hostkeys.py +++ b/paramiko/hostkeys.py @@ -83,11 +83,11 @@ class HostKeyEntry: try: key = b(key) if keytype == 'ssh-rsa': - key = RSAKey(data=base64.decodestring(key)) + key = RSAKey(data=decodebytes(key)) elif keytype == 'ssh-dss': - key = DSSKey(data=base64.decodestring(key)) + key = DSSKey(data=decodebytes(key)) elif keytype == 'ecdsa-sha2-nistp256': - key = ECDSAKey(data=base64.decodestring(key)) + key = ECDSAKey(data=decodebytes(key)) else: log.info("Unable to handle key of type %s" % (keytype,)) return None @@ -173,19 +173,21 @@ class HostKeys (MutableMapping): @raise IOError: if there was an error reading the file """ f = open(filename, 'r') - for lineno, line in enumerate(f): - line = line.strip() - if (len(line) == 0) or (line[0] == '#'): - continue - e = HostKeyEntry.from_line(line, lineno) - if e is not None: - _hostnames = e.hostnames - for h in _hostnames: - if self.check(h, e.key): - e.hostnames.remove(h) - if len(e.hostnames): - self._entries.append(e) - f.close() + try: + for lineno, line in enumerate(f): + line = line.strip() + if (len(line) == 0) or (line[0] == '#'): + continue + e = HostKeyEntry.from_line(line, lineno) + if e is not None: + _hostnames = e.hostnames + for h in _hostnames: + if self.check(h, e.key): + e.hostnames.remove(h) + if len(e.hostnames): + self._entries.append(e) + finally: + f.close() def save(self, filename): """ @@ -202,11 +204,13 @@ class HostKeys (MutableMapping): @since: 1.6.1 """ f = open(filename, 'w') - for e in self._entries: - line = e.to_line() - if line: - f.write(line) - f.close() + try: + for e in self._entries: + line = e.to_line() + if line: + f.write(line) + finally: + f.close() def lookup(self, hostname): """ @@ -362,10 +366,10 @@ class HostKeys (MutableMapping): else: if salt.startswith('|1|'): salt = salt.split('|')[2] - salt = base64.decodestring(b(salt)) + salt = decodebytes(b(salt)) assert len(salt) == SHA.digest_size hmac = HMAC.HMAC(salt, b(hostname), SHA).digest() - hostkey = '|1|%s|%s' % (u(base64.encodestring(salt)), u(base64.encodestring(hmac))) + hostkey = '|1|%s|%s' % (u(encodebytes(salt)), u(encodebytes(hmac))) return hostkey.replace('\n', '') hash_host = staticmethod(hash_host) diff --git a/paramiko/pkey.py b/paramiko/pkey.py index 53361d02..3d786aec 100644 --- a/paramiko/pkey.py +++ b/paramiko/pkey.py @@ -148,7 +148,7 @@ class PKey (object): @return: a base64 string containing the public part of the key. @rtype: str """ - return u(base64.encodestring(self.asbytes())).replace('\n', '') + return u(encodebytes(self.asbytes())).replace('\n', '') def sign_ssh_data(self, rng, data): """ @@ -283,8 +283,10 @@ class PKey (object): @raise SSHException: if the key file is invalid. """ f = open(filename, 'r') - data = self._read_private_key(tag, f, password) - f.close() + try: + data = self._read_private_key(tag, f, password) + finally: + f.close() return data def _read_private_key(self, tag, f, password=None): @@ -309,7 +311,7 @@ class PKey (object): end += 1 # if we trudged to the end of the file, just try to cope. try: - data = base64.decodestring(b(''.join(lines[start:end]))) + data = decodebytes(b(''.join(lines[start:end]))) except base64.binascii.Error: raise SSHException('base64 decoding error: ' + str(sys.exc_info()[1])) if 'proc-type' not in headers: @@ -353,10 +355,12 @@ class PKey (object): @raise IOError: if there was an error writing the file. """ f = open(filename, 'w', o600) - # grrr... the mode doesn't always take hold - os.chmod(filename, o600) - self._write_private_key(tag, f, data, password) - f.close() + try: + # grrr... the mode doesn't always take hold + os.chmod(filename, o600) + self._write_private_key(tag, f, data, password) + finally: + f.close() def _write_private_key(self, tag, f, data, password=None): f.write('-----BEGIN %s PRIVATE KEY-----\n' % tag) @@ -378,7 +382,7 @@ class PKey (object): f.write('Proc-Type: 4,ENCRYPTED\n') f.write('DEK-Info: %s,%s\n' % (cipher_name, u(hexlify(salt)).upper())) f.write('\n') - s = u(base64.encodestring(data)) + s = u(encodebytes(data)) # re-wrap to 64-char lines s = ''.join(s.split('\n')) s = '\n'.join([s[i : i+64] for i in range(0, len(s), 64)]) diff --git a/paramiko/primes.py b/paramiko/primes.py index 4db6d52d..13ec52d0 100644 --- a/paramiko/primes.py +++ b/paramiko/primes.py @@ -114,15 +114,17 @@ class ModulusPack (object): """ self.pack = {} f = open(filename, 'r') - for line in f: - line = line.strip() - if (len(line) == 0) or (line[0] == '#'): - continue - try: - self._parse_modulus(line) - except: - continue - f.close() + try: + for line in f: + line = line.strip() + if (len(line) == 0) or (line[0] == '#'): + continue + try: + self._parse_modulus(line) + except: + continue + finally: + f.close() def get_modulus(self, min, prefer, max): bitsizes = sorted(self.pack.keys()) diff --git a/paramiko/py3compat.py b/paramiko/py3compat.py index 8a01ba08..0aad3618 100644 --- a/paramiko/py3compat.py +++ b/paramiko/py3compat.py @@ -1,6 +1,9 @@ import sys +import base64 -__all__ = ['PY3', 'string_types', 'integer_types', 'text_type', 'bytes_types', 'bytes', 'long', 'input', 'bytestring', 'byte_ord', 'byte_chr', 'byte_mask', 'b', 'u', 'b2s', 'StringIO', 'BytesIO', 'is_callable', 'MAXSIZE', 'next'] +__all__ = ['PY3', 'string_types', 'integer_types', 'text_type', 'bytes_types', 'bytes', 'long', 'input', + 'decodebytes', 'encodebytes', 'bytestring', 'byte_ord', 'byte_chr', 'byte_mask', + 'b', 'u', 'b2s', 'StringIO', 'BytesIO', 'is_callable', 'MAXSIZE', 'next'] PY3 = sys.version_info[0] >= 3 @@ -12,8 +15,11 @@ if PY3: bytes = bytes bytes_types = bytes integer_types = int - long = int + class long(int): + pass input = input + decodebytes = base64.decodebytes + encodebytes = base64.encodebytes def bytestring(s): return s @@ -72,6 +78,8 @@ else: integer_types = (int, long) long = long input = raw_input + decodebytes = base64.decodestring + encodebytes = base64.encodestring def bytestring(s): # NOQA if isinstance(s, unicode): diff --git a/tests/test_auth.py b/tests/test_auth.py index 586289ba..d26b1807 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -119,13 +119,13 @@ class AuthTest (unittest.TestCase): self.ts.add_server_key(host_key) self.event = threading.Event() self.server = NullServer() - self.assert_(not self.event.isSet()) + self.assertTrue(not self.event.isSet()) self.ts.start_server(self.event, self.server) def verify_finished(self): self.event.wait(1.0) - self.assert_(self.event.isSet()) - self.assert_(self.ts.is_active()) + self.assertTrue(self.event.isSet()) + self.assertTrue(self.ts.is_active()) def test_1_bad_auth_type(self): """ @@ -136,11 +136,11 @@ class AuthTest (unittest.TestCase): try: self.tc.connect(hostkey=self.public_host_key, username='unknown', password='error') - self.assert_(False) + self.assertTrue(False) except: etype, evalue, etb = sys.exc_info() - self.assertEquals(BadAuthenticationType, etype) - self.assertEquals(['publickey'], evalue.allowed_types) + self.assertEqual(BadAuthenticationType, etype) + self.assertEqual(['publickey'], evalue.allowed_types) def test_2_bad_password(self): """ @@ -151,10 +151,10 @@ class AuthTest (unittest.TestCase): self.tc.connect(hostkey=self.public_host_key) try: self.tc.auth_password(username='slowdive', password='error') - self.assert_(False) + self.assertTrue(False) except: etype, evalue, etb = sys.exc_info() - self.assert_(issubclass(etype, AuthenticationException)) + self.assertTrue(issubclass(etype, AuthenticationException)) self.tc.auth_password(username='slowdive', password='pygmalion') self.verify_finished() @@ -165,10 +165,10 @@ class AuthTest (unittest.TestCase): self.start_server() self.tc.connect(hostkey=self.public_host_key) remain = self.tc.auth_password(username='paranoid', password='paranoid') - self.assertEquals(['publickey'], remain) + self.assertEqual(['publickey'], remain) key = DSSKey.from_private_key_file(test_path('test_dss.key')) remain = self.tc.auth_publickey(username='paranoid', key=key) - self.assertEquals([], remain) + self.assertEqual([], remain) self.verify_finished() def test_4_interactive_auth(self): @@ -184,9 +184,9 @@ class AuthTest (unittest.TestCase): self.got_prompts = prompts return ['cat'] remain = self.tc.auth_interactive('commie', handler) - self.assertEquals(self.got_title, 'password') - self.assertEquals(self.got_prompts, [('Password', False)]) - self.assertEquals([], remain) + self.assertEqual(self.got_title, 'password') + self.assertEqual(self.got_prompts, [('Password', False)]) + self.assertEqual([], remain) self.verify_finished() def test_5_interactive_auth_fallback(self): @@ -197,7 +197,7 @@ class AuthTest (unittest.TestCase): self.start_server() self.tc.connect(hostkey=self.public_host_key) remain = self.tc.auth_password('commie', 'cat') - self.assertEquals([], remain) + self.assertEqual([], remain) self.verify_finished() def test_6_auth_utf8(self): @@ -207,7 +207,7 @@ class AuthTest (unittest.TestCase): self.start_server() self.tc.connect(hostkey=self.public_host_key) remain = self.tc.auth_password('utf8', _pwd) - self.assertEquals([], remain) + self.assertEqual([], remain) self.verify_finished() def test_7_auth_non_utf8(self): @@ -218,7 +218,7 @@ class AuthTest (unittest.TestCase): self.start_server() self.tc.connect(hostkey=self.public_host_key) remain = self.tc.auth_password('non-utf8', '\xff') - self.assertEquals([], remain) + self.assertEqual([], remain) self.verify_finished() def test_8_auth_gets_disconnected(self): @@ -232,4 +232,4 @@ class AuthTest (unittest.TestCase): remain = self.tc.auth_password('bad-server', 'hello') except: etype, evalue, etb = sys.exc_info() - self.assert_(issubclass(etype, AuthenticationException)) + self.assertTrue(issubclass(etype, AuthenticationException)) diff --git a/tests/test_buffered_pipe.py b/tests/test_buffered_pipe.py index 7f48b705..5a088d80 100644 --- a/tests/test_buffered_pipe.py +++ b/tests/test_buffered_pipe.py @@ -45,39 +45,39 @@ def close_thread(pipe): class BufferedPipeTest(ParamikoTest): def test_1_buffered_pipe(self): p = BufferedPipe() - self.assert_(not p.read_ready()) + self.assertTrue(not p.read_ready()) p.feed('hello.') - self.assert_(p.read_ready()) + self.assertTrue(p.read_ready()) data = p.read(6) - self.assertEquals(b('hello.'), data) + self.assertEqual(b('hello.'), data) p.feed('plus/minus') - self.assertEquals(b('plu'), p.read(3)) - self.assertEquals(b('s/m'), p.read(3)) - self.assertEquals(b('inus'), p.read(4)) + self.assertEqual(b('plu'), p.read(3)) + self.assertEqual(b('s/m'), p.read(3)) + self.assertEqual(b('inus'), p.read(4)) p.close() - self.assert_(not p.read_ready()) - self.assertEquals(b(''), p.read(1)) + self.assertTrue(not p.read_ready()) + self.assertEqual(b(''), p.read(1)) def test_2_delay(self): p = BufferedPipe() - self.assert_(not p.read_ready()) + self.assertTrue(not p.read_ready()) threading.Thread(target=delay_thread, args=(p,)).start() - self.assertEquals(b('a'), p.read(1, 0.1)) + self.assertEqual(b('a'), p.read(1, 0.1)) try: p.read(1, 0.1) - self.assert_(False) + self.assertTrue(False) except PipeTimeout: pass - self.assertEquals(b('b'), p.read(1, 1.0)) - self.assertEquals(b(''), p.read(1)) + self.assertEqual(b('b'), p.read(1, 1.0)) + self.assertEqual(b(''), p.read(1)) def test_3_close_while_reading(self): p = BufferedPipe() threading.Thread(target=close_thread, args=(p,)).start() data = p.read(1, 1.0) - self.assertEquals(b(''), data) + self.assertEqual(b(''), data) def test_4_or_pipe(self): p = pipe.make_pipe() diff --git a/tests/test_client.py b/tests/test_client.py index b77b90d7..e96a426f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -95,10 +95,10 @@ class SSHClientTest (unittest.TestCase): self.tc.connect(self.addr, self.port, username='slowdive', password='pygmalion') self.event.wait(1.0) - self.assert_(self.event.isSet()) - self.assert_(self.ts.is_active()) - self.assertEquals('slowdive', self.ts.get_username()) - self.assertEquals(True, self.ts.is_authenticated()) + self.assertTrue(self.event.isSet()) + self.assertTrue(self.ts.is_active()) + self.assertEqual('slowdive', self.ts.get_username()) + self.assertEqual(True, self.ts.is_authenticated()) stdin, stdout, stderr = self.tc.exec_command('yes') schan = self.ts.accept(1.0) @@ -107,10 +107,10 @@ class SSHClientTest (unittest.TestCase): schan.send_stderr('This is on stderr.\n') schan.close() - self.assertEquals('Hello there.\n', stdout.readline()) - self.assertEquals('', stdout.readline()) - self.assertEquals('This is on stderr.\n', stderr.readline()) - self.assertEquals('', stderr.readline()) + self.assertEqual('Hello there.\n', stdout.readline()) + self.assertEqual('', stdout.readline()) + self.assertEqual('This is on stderr.\n', stderr.readline()) + self.assertEqual('', stderr.readline()) stdin.close() stdout.close() @@ -128,10 +128,10 @@ class SSHClientTest (unittest.TestCase): self.tc.connect(self.addr, self.port, username='slowdive', key_filename=test_path('test_dss.key')) self.event.wait(1.0) - self.assert_(self.event.isSet()) - self.assert_(self.ts.is_active()) - self.assertEquals('slowdive', self.ts.get_username()) - self.assertEquals(True, self.ts.is_authenticated()) + self.assertTrue(self.event.isSet()) + self.assertTrue(self.ts.is_active()) + self.assertEqual('slowdive', self.ts.get_username()) + self.assertEqual(True, self.ts.is_authenticated()) stdin, stdout, stderr = self.tc.exec_command('yes') schan = self.ts.accept(1.0) @@ -140,10 +140,10 @@ class SSHClientTest (unittest.TestCase): schan.send_stderr('This is on stderr.\n') schan.close() - self.assertEquals('Hello there.\n', stdout.readline()) - self.assertEquals('', stdout.readline()) - self.assertEquals('This is on stderr.\n', stderr.readline()) - self.assertEquals('', stderr.readline()) + self.assertEqual('Hello there.\n', stdout.readline()) + self.assertEqual('', stdout.readline()) + self.assertEqual('This is on stderr.\n', stderr.readline()) + self.assertEqual('', stderr.readline()) stdin.close() stdout.close() @@ -161,10 +161,10 @@ class SSHClientTest (unittest.TestCase): self.tc.connect(self.addr, self.port, username='slowdive', key_filename=[ test_path('test_rsa.key'), test_path('test_dss.key') ]) self.event.wait(1.0) - self.assert_(self.event.isSet()) - self.assert_(self.ts.is_active()) - self.assertEquals('slowdive', self.ts.get_username()) - self.assertEquals(True, self.ts.is_authenticated()) + self.assertTrue(self.event.isSet()) + self.assertTrue(self.ts.is_active()) + self.assertEqual('slowdive', self.ts.get_username()) + self.assertEqual(True, self.ts.is_authenticated()) def test_4_auto_add_policy(self): """ @@ -175,16 +175,16 @@ class SSHClientTest (unittest.TestCase): self.tc = paramiko.SSHClient() self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - self.assertEquals(0, len(self.tc.get_host_keys())) + self.assertEqual(0, len(self.tc.get_host_keys())) self.tc.connect(self.addr, self.port, username='slowdive', password='pygmalion') self.event.wait(1.0) - self.assert_(self.event.isSet()) - self.assert_(self.ts.is_active()) - self.assertEquals('slowdive', self.ts.get_username()) - self.assertEquals(True, self.ts.is_authenticated()) - self.assertEquals(1, len(self.tc.get_host_keys())) - self.assertEquals(public_host_key, self.tc.get_host_keys()['[%s]:%d' % (self.addr, self.port)]['ssh-rsa']) + self.assertTrue(self.event.isSet()) + self.assertTrue(self.ts.is_active()) + self.assertEqual('slowdive', self.ts.get_username()) + self.assertEqual(True, self.ts.is_authenticated()) + self.assertEqual(1, len(self.tc.get_host_keys())) + self.assertEqual(public_host_key, self.tc.get_host_keys()['[%s]:%d' % (self.addr, self.port)]['ssh-rsa']) def test_5_cleanup(self): """ @@ -196,12 +196,12 @@ class SSHClientTest (unittest.TestCase): self.tc = paramiko.SSHClient() self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - self.assertEquals(0, len(self.tc.get_host_keys())) + self.assertEqual(0, len(self.tc.get_host_keys())) self.tc.connect(self.addr, self.port, username='slowdive', password='pygmalion') self.event.wait(1.0) - self.assert_(self.event.isSet()) - self.assert_(self.ts.is_active()) + self.assertTrue(self.event.isSet()) + self.assertTrue(self.ts.is_active()) p = weakref.ref(self.tc._transport.packetizer) self.assertTrue(p() is not None) diff --git a/tests/test_file.py b/tests/test_file.py index 0430040c..33a49130 100755 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -54,7 +54,7 @@ class BufferedFileTest (unittest.TestCase): f = LoopbackFile('r') try: f.write('hi') - self.assert_(False, 'no exception on write to read-only file') + self.assertTrue(False, 'no exception on write to read-only file') except: pass f.close() @@ -62,7 +62,7 @@ class BufferedFileTest (unittest.TestCase): f = LoopbackFile('w') try: f.read(1) - self.assert_(False, 'no exception to read from write-only file') + self.assertTrue(False, 'no exception to read from write-only file') except: pass f.close() @@ -81,12 +81,12 @@ class BufferedFileTest (unittest.TestCase): f.close() try: f.readline() - self.assert_(False, 'no exception on readline of closed file') + self.assertTrue(False, 'no exception on readline of closed file') except IOError: pass - self.assert_(linefeed_byte in f.newlines) - self.assert_(crlf in f.newlines) - self.assert_(cr_byte not in f.newlines) + self.assertTrue(linefeed_byte in f.newlines) + self.assertTrue(crlf in f.newlines) + self.assertTrue(cr_byte not in f.newlines) def test_3_lf(self): """ diff --git a/tests/test_hostkeys.py b/tests/test_hostkeys.py index 66b41b6f..a7621d8b 100644 --- a/tests/test_hostkeys.py +++ b/tests/test_hostkeys.py @@ -25,7 +25,7 @@ from binascii import hexlify import os import unittest import paramiko -from paramiko.py3compat import b +from paramiko.py3compat import b, decodebytes test_hosts_file = """\ @@ -65,42 +65,42 @@ class HostKeysTest (unittest.TestCase): def test_1_load(self): hostdict = paramiko.HostKeys('hostfile.temp') - self.assertEquals(2, len(hostdict)) - self.assertEquals(1, len(list(hostdict.values())[0])) - self.assertEquals(1, len(list(hostdict.values())[1])) + self.assertEqual(2, len(hostdict)) + self.assertEqual(1, len(list(hostdict.values())[0])) + self.assertEqual(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) + self.assertEqual(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) def test_2_add(self): hostdict = paramiko.HostKeys('hostfile.temp') hh = '|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c=' - key = paramiko.RSAKey(data=base64.decodestring(keyblob)) + key = paramiko.RSAKey(data=decodebytes(keyblob)) hostdict.add(hh, 'ssh-rsa', key) - self.assertEquals(3, len(list(hostdict))) + self.assertEqual(3, len(list(hostdict))) x = hostdict['foo.example.com'] fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals(b('7EC91BB336CB6D810B124B1353C32396'), fp) - self.assert_(hostdict.check('foo.example.com', key)) + self.assertEqual(b('7EC91BB336CB6D810B124B1353C32396'), fp) + self.assertTrue(hostdict.check('foo.example.com', key)) def test_3_dict(self): hostdict = paramiko.HostKeys('hostfile.temp') - self.assert_('secure.example.com' in hostdict) - self.assert_('not.example.com' not in hostdict) - self.assert_('secure.example.com' in hostdict) - self.assert_('not.example.com' not in hostdict) + self.assertTrue('secure.example.com' in hostdict) + self.assertTrue('not.example.com' not in hostdict) + self.assertTrue('secure.example.com' in hostdict) + self.assertTrue('not.example.com' not in hostdict) x = hostdict.get('secure.example.com', None) - self.assert_(x is not None) + self.assertTrue(x is not None) fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) + self.assertEqual(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) i = 0 for key in hostdict: i += 1 - self.assertEquals(2, i) + self.assertEqual(2, i) def test_4_dict_set(self): hostdict = paramiko.HostKeys('hostfile.temp') - key = paramiko.RSAKey(data=base64.decodestring(keyblob)) - key_dss = paramiko.DSSKey(data=base64.decodestring(keyblob_dss)) + key = paramiko.RSAKey(data=decodebytes(keyblob)) + key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss)) hostdict['secure.example.com'] = { 'ssh-rsa': key, 'ssh-dss': key_dss @@ -108,11 +108,11 @@ class HostKeysTest (unittest.TestCase): hostdict['fake.example.com'] = {} hostdict['fake.example.com']['ssh-rsa'] = key - self.assertEquals(3, len(hostdict)) - self.assertEquals(2, len(list(hostdict.values())[0])) - self.assertEquals(1, len(list(hostdict.values())[1])) - self.assertEquals(1, len(list(hostdict.values())[2])) + self.assertEqual(3, len(hostdict)) + self.assertEqual(2, len(list(hostdict.values())[0])) + self.assertEqual(1, len(list(hostdict.values())[1])) + self.assertEqual(1, len(list(hostdict.values())[2])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals(b('7EC91BB336CB6D810B124B1353C32396'), fp) + self.assertEqual(b('7EC91BB336CB6D810B124B1353C32396'), fp) fp = hexlify(hostdict['secure.example.com']['ssh-dss'].get_fingerprint()).upper() - self.assertEquals(b('4478F0B9A23CC5182009FF755BC1D26C'), fp) + self.assertEqual(b('4478F0B9A23CC5182009FF755BC1D26C'), fp) diff --git a/tests/test_kex.py b/tests/test_kex.py index f7cb0647..dbe377a4 100644 --- a/tests/test_kex.py +++ b/tests/test_kex.py @@ -92,8 +92,8 @@ class KexTest (unittest.TestCase): kex = KexGroup1(transport) kex.start_kex() x = b('1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assertEquals((paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertEqual((paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect) # fake "reply" msg = Message() @@ -103,17 +103,17 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_REPLY, msg) H = b('03079780F3D3AD0B3C6DB30C8D21685F367A86D2') - self.assertEquals(self.K, transport._K) - self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals((b('fake-host-key'), b('fake-sig')), transport._verify) - self.assert_(transport._activated) + self.assertEqual(self.K, transport._K) + self.assertEqual(H, hexlify(transport._H).upper()) + self.assertEqual((b('fake-host-key'), b('fake-sig')), transport._verify) + self.assertTrue(transport._activated) def test_2_group1_server(self): transport = FakeTransport() transport.server_mode = True kex = KexGroup1(transport) kex.start_kex() - self.assertEquals((paramiko.kex_group1._MSG_KEXDH_INIT,), transport._expect) + self.assertEqual((paramiko.kex_group1._MSG_KEXDH_INIT,), transport._expect) msg = Message() msg.add_mpint(69) @@ -121,10 +121,10 @@ class KexTest (unittest.TestCase): kex.parse_next(paramiko.kex_group1._MSG_KEXDH_INIT, msg) H = b('B16BF34DD10945EDE84E9C1EF24A14BFDC843389') x = b('1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') - self.assertEquals(self.K, transport._K) - self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assert_(transport._activated) + self.assertEqual(self.K, transport._K) + self.assertEqual(H, hexlify(transport._H).upper()) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertTrue(transport._activated) def test_3_gex_client(self): transport = FakeTransport() @@ -132,8 +132,8 @@ class KexTest (unittest.TestCase): kex = KexGex(transport) kex.start_kex() x = b('22000004000000080000002000') - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) msg = Message() msg.add_mpint(FakeModulusPack.P) @@ -141,8 +141,8 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = b('20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) msg = Message() msg.add_string('fake-host-key') @@ -151,10 +151,10 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) H = b('A265563F2FA87F1A89BF007EE90D58BE2E4A4BD0') - self.assertEquals(self.K, transport._K) - self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals((b('fake-host-key'), b('fake-sig')), transport._verify) - self.assert_(transport._activated) + self.assertEqual(self.K, transport._K) + self.assertEqual(H, hexlify(transport._H).upper()) + self.assertEqual((b('fake-host-key'), b('fake-sig')), transport._verify) + self.assertTrue(transport._activated) def test_4_gex_old_client(self): transport = FakeTransport() @@ -162,8 +162,8 @@ class KexTest (unittest.TestCase): kex = KexGex(transport) kex.start_kex(_test_old_style=True) x = b('1E00000800') - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) msg = Message() msg.add_mpint(FakeModulusPack.P) @@ -171,8 +171,8 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = b('20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) msg = Message() msg.add_string('fake-host-key') @@ -181,17 +181,17 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) H = b('807F87B269EF7AC5EC7E75676808776A27D5864C') - self.assertEquals(self.K, transport._K) - self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals((b('fake-host-key'), b('fake-sig')), transport._verify) - self.assert_(transport._activated) + self.assertEqual(self.K, transport._K) + self.assertEqual(H, hexlify(transport._H).upper()) + self.assertEqual((b('fake-host-key'), b('fake-sig')), transport._verify) + self.assertTrue(transport._activated) def test_5_gex_server(self): transport = FakeTransport() transport.server_mode = True kex = KexGex(transport) kex.start_kex() - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD), transport._expect) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD), transport._expect) msg = Message() msg.add_int(1024) @@ -200,8 +200,8 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) x = b('1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102') - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) msg = Message() msg.add_mpint(12345) @@ -210,25 +210,25 @@ class KexTest (unittest.TestCase): K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 H = b('CE754197C21BF3452863B4F44D0B3951F12516EF') x = b('210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') - self.assertEquals(K, transport._K) - self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assert_(transport._activated) + self.assertEqual(K, transport._K) + self.assertEqual(H, hexlify(transport._H).upper()) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertTrue(transport._activated) def test_6_gex_server_with_old_client(self): transport = FakeTransport() transport.server_mode = True kex = KexGex(transport) kex.start_kex() - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD), transport._expect) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD), transport._expect) msg = Message() msg.add_int(2048) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) x = b('1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102') - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assertEquals((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) msg = Message() msg.add_mpint(12345) @@ -237,7 +237,7 @@ class KexTest (unittest.TestCase): K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 H = b('B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B') x = b('210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') - self.assertEquals(K, transport._K) - self.assertEquals(H, hexlify(transport._H).upper()) - self.assertEquals(x, hexlify(transport._message.asbytes()).upper()) - self.assert_(transport._activated) + self.assertEqual(K, transport._K) + self.assertEqual(H, hexlify(transport._H).upper()) + self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) + self.assertTrue(transport._activated) diff --git a/tests/test_message.py b/tests/test_message.py index 0aed88c2..f983b4de 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -40,7 +40,7 @@ class MessageTest (unittest.TestCase): msg.add_string('q') msg.add_string('hello') msg.add_string('x' * 1000) - self.assertEquals(msg.asbytes(), self.__a) + self.assertEqual(msg.asbytes(), self.__a) msg = Message() msg.add_boolean(True) @@ -49,7 +49,7 @@ class MessageTest (unittest.TestCase): msg.add_bytes(zero_byte + byte_chr(0x3f)) msg.add_list(['huey', 'dewey', 'louie']) - self.assertEquals(msg.asbytes(), self.__b) + self.assertEqual(msg.asbytes(), self.__b) msg = Message() msg.add_int64(5) @@ -57,29 +57,29 @@ class MessageTest (unittest.TestCase): msg.add_mpint(17) msg.add_mpint(0xf5e4d3c2b109) msg.add_mpint(-0x65e4d3c2b109) - self.assertEquals(msg.asbytes(), self.__c) + self.assertEqual(msg.asbytes(), self.__c) def test_2_decode(self): msg = Message(self.__a) - self.assertEquals(msg.get_int(), 23) - self.assertEquals(msg.get_int(), 123789456) - self.assertEquals(msg.get_text(), 'q') - self.assertEquals(msg.get_text(), 'hello') - self.assertEquals(msg.get_text(), 'x' * 1000) + self.assertEqual(msg.get_int(), 23) + self.assertEqual(msg.get_int(), 123789456) + self.assertEqual(msg.get_text(), 'q') + self.assertEqual(msg.get_text(), 'hello') + self.assertEqual(msg.get_text(), 'x' * 1000) msg = Message(self.__b) - self.assertEquals(msg.get_boolean(), True) - self.assertEquals(msg.get_boolean(), False) - self.assertEquals(msg.get_byte(), byte_chr(0xf3)) - self.assertEquals(msg.get_bytes(2), zero_byte + byte_chr(0x3f)) - self.assertEquals(msg.get_list(), ['huey', 'dewey', 'louie']) + self.assertEqual(msg.get_boolean(), True) + self.assertEqual(msg.get_boolean(), False) + self.assertEqual(msg.get_byte(), byte_chr(0xf3)) + self.assertEqual(msg.get_bytes(2), zero_byte + byte_chr(0x3f)) + self.assertEqual(msg.get_list(), ['huey', 'dewey', 'louie']) msg = Message(self.__c) - self.assertEquals(msg.get_int64(), 5) - self.assertEquals(msg.get_int64(), 0xf5e4d3c2b109) - self.assertEquals(msg.get_mpint(), 17) - self.assertEquals(msg.get_mpint(), 0xf5e4d3c2b109) - self.assertEquals(msg.get_mpint(), -0x65e4d3c2b109) + self.assertEqual(msg.get_int64(), 5) + self.assertEqual(msg.get_int64(), 0xf5e4d3c2b109) + self.assertEqual(msg.get_mpint(), 17) + self.assertEqual(msg.get_mpint(), 0xf5e4d3c2b109) + self.assertEqual(msg.get_mpint(), -0x65e4d3c2b109) def test_3_add(self): msg = Message() @@ -89,16 +89,16 @@ class MessageTest (unittest.TestCase): msg.add(True) msg.add('cat') msg.add(['a', 'b']) - self.assertEquals(msg.asbytes(), self.__d) + self.assertEqual(msg.asbytes(), self.__d) def test_4_misc(self): msg = Message(self.__d) - self.assertEquals(msg.get_int(), 5) - self.assertEquals(msg.get_int(), 0x1122334455) - self.assertEquals(msg.get_int(), 0xf00000000000000000) - self.assertEquals(msg.get_so_far(), self.__d[:29]) - self.assertEquals(msg.get_remainder(), self.__d[29:]) + self.assertEqual(msg.get_int(), 5) + self.assertEqual(msg.get_int(), 0x1122334455) + self.assertEqual(msg.get_int(), 0xf00000000000000000) + self.assertEqual(msg.get_so_far(), self.__d[:29]) + self.assertEqual(msg.get_remainder(), self.__d[29:]) msg.rewind() - self.assertEquals(msg.get_int(), 5) - self.assertEquals(msg.get_so_far(), self.__d[:4]) - self.assertEquals(msg.get_remainder(), self.__d[4:]) + self.assertEqual(msg.get_int(), 5) + self.assertEqual(msg.get_so_far(), self.__d[:4]) + self.assertEqual(msg.get_remainder(), self.__d[4:]) diff --git a/tests/test_packetizer.py b/tests/test_packetizer.py index a4ada72f..43dea38a 100644 --- a/tests/test_packetizer.py +++ b/tests/test_packetizer.py @@ -54,8 +54,8 @@ class PacketizerTest (unittest.TestCase): p.send_message(m) data = rsock.recv(100) # 32 + 12 bytes of MAC = 44 - self.assertEquals(44, len(data)) - self.assertEquals(unhexlify(b('439197bd5b50ac2587c2c46bc7e938c0')), data[:16]) + self.assertEqual(44, len(data)) + self.assertEqual(unhexlify(b('439197bd5b50ac2587c2c46bc7e938c0')), data[:16]) def test_2_read (self): rsock = LoopSocket() @@ -68,7 +68,7 @@ class PacketizerTest (unittest.TestCase): p.set_inbound_cipher(cipher, 16, SHA, 12, x1f * 20) wsock.send(unhexlify(b('439197bd5b50ac2587c2c46bc7e938c090d216560d717361387c4c3dfb977de26e03b1a0c21cd641414cb459'))) cmd, m = p.read_message() - self.assertEquals(100, cmd) - self.assertEquals(100, m.get_int()) - self.assertEquals(1, m.get_int()) - self.assertEquals(900, m.get_int()) + self.assertEqual(100, cmd) + self.assertEqual(100, m.get_int()) + self.assertEqual(1, m.get_int()) + self.assertEqual(900, m.get_int()) diff --git a/tests/test_pkey.py b/tests/test_pkey.py index 8ab21a3a..f8549468 100644 --- a/tests/test_pkey.py +++ b/tests/test_pkey.py @@ -92,157 +92,157 @@ class KeyTest (unittest.TestCase): from Crypto.Hash import MD5 key = util.generate_key_bytes(MD5, x1234, 'happy birthday', 30) exp = unhexlify(b('61E1F272F4C1C4561586BD322498C0E924672780F47BB37DDA7D54019E64')) - self.assertEquals(exp, key) + self.assertEqual(exp, key) def test_2_load_rsa(self): key = RSAKey.from_private_key_file(test_path('test_rsa.key')) - self.assertEquals('ssh-rsa', key.get_name()) + self.assertEqual('ssh-rsa', key.get_name()) exp_rsa = b(FINGER_RSA.split()[1].replace(':', '')) my_rsa = hexlify(key.get_fingerprint()) - self.assertEquals(exp_rsa, my_rsa) - self.assertEquals(PUB_RSA.split()[1], key.get_base64()) - self.assertEquals(1024, key.get_bits()) + self.assertEqual(exp_rsa, my_rsa) + self.assertEqual(PUB_RSA.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) s = StringIO() key.write_private_key(s) - self.assertEquals(RSA_PRIVATE_OUT, s.getvalue()) + self.assertEqual(RSA_PRIVATE_OUT, s.getvalue()) s.seek(0) key2 = RSAKey.from_private_key(s) - self.assertEquals(key, key2) + self.assertEqual(key, key2) def test_3_load_rsa_password(self): key = RSAKey.from_private_key_file(test_path('test_rsa_password.key'), 'television') - self.assertEquals('ssh-rsa', key.get_name()) + self.assertEqual('ssh-rsa', key.get_name()) exp_rsa = b(FINGER_RSA.split()[1].replace(':', '')) my_rsa = hexlify(key.get_fingerprint()) - self.assertEquals(exp_rsa, my_rsa) - self.assertEquals(PUB_RSA.split()[1], key.get_base64()) - self.assertEquals(1024, key.get_bits()) + self.assertEqual(exp_rsa, my_rsa) + self.assertEqual(PUB_RSA.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) def test_4_load_dss(self): key = DSSKey.from_private_key_file(test_path('test_dss.key')) - self.assertEquals('ssh-dss', key.get_name()) + self.assertEqual('ssh-dss', key.get_name()) exp_dss = b(FINGER_DSS.split()[1].replace(':', '')) my_dss = hexlify(key.get_fingerprint()) - self.assertEquals(exp_dss, my_dss) - self.assertEquals(PUB_DSS.split()[1], key.get_base64()) - self.assertEquals(1024, key.get_bits()) + self.assertEqual(exp_dss, my_dss) + self.assertEqual(PUB_DSS.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) s = StringIO() key.write_private_key(s) - self.assertEquals(DSS_PRIVATE_OUT, s.getvalue()) + self.assertEqual(DSS_PRIVATE_OUT, s.getvalue()) s.seek(0) key2 = DSSKey.from_private_key(s) - self.assertEquals(key, key2) + self.assertEqual(key, key2) def test_5_load_dss_password(self): key = DSSKey.from_private_key_file(test_path('test_dss_password.key'), 'television') - self.assertEquals('ssh-dss', key.get_name()) + self.assertEqual('ssh-dss', key.get_name()) exp_dss = b(FINGER_DSS.split()[1].replace(':', '')) my_dss = hexlify(key.get_fingerprint()) - self.assertEquals(exp_dss, my_dss) - self.assertEquals(PUB_DSS.split()[1], key.get_base64()) - self.assertEquals(1024, key.get_bits()) + self.assertEqual(exp_dss, my_dss) + self.assertEqual(PUB_DSS.split()[1], key.get_base64()) + self.assertEqual(1024, key.get_bits()) def test_6_compare_rsa(self): # verify that the private & public keys compare equal key = RSAKey.from_private_key_file(test_path('test_rsa.key')) - self.assertEquals(key, key) + self.assertEqual(key, key) pub = RSAKey(data=key.asbytes()) - self.assert_(key.can_sign()) - self.assert_(not pub.can_sign()) - self.assertEquals(key, pub) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) def test_7_compare_dss(self): # verify that the private & public keys compare equal key = DSSKey.from_private_key_file(test_path('test_dss.key')) - self.assertEquals(key, key) + self.assertEqual(key, key) pub = DSSKey(data=key.asbytes()) - self.assert_(key.can_sign()) - self.assert_(not pub.can_sign()) - self.assertEquals(key, pub) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) def test_8_sign_rsa(self): # verify that the rsa private key can sign and verify key = RSAKey.from_private_key_file(test_path('test_rsa.key')) msg = key.sign_ssh_data(rng, b('ice weasels')) - self.assert_(type(msg) is Message) + self.assertTrue(type(msg) is Message) msg.rewind() - self.assertEquals('ssh-rsa', msg.get_text()) + self.assertEqual('ssh-rsa', msg.get_text()) sig = bytes().join([byte_chr(int(x, 16)) for x in SIGNED_RSA.split(':')]) - self.assertEquals(sig, msg.get_binary()) + self.assertEqual(sig, msg.get_binary()) msg.rewind() pub = RSAKey(data=key.asbytes()) - self.assert_(pub.verify_ssh_sig(b('ice weasels'), msg)) + self.assertTrue(pub.verify_ssh_sig(b('ice weasels'), msg)) def test_9_sign_dss(self): # verify that the dss private key can sign and verify key = DSSKey.from_private_key_file(test_path('test_dss.key')) msg = key.sign_ssh_data(rng, b('ice weasels')) - self.assert_(type(msg) is Message) + self.assertTrue(type(msg) is Message) msg.rewind() - self.assertEquals('ssh-dss', msg.get_text()) + self.assertEqual('ssh-dss', msg.get_text()) # can't do the same test as we do for RSA, because DSS signatures # are usually different each time. but we can test verification # anyway so it's ok. - self.assertEquals(40, len(msg.get_binary())) + self.assertEqual(40, len(msg.get_binary())) msg.rewind() pub = DSSKey(data=key.asbytes()) - self.assert_(pub.verify_ssh_sig(b('ice weasels'), msg)) + self.assertTrue(pub.verify_ssh_sig(b('ice weasels'), msg)) def test_A_generate_rsa(self): key = RSAKey.generate(1024) msg = key.sign_ssh_data(rng, b('jerri blank')) msg.rewind() - self.assert_(key.verify_ssh_sig(b('jerri blank'), msg)) + self.assertTrue(key.verify_ssh_sig(b('jerri blank'), msg)) def test_B_generate_dss(self): key = DSSKey.generate(1024) msg = key.sign_ssh_data(rng, b('jerri blank')) msg.rewind() - self.assert_(key.verify_ssh_sig(b('jerri blank'), msg)) + self.assertTrue(key.verify_ssh_sig(b('jerri blank'), msg)) def test_10_load_ecdsa(self): key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) - self.assertEquals('ecdsa-sha2-nistp256', key.get_name()) + self.assertEqual('ecdsa-sha2-nistp256', key.get_name()) exp_ecdsa = b(FINGER_ECDSA.split()[1].replace(':', '')) my_ecdsa = hexlify(key.get_fingerprint()) - self.assertEquals(exp_ecdsa, my_ecdsa) - self.assertEquals(PUB_ECDSA.split()[1], key.get_base64()) - self.assertEquals(256, key.get_bits()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA.split()[1], key.get_base64()) + self.assertEqual(256, key.get_bits()) s = StringIO() key.write_private_key(s) - self.assertEquals(ECDSA_PRIVATE_OUT, s.getvalue()) + self.assertEqual(ECDSA_PRIVATE_OUT, s.getvalue()) s.seek(0) key2 = ECDSAKey.from_private_key(s) - self.assertEquals(key, key2) + self.assertEqual(key, key2) def test_11_load_ecdsa_password(self): key = ECDSAKey.from_private_key_file(test_path('test_ecdsa_password.key'), b('television')) - self.assertEquals('ecdsa-sha2-nistp256', key.get_name()) + self.assertEqual('ecdsa-sha2-nistp256', key.get_name()) exp_ecdsa = b(FINGER_ECDSA.split()[1].replace(':', '')) my_ecdsa = hexlify(key.get_fingerprint()) - self.assertEquals(exp_ecdsa, my_ecdsa) - self.assertEquals(PUB_ECDSA.split()[1], key.get_base64()) - self.assertEquals(256, key.get_bits()) + self.assertEqual(exp_ecdsa, my_ecdsa) + self.assertEqual(PUB_ECDSA.split()[1], key.get_base64()) + self.assertEqual(256, key.get_bits()) def test_12_compare_ecdsa(self): # verify that the private & public keys compare equal key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) - self.assertEquals(key, key) + self.assertEqual(key, key) pub = ECDSAKey(data=key.asbytes()) - self.assert_(key.can_sign()) - self.assert_(not pub.can_sign()) - self.assertEquals(key, pub) + self.assertTrue(key.can_sign()) + self.assertTrue(not pub.can_sign()) + self.assertEqual(key, pub) def test_13_sign_ecdsa(self): # verify that the rsa private key can sign and verify key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) msg = key.sign_ssh_data(rng, b('ice weasels')) - self.assert_(type(msg) is Message) + self.assertTrue(type(msg) is Message) msg.rewind() - self.assertEquals('ecdsa-sha2-nistp256', msg.get_text()) + self.assertEqual('ecdsa-sha2-nistp256', msg.get_text()) # ECDSA signatures, like DSS signatures, tend to be different # each time, so we can't compare against a "known correct" # signature. @@ -250,4 +250,4 @@ class KeyTest (unittest.TestCase): msg.rewind() pub = ECDSAKey(data=key.asbytes()) - self.assert_(pub.verify_ssh_sig(b('ice weasels'), msg)) + self.assertTrue(pub.verify_ssh_sig(b('ice weasels'), msg)) diff --git a/tests/test_sftp.py b/tests/test_sftp.py index c17defaa..b84b3fd6 100755 --- a/tests/test_sftp.py +++ b/tests/test_sftp.py @@ -162,8 +162,8 @@ class SFTPTest (unittest.TestCase): f = sftp.open(FOLDER + '/test', 'w') try: self.assertEqual(f.stat().st_size, 0) - f.close() finally: + f.close() sftp.remove(FOLDER + '/test') def test_2_close(self): @@ -219,8 +219,8 @@ class SFTPTest (unittest.TestCase): self.assertEqual(f.stat().st_size, 37) f.seek(-26, f.SEEK_CUR) self.assertEqual(f.readline(), 'second line\n') - f.close() finally: + f.close() sftp.remove(FOLDER + '/append.txt') def test_5_rename(self): diff --git a/tests/test_sftp_big.py b/tests/test_sftp_big.py index a53a6c3d..dc9cba93 100644 --- a/tests/test_sftp_big.py +++ b/tests/test_sftp_big.py @@ -262,6 +262,7 @@ class BigSFTPTest (unittest.TestCase): for i in range(10): f = sftp.open('%s/hongry.txt' % FOLDER, 'r') f.prefetch() + f.close() f = sftp.open('%s/hongry.txt' % FOLDER, 'r') f.prefetch() for n in range(1024): diff --git a/tests/test_transport.py b/tests/test_transport.py index 22a02a8e..397b00ca 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -132,28 +132,28 @@ class TransportTest(ParamikoTest): event = threading.Event() self.server = NullServer() - self.assert_(not event.isSet()) + self.assertTrue(not event.isSet()) self.ts.start_server(event, self.server) self.tc.connect(hostkey=public_host_key, username='slowdive', password='pygmalion') event.wait(1.0) - self.assert_(event.isSet()) - self.assert_(self.ts.is_active()) + self.assertTrue(event.isSet()) + self.assertTrue(self.ts.is_active()) def test_1_security_options(self): o = self.tc.get_security_options() - self.assertEquals(type(o), SecurityOptions) - self.assert_(('aes256-cbc', 'blowfish-cbc') != o.ciphers) + self.assertEqual(type(o), SecurityOptions) + self.assertTrue(('aes256-cbc', 'blowfish-cbc') != o.ciphers) o.ciphers = ('aes256-cbc', 'blowfish-cbc') - self.assertEquals(('aes256-cbc', 'blowfish-cbc'), o.ciphers) + self.assertEqual(('aes256-cbc', 'blowfish-cbc'), o.ciphers) try: o.ciphers = ('aes256-cbc', 'made-up-cipher') - self.assert_(False) + self.assertTrue(False) except ValueError: pass try: o.ciphers = 23 - self.assert_(False) + self.assertTrue(False) except TypeError: pass @@ -162,7 +162,7 @@ class TransportTest(ParamikoTest): self.tc.H = unhexlify(b('0C8307CDE6856FF30BA93684EB0F04C2520E9ED3')) self.tc.session_id = self.tc.H key = self.tc._compute_key('C', 32) - self.assertEquals(b('207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995'), + self.assertEqual(b('207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995'), hexlify(key).upper()) def test_3_simple(self): @@ -176,21 +176,21 @@ class TransportTest(ParamikoTest): self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() - self.assert_(not event.isSet()) - self.assertEquals(None, self.tc.get_username()) - self.assertEquals(None, self.ts.get_username()) - self.assertEquals(False, self.tc.is_authenticated()) - self.assertEquals(False, self.ts.is_authenticated()) + self.assertTrue(not event.isSet()) + self.assertEqual(None, self.tc.get_username()) + self.assertEqual(None, self.ts.get_username()) + self.assertEqual(False, self.tc.is_authenticated()) + self.assertEqual(False, self.ts.is_authenticated()) self.ts.start_server(event, server) self.tc.connect(hostkey=public_host_key, username='slowdive', password='pygmalion') event.wait(1.0) - self.assert_(event.isSet()) - self.assert_(self.ts.is_active()) - self.assertEquals('slowdive', self.tc.get_username()) - self.assertEquals('slowdive', self.ts.get_username()) - self.assertEquals(True, self.tc.is_authenticated()) - self.assertEquals(True, self.ts.is_authenticated()) + self.assertTrue(event.isSet()) + self.assertTrue(self.ts.is_active()) + self.assertEqual('slowdive', self.tc.get_username()) + self.assertEqual('slowdive', self.ts.get_username()) + self.assertEqual(True, self.tc.is_authenticated()) + self.assertEqual(True, self.ts.is_authenticated()) def test_3a_long_banner(self): """ @@ -201,14 +201,14 @@ class TransportTest(ParamikoTest): self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() - self.assert_(not event.isSet()) + self.assertTrue(not event.isSet()) self.socks.send(LONG_BANNER) self.ts.start_server(event, server) self.tc.connect(hostkey=public_host_key, username='slowdive', password='pygmalion') event.wait(1.0) - self.assert_(event.isSet()) - self.assert_(self.ts.is_active()) + self.assertTrue(event.isSet()) + self.assertTrue(self.ts.is_active()) def test_4_special(self): """ @@ -219,10 +219,10 @@ class TransportTest(ParamikoTest): options.ciphers = ('aes256-cbc',) options.digests = ('hmac-md5-96',) self.setup_test_server(client_options=force_algorithms) - self.assertEquals('aes256-cbc', self.tc.local_cipher) - self.assertEquals('aes256-cbc', self.tc.remote_cipher) - self.assertEquals(12, self.tc.packetizer.get_mac_size_out()) - self.assertEquals(12, self.tc.packetizer.get_mac_size_in()) + self.assertEqual('aes256-cbc', self.tc.local_cipher) + self.assertEqual('aes256-cbc', self.tc.remote_cipher) + self.assertEqual(12, self.tc.packetizer.get_mac_size_out()) + self.assertEqual(12, self.tc.packetizer.get_mac_size_in()) self.tc.send_ignore(1024) self.tc.renegotiate_keys() @@ -233,10 +233,10 @@ class TransportTest(ParamikoTest): verify that the keepalive will be sent. """ self.setup_test_server() - self.assertEquals(None, getattr(self.server, '_global_request', None)) + self.assertEqual(None, getattr(self.server, '_global_request', None)) self.tc.set_keepalive(1) time.sleep(2) - self.assertEquals('keepalive@lag.net', self.server._global_request) + self.assertEqual('keepalive@lag.net', self.server._global_request) def test_6_exec_command(self): """ @@ -248,7 +248,7 @@ class TransportTest(ParamikoTest): schan = self.ts.accept(1.0) try: chan.exec_command('no') - self.assert_(False) + self.assertTrue(False) except SSHException: pass @@ -260,11 +260,11 @@ class TransportTest(ParamikoTest): schan.close() f = chan.makefile() - self.assertEquals('Hello there.\n', f.readline()) - self.assertEquals('', f.readline()) + self.assertEqual('Hello there.\n', f.readline()) + self.assertEqual('', f.readline()) f = chan.makefile_stderr() - self.assertEquals('This is on stderr.\n', f.readline()) - self.assertEquals('', f.readline()) + self.assertEqual('This is on stderr.\n', f.readline()) + self.assertEqual('', f.readline()) # now try it with combined stdout/stderr chan = self.tc.open_session() @@ -276,9 +276,9 @@ class TransportTest(ParamikoTest): chan.set_combine_stderr(True) f = chan.makefile() - self.assertEquals('Hello there.\n', f.readline()) - self.assertEquals('This is on stderr.\n', f.readline()) - self.assertEquals('', f.readline()) + self.assertEqual('Hello there.\n', f.readline()) + self.assertEqual('This is on stderr.\n', f.readline()) + self.assertEqual('', f.readline()) def test_7_invoke_shell(self): """ @@ -290,9 +290,9 @@ class TransportTest(ParamikoTest): schan = self.ts.accept(1.0) chan.send('communist j. cat\n') f = schan.makefile() - self.assertEquals('communist j. cat\n', f.readline()) + self.assertEqual('communist j. cat\n', f.readline()) chan.close() - self.assertEquals('', f.readline()) + self.assertEqual('', f.readline()) def test_8_channel_exception(self): """ @@ -304,7 +304,7 @@ class TransportTest(ParamikoTest): self.fail('expected exception') except ChannelException: x = sys.exc_info()[1] - self.assert_(x.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) + self.assertTrue(x.code == OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) def test_9_exit_status(self): """ @@ -316,7 +316,7 @@ class TransportTest(ParamikoTest): schan = self.ts.accept(1.0) chan.exec_command('yes') schan.send('Hello there.\n') - self.assert_(not chan.exit_status_ready()) + self.assertTrue(not chan.exit_status_ready()) # trigger an EOF schan.shutdown_read() schan.shutdown_write() @@ -324,15 +324,15 @@ class TransportTest(ParamikoTest): schan.close() f = chan.makefile() - self.assertEquals('Hello there.\n', f.readline()) - self.assertEquals('', f.readline()) + self.assertEqual('Hello there.\n', f.readline()) + self.assertEqual('', f.readline()) count = 0 while not chan.exit_status_ready(): time.sleep(0.1) count += 1 if count > 50: raise Exception("timeout") - self.assertEquals(23, chan.recv_exit_status()) + self.assertEqual(23, chan.recv_exit_status()) chan.close() def test_A_select(self): @@ -346,9 +346,9 @@ class TransportTest(ParamikoTest): # nothing should be ready r, w, e = select.select([chan], [], [], 0.1) - self.assertEquals([], r) - self.assertEquals([], w) - self.assertEquals([], e) + self.assertEqual([], r) + self.assertEqual([], w) + self.assertEqual([], e) schan.send('hello\n') @@ -358,17 +358,17 @@ class TransportTest(ParamikoTest): if chan in r: break time.sleep(0.1) - self.assertEquals([chan], r) - self.assertEquals([], w) - self.assertEquals([], e) + self.assertEqual([chan], r) + self.assertEqual([], w) + self.assertEqual([], e) - self.assertEquals(b('hello\n'), chan.recv(6)) + self.assertEqual(b('hello\n'), chan.recv(6)) # and, should be dead again now r, w, e = select.select([chan], [], [], 0.1) - self.assertEquals([], r) - self.assertEquals([], w) - self.assertEquals([], e) + self.assertEqual([], r) + self.assertEqual([], w) + self.assertEqual([], e) schan.close() @@ -378,17 +378,17 @@ class TransportTest(ParamikoTest): if chan in r: break time.sleep(0.1) - self.assertEquals([chan], r) - self.assertEquals([], w) - self.assertEquals([], e) - self.assertEquals(bytes(), chan.recv(16)) + self.assertEqual([chan], r) + self.assertEqual([], w) + self.assertEqual([], e) + self.assertEqual(bytes(), chan.recv(16)) # make sure the pipe is still open for now... p = chan._pipe - self.assertEquals(False, p._closed) + self.assertEqual(False, p._closed) chan.close() # ...and now is closed. - self.assertEquals(True, p._closed) + self.assertEqual(True, p._closed) def test_B_renegotiate(self): """ @@ -400,7 +400,7 @@ class TransportTest(ParamikoTest): chan.exec_command('yes') schan = self.ts.accept(1.0) - self.assertEquals(self.tc.H, self.tc.session_id) + self.assertEqual(self.tc.H, self.tc.session_id) for i in range(20): chan.send('x' * 1024) chan.close() @@ -410,7 +410,7 @@ class TransportTest(ParamikoTest): if self.tc.H != self.tc.session_id: break time.sleep(0.1) - self.assertNotEquals(self.tc.H, self.tc.session_id) + self.assertNotEqual(self.tc.H, self.tc.session_id) schan.close() @@ -429,8 +429,8 @@ class TransportTest(ParamikoTest): chan.send('x' * 1024) bytes2 = self.tc.packetizer._Packetizer__sent_bytes # tests show this is actually compressed to *52 bytes*! including packet overhead! nice!! :) - self.assert_(bytes2 - bytes < 1024) - self.assertEquals(52, bytes2 - bytes) + self.assertTrue(bytes2 - bytes < 1024) + self.assertEqual(52, bytes2 - bytes) chan.close() schan.close() @@ -450,20 +450,20 @@ class TransportTest(ParamikoTest): requested.append((addr, port)) self.tc._queue_incoming_channel(c) - self.assertEquals(None, getattr(self.server, '_x11_screen_number', None)) + self.assertEqual(None, getattr(self.server, '_x11_screen_number', None)) cookie = chan.request_x11(0, single_connection=True, handler=handler) - self.assertEquals(0, self.server._x11_screen_number) - self.assertEquals('MIT-MAGIC-COOKIE-1', self.server._x11_auth_protocol) - self.assertEquals(cookie, self.server._x11_auth_cookie) - self.assertEquals(True, self.server._x11_single_connection) + self.assertEqual(0, self.server._x11_screen_number) + self.assertEqual('MIT-MAGIC-COOKIE-1', self.server._x11_auth_protocol) + self.assertEqual(cookie, self.server._x11_auth_cookie) + self.assertEqual(True, self.server._x11_single_connection) x11_server = self.ts.open_x11_channel(('localhost', 6093)) x11_client = self.tc.accept() - self.assertEquals('localhost', requested[0][0]) - self.assertEquals(6093, requested[0][1]) + self.assertEqual('localhost', requested[0][0]) + self.assertEqual(6093, requested[0][1]) x11_server.send('hello') - self.assertEquals(b('hello'), x11_client.recv(5)) + self.assertEqual(b('hello'), x11_client.recv(5)) x11_server.close() x11_client.close() @@ -487,7 +487,7 @@ class TransportTest(ParamikoTest): self.tc._queue_incoming_channel(c) port = self.tc.request_port_forward('127.0.0.1', 0, handler) - self.assertEquals(port, self.server._listen.getsockname()[1]) + self.assertEqual(port, self.server._listen.getsockname()[1]) cs = socket.socket() cs.connect(('127.0.0.1', port)) @@ -496,7 +496,7 @@ class TransportTest(ParamikoTest): cch = self.tc.accept() sch.send('hello') - self.assertEquals(b('hello'), cch.recv(5)) + self.assertEqual(b('hello'), cch.recv(5)) sch.close() cch.close() ss.close() @@ -533,7 +533,7 @@ class TransportTest(ParamikoTest): sch.send(cch.recv(8192)) sch.close() - self.assertEquals(b('Hello!\n'), cs.recv(7)) + self.assertEqual(b('Hello!\n'), cs.recv(7)) cs.close() def test_G_stderr_select(self): @@ -548,9 +548,9 @@ class TransportTest(ParamikoTest): # nothing should be ready r, w, e = select.select([chan], [], [], 0.1) - self.assertEquals([], r) - self.assertEquals([], w) - self.assertEquals([], e) + self.assertEqual([], r) + self.assertEqual([], w) + self.assertEqual([], e) schan.send_stderr('hello\n') @@ -560,17 +560,17 @@ class TransportTest(ParamikoTest): if chan in r: break time.sleep(0.1) - self.assertEquals([chan], r) - self.assertEquals([], w) - self.assertEquals([], e) + self.assertEqual([chan], r) + self.assertEqual([], w) + self.assertEqual([], e) - self.assertEquals(b('hello\n'), chan.recv_stderr(6)) + self.assertEqual(b('hello\n'), chan.recv_stderr(6)) # and, should be dead again now r, w, e = select.select([chan], [], [], 0.1) - self.assertEquals([], r) - self.assertEquals([], w) - self.assertEquals([], e) + self.assertEqual([], r) + self.assertEqual([], w) + self.assertEqual([], e) schan.close() chan.close() @@ -584,7 +584,7 @@ class TransportTest(ParamikoTest): chan.invoke_shell() schan = self.ts.accept(1.0) - self.assertEquals(chan.send_ready(), True) + self.assertEqual(chan.send_ready(), True) total = 0 K = '*' * 1024 while total < 1024 * 1024: @@ -592,11 +592,11 @@ class TransportTest(ParamikoTest): total += len(K) if not chan.send_ready(): break - self.assert_(total < 1024 * 1024) + self.assertTrue(total < 1024 * 1024) schan.close() chan.close() - self.assertEquals(chan.send_ready(), True) + self.assertEqual(chan.send_ready(), True) def test_I_rekey_deadlock(self): """ diff --git a/tests/test_util.py b/tests/test_util.py index 84d5e88e..dba52236 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -103,7 +103,7 @@ class UtilTest(ParamikoTest): global test_config_file f = StringIO(test_config_file) config = paramiko.util.parse_ssh_config(f) - self.assertEquals(config._config, + self.assertEqual(config._config, [{'host': ['*'], 'config': {}}, {'host': ['*'], 'config': {'identityfile': ['~/.ssh/id_rsa'], 'user': 'robey'}}, {'host': ['*.example.com'], 'config': {'user': 'bjork', 'port': '3333'}}, {'host': ['*'], 'config': {'crazy': 'something dumb '}}, @@ -131,7 +131,7 @@ class UtilTest(ParamikoTest): hostname=host, identityfile=[os.path.expanduser("~/.ssh/id_rsa")] ) - self.assertEquals( + self.assertEqual( paramiko.util.lookup_ssh_host_config(host, config), values ) @@ -139,7 +139,7 @@ class UtilTest(ParamikoTest): def test_4_generate_key_bytes(self): x = paramiko.util.generate_key_bytes(SHA, b('ABCDEFGH'), 'This is my secret passphrase.', 64) hex = ''.join(['%02x' % byte_ord(c) for c in x]) - self.assertEquals(hex, '9110e2f6793b69363e58173e9436b13a5a4b339005741d5c680e505f57d871347b4239f14fb5c46e857d5e100424873ba849ac699cea98d729e57b3e84378e8b') + self.assertEqual(hex, '9110e2f6793b69363e58173e9436b13a5a4b339005741d5c680e505f57d871347b4239f14fb5c46e857d5e100424873ba849ac699cea98d729e57b3e84378e8b') def test_5_host_keys(self): f = open('hostfile.temp', 'w') @@ -147,11 +147,11 @@ class UtilTest(ParamikoTest): f.close() try: hostdict = paramiko.util.load_host_keys('hostfile.temp') - self.assertEquals(2, len(hostdict)) - self.assertEquals(1, len(list(hostdict.values())[0])) - self.assertEquals(1, len(list(hostdict.values())[1])) + self.assertEqual(2, len(hostdict)) + self.assertEqual(1, len(list(hostdict.values())[0])) + self.assertEqual(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEquals(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) + self.assertEqual(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) finally: os.unlink('hostfile.temp') @@ -159,7 +159,7 @@ class UtilTest(ParamikoTest): from paramiko.common import rng # just verify that we can pull out 32 bytes and not get an exception. x = rng.read(32) - self.assertEquals(len(x), 32) + self.assertEqual(len(x), 32) def test_7_host_config_expose_issue_33(self): test_config_file = """ @@ -175,13 +175,13 @@ Host * f = StringIO(test_config_file) config = paramiko.util.parse_ssh_config(f) host = 'www13.example.com' - self.assertEquals( + self.assertEqual( paramiko.util.lookup_ssh_host_config(host, config), {'hostname': host, 'port': '22'} ) def test_8_eintr_retry(self): - self.assertEquals('foo', paramiko.util.retry_on_signal(lambda: 'foo')) + self.assertEqual('foo', paramiko.util.retry_on_signal(lambda: 'foo')) # Variables that are set by raises_intr intr_errors_remaining = [3] @@ -192,8 +192,8 @@ Host * intr_errors_remaining[0] -= 1 raise IOError(errno.EINTR, 'file', 'interrupted system call') self.assertTrue(paramiko.util.retry_on_signal(raises_intr) is None) - self.assertEquals(0, intr_errors_remaining[0]) - self.assertEquals(4, call_count[0]) + self.assertEqual(0, intr_errors_remaining[0]) + self.assertEqual(4, call_count[0]) def raises_ioerror_not_eintr(): raise IOError(errno.ENOENT, 'file', 'file not found') @@ -219,7 +219,7 @@ Host equals-delimited f = StringIO(conf) config = paramiko.util.parse_ssh_config(f) for host in ('space-delimited', 'equals-delimited'): - self.assertEquals( + self.assertEqual( host_config(host, config)['proxycommand'], 'foo bar=biz baz' ) @@ -245,7 +245,7 @@ Host * ('specific', "host specific port 37 lol"), ('portonly', "host portonly port 155"), ): - self.assertEquals( + self.assertEqual( host_config(host, config)['proxycommand'], val ) @@ -267,7 +267,7 @@ Host * f = StringIO(test_config_file) config = paramiko.util.parse_ssh_config(f) host = 'www13.example.com' - self.assertEquals( + self.assertEqual( paramiko.util.lookup_ssh_host_config(host, config), {'hostname': host, 'port': '8080'} ) @@ -295,7 +295,7 @@ ProxyCommand foo=bar:%h-%p f = StringIO(test_config_file) config = paramiko.util.parse_ssh_config(f) - self.assertEquals( + self.assertEqual( paramiko.util.lookup_ssh_host_config(host, config), values ) @@ -325,7 +325,7 @@ IdentityFile id_dsa22 f = StringIO(test_config_file) config = paramiko.util.parse_ssh_config(f) - self.assertEquals( + self.assertEqual( paramiko.util.lookup_ssh_host_config(host, config), values ) -- cgit v1.2.3 From 6d75c75e643c3a109075e86e72b08221c76088cc Mon Sep 17 00:00:00 2001 From: Scott Maxwell Date: Tue, 19 Nov 2013 10:09:08 -0800 Subject: Remove byte conversions and unhexlify calls that we only needed for Py2.5 support and use the `b` byte string marker instead --- demos/demo_server.py | 8 ++++---- paramiko/ecdsakey.py | 1 - paramiko/pipe.py | 4 ++-- paramiko/rsakey.py | 3 +-- paramiko/sftp_client.py | 2 +- tests/test_buffered_pipe.py | 18 +++++++++--------- tests/test_client.py | 2 +- tests/test_hostkeys.py | 18 +++++++++--------- tests/test_kex.py | 42 +++++++++++++++++++++--------------------- tests/test_message.py | 9 ++++----- tests/test_packetizer.py | 5 ++--- tests/test_pkey.py | 28 ++++++++++++++-------------- tests/test_sftp.py | 2 +- tests/test_transport.py | 18 +++++++++--------- tests/test_util.py | 4 ++-- 15 files changed, 80 insertions(+), 84 deletions(-) (limited to 'tests/test_packetizer.py') diff --git a/demos/demo_server.py b/demos/demo_server.py index 34a9bd5e..bb35258b 100644 --- a/demos/demo_server.py +++ b/demos/demo_server.py @@ -42,10 +42,10 @@ print('Read key: ' + u(hexlify(host_key.get_fingerprint()))) class Server (paramiko.ServerInterface): # 'data' is the output of base64.encodestring(str(key)) # (using the "user_rsa_key" files) - data = b('AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp' + \ - 'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC' + \ - 'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT' + \ - 'UWT10hcuO4Ks8=') + data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp' + b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC' + b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT' + b'UWT10hcuO4Ks8=') good_pub_key = paramiko.RSAKey(data=decodebytes(data)) def __init__(self): diff --git a/paramiko/ecdsakey.py b/paramiko/ecdsakey.py index 5f9dff29..3ecf0a58 100644 --- a/paramiko/ecdsakey.py +++ b/paramiko/ecdsakey.py @@ -21,7 +21,6 @@ L{ECDSAKey} """ import binascii -from binascii import unhexlify from ecdsa import SigningKey, VerifyingKey, der, curves from ecdsa.util import number_to_string, sigencode_string, sigencode_strings, sigdecode_strings from Crypto.Hash import SHA256, MD5 diff --git a/paramiko/pipe.py b/paramiko/pipe.py index 4c965465..619b807e 100644 --- a/paramiko/pipe.py +++ b/paramiko/pipe.py @@ -64,7 +64,7 @@ class PosixPipe (object): if self._set or self._closed: return self._set = True - os.write(self._wfd, b('*')) + os.write(self._wfd, b'*') def set_forever (self): self._forever = True @@ -110,7 +110,7 @@ class WindowsPipe (object): if self._set or self._closed: return self._set = True - self._wsock.send(b('*')) + self._wsock.send(b'*') def set_forever (self): self._forever = True diff --git a/paramiko/rsakey.py b/paramiko/rsakey.py index 0a271198..65f1463d 100644 --- a/paramiko/rsakey.py +++ b/paramiko/rsakey.py @@ -20,7 +20,6 @@ L{RSAKey} """ -from binascii import unhexlify from Crypto.PublicKey import RSA from Crypto.Hash import SHA, MD5 from Crypto.Cipher import DES3 @@ -32,7 +31,7 @@ from paramiko.ber import BER, BERException from paramiko.pkey import PKey from paramiko.ssh_exception import SSHException -SHA1_DIGESTINFO = unhexlify(b('3021300906052b0e03021a05000414')) +SHA1_DIGESTINFO = b'\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' class RSAKey (PKey): diff --git a/paramiko/sftp_client.py b/paramiko/sftp_client.py index 2b3eb187..41e763e2 100644 --- a/paramiko/sftp_client.py +++ b/paramiko/sftp_client.py @@ -48,7 +48,7 @@ def _to_unicode(s): except UnicodeError: return s -b_slash = b('/') +b_slash = b'/' class SFTPClient (BaseSFTP): """ diff --git a/tests/test_buffered_pipe.py b/tests/test_buffered_pipe.py index 5a088d80..b9d2bef4 100644 --- a/tests/test_buffered_pipe.py +++ b/tests/test_buffered_pipe.py @@ -49,35 +49,35 @@ class BufferedPipeTest(ParamikoTest): p.feed('hello.') self.assertTrue(p.read_ready()) data = p.read(6) - self.assertEqual(b('hello.'), data) + self.assertEqual(b'hello.', data) p.feed('plus/minus') - self.assertEqual(b('plu'), p.read(3)) - self.assertEqual(b('s/m'), p.read(3)) - self.assertEqual(b('inus'), p.read(4)) + self.assertEqual(b'plu', p.read(3)) + self.assertEqual(b's/m', p.read(3)) + self.assertEqual(b'inus', p.read(4)) p.close() self.assertTrue(not p.read_ready()) - self.assertEqual(b(''), p.read(1)) + self.assertEqual(b'', p.read(1)) def test_2_delay(self): p = BufferedPipe() self.assertTrue(not p.read_ready()) threading.Thread(target=delay_thread, args=(p,)).start() - self.assertEqual(b('a'), p.read(1, 0.1)) + self.assertEqual(b'a', p.read(1, 0.1)) try: p.read(1, 0.1) self.assertTrue(False) except PipeTimeout: pass - self.assertEqual(b('b'), p.read(1, 1.0)) - self.assertEqual(b(''), p.read(1)) + self.assertEqual(b'b', p.read(1, 1.0)) + self.assertEqual(b'', p.read(1)) def test_3_close_while_reading(self): p = BufferedPipe() threading.Thread(target=close_thread, args=(p,)).start() data = p.read(1, 1.0) - self.assertEqual(b(''), data) + self.assertEqual(b'', data) def test_4_or_pipe(self): p = pipe.make_pipe() diff --git a/tests/test_client.py b/tests/test_client.py index e96a426f..c508b83a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -45,7 +45,7 @@ class NullServer (paramiko.ServerInterface): return paramiko.AUTH_FAILED def check_auth_publickey(self, username, key): - if (key.get_name() == 'ssh-dss') and (hexlify(key.get_fingerprint()) == b('4478f0b9a23cc5182009ff755bc1d26c')): + if (key.get_name() == 'ssh-dss') and key.get_fingerprint() == b'\x44\x78\xf0\xb9\xa2\x3c\xc5\x18\x20\x09\xff\x75\x5b\xc1\xd2\x6c': return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED diff --git a/tests/test_hostkeys.py b/tests/test_hostkeys.py index 5290a4dc..9a7e3689 100644 --- a/tests/test_hostkeys.py +++ b/tests/test_hostkeys.py @@ -37,12 +37,12 @@ BGQ3GQ/Fc7SX6gkpXkwcZryoi4kNFhHu5LvHcZPdxXV1D+uTMfGS1eyd2Yz/DoNWXNAl8TI0cAsW\ 5ymME3bQ4J/k1IKxCtz/bAlAqFgKoc+EolMziDYqWIATtW0rYTJvzGAzTmMj80/QpsFH+Pc2M= """ -keyblob = b("""\ +keyblob = b"""\ AAAAB3NzaC1yc2EAAAABIwAAAIEA8bP1ZA7DCZDB9J0s50l31MBGQ3GQ/Fc7SX6gkpXkwcZryoi4k\ NFhHu5LvHcZPdxXV1D+uTMfGS1eyd2Yz/DoNWXNAl8TI0cAsW5ymME3bQ4J/k1IKxCtz/bAlAqFgK\ -oc+EolMziDYqWIATtW0rYTJvzGAzTmMj80/QpsFH+Pc2M=""") +oc+EolMziDYqWIATtW0rYTJvzGAzTmMj80/QpsFH+Pc2M=""" -keyblob_dss = b("""\ +keyblob_dss = b"""\ AAAAB3NzaC1kc3MAAACBAOeBpgNnfRzr/twmAQRu2XwWAp3CFtrVnug6s6fgwj/oLjYbVtjAy6pl/\ h0EKCWx2rf1IetyNsTxWrniA9I6HeDj65X1FyDkg6g8tvCnaNB8Xp/UUhuzHuGsMIipRxBxw9LF60\ 8EqZcj1E3ytktoW5B5OcjrkEoz3xG7C+rpIjYvAAAAFQDwz4UnmsGiSNu5iqjn3uTzwUpshwAAAIE\ @@ -50,7 +50,7 @@ AkxfFeY8P2wZpDjX0MimZl5wkoFQDL25cPzGBuB4OnB8NoUk/yjAHIIpEShw8V+LzouMK5CTJQo5+\ Ngw3qIch/WgRmMHy4kBq1SsXMjQCte1So6HBMvBPIW5SiMTmjCfZZiw4AYHK+B/JaOwaG9yRg2Ejg\ 4Ok10+XFDxlqZo8Y+wAAACARmR7CCPjodxASvRbIyzaVpZoJ/Z6x7dAumV+ysrV1BVYd0lYukmnjO\ 1kKBWApqpH1ve9XDQYN8zgxM4b16L21kpoWQnZtXrY3GZ4/it9kUgyB7+NwacIBlXa8cMDL7Q/69o\ -0d54U0X/NeX5QxuYR6OMJlrkQB7oiW/P/1mwjQgE=""") +0d54U0X/NeX5QxuYR6OMJlrkQB7oiW/P/1mwjQgE=""" class HostKeysTest (unittest.TestCase): @@ -68,7 +68,7 @@ class HostKeysTest (unittest.TestCase): self.assertEqual(1, len(list(hostdict.values())[0])) self.assertEqual(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEqual(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) + self.assertEqual(b'E6684DB30E109B67B70FF1DC5C7F1363', fp) def test_2_add(self): hostdict = paramiko.HostKeys('hostfile.temp') @@ -78,7 +78,7 @@ class HostKeysTest (unittest.TestCase): self.assertEqual(3, len(list(hostdict))) x = hostdict['foo.example.com'] fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() - self.assertEqual(b('7EC91BB336CB6D810B124B1353C32396'), fp) + self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp) self.assertTrue(hostdict.check('foo.example.com', key)) def test_3_dict(self): @@ -90,7 +90,7 @@ class HostKeysTest (unittest.TestCase): x = hostdict.get('secure.example.com', None) self.assertTrue(x is not None) fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper() - self.assertEqual(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) + self.assertEqual(b'E6684DB30E109B67B70FF1DC5C7F1363', fp) i = 0 for key in hostdict: i += 1 @@ -112,6 +112,6 @@ class HostKeysTest (unittest.TestCase): self.assertEqual(1, len(list(hostdict.values())[1])) self.assertEqual(1, len(list(hostdict.values())[2])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEqual(b('7EC91BB336CB6D810B124B1353C32396'), fp) + self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp) fp = hexlify(hostdict['secure.example.com']['ssh-dss'].get_fingerprint()).upper() - self.assertEqual(b('4478F0B9A23CC5182009FF755BC1D26C'), fp) + self.assertEqual(b'4478F0B9A23CC5182009FF755BC1D26C', fp) diff --git a/tests/test_kex.py b/tests/test_kex.py index dbe377a4..e69c051b 100644 --- a/tests/test_kex.py +++ b/tests/test_kex.py @@ -38,9 +38,9 @@ class FakeKey (object): def __str__(self): return 'fake-key' def asbytes(self): - return b('fake-key') + return b'fake-key' def sign_ssh_data(self, rng, H): - return b('fake-sig') + return b'fake-sig' class FakeModulusPack (object): @@ -91,7 +91,7 @@ class KexTest (unittest.TestCase): transport.server_mode = False kex = KexGroup1(transport) kex.start_kex() - x = b('1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') + x = b'1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual((paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect) @@ -102,10 +102,10 @@ class KexTest (unittest.TestCase): msg.add_string('fake-sig') msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_REPLY, msg) - H = b('03079780F3D3AD0B3C6DB30C8D21685F367A86D2') + H = b'03079780F3D3AD0B3C6DB30C8D21685F367A86D2' self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) - self.assertEqual((b('fake-host-key'), b('fake-sig')), transport._verify) + self.assertEqual((b'fake-host-key', b'fake-sig'), transport._verify) self.assertTrue(transport._activated) def test_2_group1_server(self): @@ -119,8 +119,8 @@ class KexTest (unittest.TestCase): msg.add_mpint(69) msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_INIT, msg) - H = b('B16BF34DD10945EDE84E9C1EF24A14BFDC843389') - x = b('1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') + H = b'B16BF34DD10945EDE84E9C1EF24A14BFDC843389' + x = b'1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) @@ -131,7 +131,7 @@ class KexTest (unittest.TestCase): transport.server_mode = False kex = KexGex(transport) kex.start_kex() - x = b('22000004000000080000002000') + x = b'22000004000000080000002000' self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) @@ -140,7 +140,7 @@ class KexTest (unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = b('20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') + x = b'20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) @@ -150,10 +150,10 @@ class KexTest (unittest.TestCase): msg.add_string('fake-sig') msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) - H = b('A265563F2FA87F1A89BF007EE90D58BE2E4A4BD0') + H = b'A265563F2FA87F1A89BF007EE90D58BE2E4A4BD0' self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) - self.assertEqual((b('fake-host-key'), b('fake-sig')), transport._verify) + self.assertEqual((b'fake-host-key', b'fake-sig'), transport._verify) self.assertTrue(transport._activated) def test_4_gex_old_client(self): @@ -161,7 +161,7 @@ class KexTest (unittest.TestCase): transport.server_mode = False kex = KexGex(transport) kex.start_kex(_test_old_style=True) - x = b('1E00000800') + x = b'1E00000800' self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect) @@ -170,7 +170,7 @@ class KexTest (unittest.TestCase): msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) - x = b('20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4') + x = b'20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4' self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect) @@ -180,10 +180,10 @@ class KexTest (unittest.TestCase): msg.add_string('fake-sig') msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) - H = b('807F87B269EF7AC5EC7E75676808776A27D5864C') + H = b'807F87B269EF7AC5EC7E75676808776A27D5864C' self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) - self.assertEqual((b('fake-host-key'), b('fake-sig')), transport._verify) + self.assertEqual((b'fake-host-key', b'fake-sig'), transport._verify) self.assertTrue(transport._activated) def test_5_gex_server(self): @@ -199,7 +199,7 @@ class KexTest (unittest.TestCase): msg.add_int(4096) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) - x = b('1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102') + x = b'1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102' self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) @@ -208,8 +208,8 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 - H = b('CE754197C21BF3452863B4F44D0B3951F12516EF') - x = b('210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') + H = b'CE754197C21BF3452863B4F44D0B3951F12516EF' + x = b'210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) @@ -226,7 +226,7 @@ class KexTest (unittest.TestCase): msg.add_int(2048) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) - x = b('1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102') + x = b'1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102' self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual((paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect) @@ -235,8 +235,8 @@ class KexTest (unittest.TestCase): msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 - H = b('B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B') - x = b('210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967') + H = b'B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B' + x = b'210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967' self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) diff --git a/tests/test_message.py b/tests/test_message.py index cb815f9f..4da52cfb 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -21,17 +21,16 @@ Some unit tests for ssh protocol message blocks. """ import unittest -from binascii import unhexlify from paramiko.message import Message from paramiko.common import * class MessageTest (unittest.TestCase): - __a = unhexlify(b('000000170760e09000000001710000000568656c6c6f000003e8')) + (b('x') * 1000) - __b = unhexlify(b('0100f3003f00000010687565792c64657765792c6c6f756965')) - __c = unhexlify(b('00000000000000050000f5e4d3c2b10900000001110000000700f5e4d3c2b109000000069a1b2c3d4ef7')) - __d = unhexlify(b('00000005ff000000051122334455ff0000000a00f00000000000000000010000000363617400000003612c62')) + __a = b'\x00\x00\x00\x17\x07\x60\xe0\x90\x00\x00\x00\x01\x71\x00\x00\x00\x05\x68\x65\x6c\x6c\x6f\x00\x00\x03\xe8' + b'x' * 1000 + __b = b'\x01\x00\xf3\x00\x3f\x00\x00\x00\x10\x68\x75\x65\x79\x2c\x64\x65\x77\x65\x79\x2c\x6c\x6f\x75\x69\x65' + __c = b'\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x01\x11\x00\x00\x00\x07\x00\xf5\xe4\xd3\xc2\xb1\x09\x00\x00\x00\x06\x9a\x1b\x2c\x3d\x4e\xf7' + __d = b'\x00\x00\x00\x05\xff\x00\x00\x00\x05\x11\x22\x33\x44\x55\xff\x00\x00\x00\x0a\x00\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x63\x61\x74\x00\x00\x00\x03\x61\x2c\x62' def test_1_encode(self): msg = Message() diff --git a/tests/test_packetizer.py b/tests/test_packetizer.py index 43dea38a..5c36fed6 100644 --- a/tests/test_packetizer.py +++ b/tests/test_packetizer.py @@ -21,7 +21,6 @@ Some unit tests for the ssh2 protocol in Transport. """ import unittest -from binascii import unhexlify from tests.loop import LoopSocket from Crypto.Cipher import AES from Crypto.Hash import SHA, HMAC @@ -55,7 +54,7 @@ class PacketizerTest (unittest.TestCase): data = rsock.recv(100) # 32 + 12 bytes of MAC = 44 self.assertEqual(44, len(data)) - self.assertEqual(unhexlify(b('439197bd5b50ac2587c2c46bc7e938c0')), data[:16]) + self.assertEqual(b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0', data[:16]) def test_2_read (self): rsock = LoopSocket() @@ -66,7 +65,7 @@ class PacketizerTest (unittest.TestCase): p.set_hexdump(True) cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16) p.set_inbound_cipher(cipher, 16, SHA, 12, x1f * 20) - wsock.send(unhexlify(b('439197bd5b50ac2587c2c46bc7e938c090d216560d717361387c4c3dfb977de26e03b1a0c21cd641414cb459'))) + wsock.send(b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0\x90\xd2\x16\x56\x0d\x71\x73\x61\x38\x7c\x4c\x3d\xfb\x97\x7d\xe2\x6e\x03\xb1\xa0\xc2\x1c\xd6\x41\x41\x4c\xb4\x59') cmd, m = p.read_message() self.assertEqual(100, cmd) self.assertEqual(100, m.get_int()) diff --git a/tests/test_pkey.py b/tests/test_pkey.py index 19c5c698..2e565a5f 100644 --- a/tests/test_pkey.py +++ b/tests/test_pkey.py @@ -20,7 +20,7 @@ Some unit tests for public/private key objects. """ -from binascii import hexlify, unhexlify +from binascii import hexlify import unittest from paramiko import RSAKey, DSSKey, ECDSAKey, Message, util from paramiko.common import rng, StringIO, byte_chr, b, bytes @@ -77,7 +77,7 @@ ADRvOqQ5R98Sxst765CAqXmRtz8vwoD96g== -----END EC PRIVATE KEY----- """ -x1234 = unhexlify(b('01020304')) +x1234 = b'\x01\x02\x03\x04' class KeyTest (unittest.TestCase): @@ -91,7 +91,7 @@ class KeyTest (unittest.TestCase): def test_1_generate_key_bytes(self): from Crypto.Hash import MD5 key = util.generate_key_bytes(MD5, x1234, 'happy birthday', 30) - exp = unhexlify(b('61E1F272F4C1C4561586BD322498C0E924672780F47BB37DDA7D54019E64')) + exp = b'\x61\xE1\xF2\x72\xF4\xC1\xC4\x56\x15\x86\xBD\x32\x24\x98\xC0\xE9\x24\x67\x27\x80\xF4\x7B\xB3\x7D\xDA\x7D\x54\x01\x9E\x64' self.assertEqual(exp, key) def test_2_load_rsa(self): @@ -165,7 +165,7 @@ class KeyTest (unittest.TestCase): def test_8_sign_rsa(self): # verify that the rsa private key can sign and verify key = RSAKey.from_private_key_file(test_path('test_rsa.key')) - msg = key.sign_ssh_data(rng, b('ice weasels')) + msg = key.sign_ssh_data(rng, b'ice weasels') self.assertTrue(type(msg) is Message) msg.rewind() self.assertEqual('ssh-rsa', msg.get_text()) @@ -173,12 +173,12 @@ class KeyTest (unittest.TestCase): self.assertEqual(sig, msg.get_binary()) msg.rewind() pub = RSAKey(data=key.asbytes()) - self.assertTrue(pub.verify_ssh_sig(b('ice weasels'), msg)) + self.assertTrue(pub.verify_ssh_sig(b'ice weasels', msg)) def test_9_sign_dss(self): # verify that the dss private key can sign and verify key = DSSKey.from_private_key_file(test_path('test_dss.key')) - msg = key.sign_ssh_data(rng, b('ice weasels')) + msg = key.sign_ssh_data(rng, b'ice weasels') self.assertTrue(type(msg) is Message) msg.rewind() self.assertEqual('ssh-dss', msg.get_text()) @@ -188,19 +188,19 @@ class KeyTest (unittest.TestCase): self.assertEqual(40, len(msg.get_binary())) msg.rewind() pub = DSSKey(data=key.asbytes()) - self.assertTrue(pub.verify_ssh_sig(b('ice weasels'), msg)) + self.assertTrue(pub.verify_ssh_sig(b'ice weasels', msg)) def test_A_generate_rsa(self): key = RSAKey.generate(1024) - msg = key.sign_ssh_data(rng, b('jerri blank')) + msg = key.sign_ssh_data(rng, b'jerri blank') msg.rewind() - self.assertTrue(key.verify_ssh_sig(b('jerri blank'), msg)) + self.assertTrue(key.verify_ssh_sig(b'jerri blank', msg)) def test_B_generate_dss(self): key = DSSKey.generate(1024) - msg = key.sign_ssh_data(rng, b('jerri blank')) + msg = key.sign_ssh_data(rng, b'jerri blank') msg.rewind() - self.assertTrue(key.verify_ssh_sig(b('jerri blank'), msg)) + self.assertTrue(key.verify_ssh_sig(b'jerri blank', msg)) def test_10_load_ecdsa(self): key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) @@ -219,7 +219,7 @@ class KeyTest (unittest.TestCase): self.assertEqual(key, key2) def test_11_load_ecdsa_password(self): - key = ECDSAKey.from_private_key_file(test_path('test_ecdsa_password.key'), b('television')) + key = ECDSAKey.from_private_key_file(test_path('test_ecdsa_password.key'), b'television') self.assertEqual('ecdsa-sha2-nistp256', key.get_name()) exp_ecdsa = b(FINGER_ECDSA.split()[1].replace(':', '')) my_ecdsa = hexlify(key.get_fingerprint()) @@ -239,7 +239,7 @@ class KeyTest (unittest.TestCase): def test_13_sign_ecdsa(self): # verify that the rsa private key can sign and verify key = ECDSAKey.from_private_key_file(test_path('test_ecdsa.key')) - msg = key.sign_ssh_data(rng, b('ice weasels')) + msg = key.sign_ssh_data(rng, b'ice weasels') self.assertTrue(type(msg) is Message) msg.rewind() self.assertEqual('ecdsa-sha2-nistp256', msg.get_text()) @@ -250,4 +250,4 @@ class KeyTest (unittest.TestCase): msg.rewind() pub = ECDSAKey(data=key.asbytes()) - self.assertTrue(pub.verify_ssh_sig(b('ice weasels'), msg)) + self.assertTrue(pub.verify_ssh_sig(b'ice weasels', msg)) diff --git a/tests/test_sftp.py b/tests/test_sftp.py index f78047bb..271c08b5 100755 --- a/tests/test_sftp.py +++ b/tests/test_sftp.py @@ -549,7 +549,7 @@ class SFTPTest (unittest.TestCase): fd, localname = mkstemp() os.close(fd) - text = b('All I wanted was a plastic bunny rabbit.\n') + text = b'All I wanted was a plastic bunny rabbit.\n' with open(localname, 'wb') as f: f.write(text) saved_progress = [] diff --git a/tests/test_transport.py b/tests/test_transport.py index 6f6843ba..876759c8 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -20,7 +20,7 @@ Some unit tests for the ssh2 protocol in Transport. """ -from binascii import hexlify, unhexlify +from binascii import hexlify import select import socket import sys @@ -159,10 +159,10 @@ class TransportTest(ParamikoTest): def test_2_compute_key(self): self.tc.K = 123281095979686581523377256114209720774539068973101330872763622971399429481072519713536292772709507296759612401802191955568143056534122385270077606457721553469730659233569339356140085284052436697480759510519672848743794433460113118986816826624865291116513647975790797391795651716378444844877749505443714557929 - self.tc.H = unhexlify(b('0C8307CDE6856FF30BA93684EB0F04C2520E9ED3')) + self.tc.H = b'\x0C\x83\x07\xCD\xE6\x85\x6F\xF3\x0B\xA9\x36\x84\xEB\x0F\x04\xC2\x52\x0E\x9E\xD3' self.tc.session_id = self.tc.H key = self.tc._compute_key('C', 32) - self.assertEqual(b('207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995'), + self.assertEqual(b'207E66594CA87C44ECCBA3B3CD39FDDB378E6FDB0F97C54B2AA0CFBF900CD995', hexlify(key).upper()) def test_3_simple(self): @@ -361,7 +361,7 @@ class TransportTest(ParamikoTest): self.assertEqual([], w) self.assertEqual([], e) - self.assertEqual(b('hello\n'), chan.recv(6)) + self.assertEqual(b'hello\n', chan.recv(6)) # and, should be dead again now r, w, e = select.select([chan], [], [], 0.1) @@ -462,7 +462,7 @@ class TransportTest(ParamikoTest): self.assertEqual(6093, requested[0][1]) x11_server.send('hello') - self.assertEqual(b('hello'), x11_client.recv(5)) + self.assertEqual(b'hello', x11_client.recv(5)) x11_server.close() x11_client.close() @@ -495,7 +495,7 @@ class TransportTest(ParamikoTest): cch = self.tc.accept() sch.send('hello') - self.assertEqual(b('hello'), cch.recv(5)) + self.assertEqual(b'hello', cch.recv(5)) sch.close() cch.close() ss.close() @@ -527,12 +527,12 @@ class TransportTest(ParamikoTest): cch.connect(self.server._tcpip_dest) ss, _ = greeting_server.accept() - ss.send(b('Hello!\n')) + ss.send(b'Hello!\n') ss.close() sch.send(cch.recv(8192)) sch.close() - self.assertEqual(b('Hello!\n'), cs.recv(7)) + self.assertEqual(b'Hello!\n', cs.recv(7)) cs.close() def test_G_stderr_select(self): @@ -563,7 +563,7 @@ class TransportTest(ParamikoTest): self.assertEqual([], w) self.assertEqual([], e) - self.assertEqual(b('hello\n'), chan.recv_stderr(6)) + self.assertEqual(b'hello\n', chan.recv_stderr(6)) # and, should be dead again now r, w, e = select.select([chan], [], [], 0.1) diff --git a/tests/test_util.py b/tests/test_util.py index be107195..4f85c391 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -137,7 +137,7 @@ class UtilTest(ParamikoTest): ) def test_4_generate_key_bytes(self): - x = paramiko.util.generate_key_bytes(SHA, b('ABCDEFGH'), 'This is my secret passphrase.', 64) + x = paramiko.util.generate_key_bytes(SHA, b'ABCDEFGH', 'This is my secret passphrase.', 64) hex = ''.join(['%02x' % byte_ord(c) for c in x]) self.assertEqual(hex, '9110e2f6793b69363e58173e9436b13a5a4b339005741d5c680e505f57d871347b4239f14fb5c46e857d5e100424873ba849ac699cea98d729e57b3e84378e8b') @@ -150,7 +150,7 @@ class UtilTest(ParamikoTest): self.assertEqual(1, len(list(hostdict.values())[0])) self.assertEqual(1, len(list(hostdict.values())[1])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() - self.assertEqual(b('E6684DB30E109B67B70FF1DC5C7F1363'), fp) + self.assertEqual(b'E6684DB30E109B67B70FF1DC5C7F1363', fp) finally: os.unlink('hostfile.temp') -- cgit v1.2.3