Skip to content

Commit

Permalink
added py3compat layer
Browse files Browse the repository at this point in the history
  • Loading branch information
tintinweb committed Mar 4, 2017
1 parent fd08cf8 commit e0f3be0
Show file tree
Hide file tree
Showing 12 changed files with 284 additions and 75 deletions.
9 changes: 5 additions & 4 deletions examples/client_hello_twice.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# If you installed this package via pip, you just need to execute this
from scapy.layers.ssl_tls import *

from scapy_ssl_tls.py3compat import bytes, py2range
import socket

if __name__ == "__main__":
Expand All @@ -31,19 +32,19 @@
# create TLS Handhsake / Client Hello packet
p = TLSRecord(version="TLS_1_0") / TLSHandshakes(handshakes=[TLSHandshake() /
TLSClientHello(version="TLS_1_0",
compression_methods=range(0xff),
cipher_suites=range(0xff))])
compression_methods=py2range(0xff),
cipher_suites=py2range(0xff))])

p.show()

print ("sending TLS payload")
s.sendall(str(p))
s.sendall(bytes(p))
resp = s.recv(1024 * 8)
print ("received, %s" % repr(resp))
SSL(resp).show()

print ("sending TLS payload")
s.sendall(str(p))
s.sendall(bytes(p))
resp = s.recv(1024 * 8)
print ("received, %s" % repr(resp))
SSL(resp).show()
Expand Down
8 changes: 5 additions & 3 deletions examples/client_hello_valid.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# If you installed this package via pip, you just need to execute this
from scapy.layers.ssl_tls import *

from scapy_ssl_tls.py3compat import bytes, py2range
import socket

if __name__ == "__main__":
Expand All @@ -31,13 +32,14 @@

# create TLS Handhsake / Client Hello packet
p = TLSRecord() / TLSHandshakes(handshakes=[TLSHandshake() /
TLSClientHello(compression_methods=range(0xff)[::-1],
cipher_suites=range(0xff))])
TLSClientHello(compression_methods=py2range(0xff)[::-1],
cipher_suites=py2range(0xff))])


p.show()

print ("sending TLS payload")
s.sendall(str(p))
s.sendall(bytes(p))
resp = s.recv(1024 * 8)
print ("received, %s" % repr(resp))
SSL(resp).show()
Expand Down
2 changes: 1 addition & 1 deletion examples/security_scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ def _scan_supported_protocol_versions(
versionlist=(
(k,
v) for k,
v in TLS_VERSIONS.iteritems() if v.startswith("TLS_") or v.startswith("SSL_"))):
v in TLS_VERSIONS.items() if v.startswith("TLS_") or v.startswith("SSL_"))):
for magic, name in versionlist:
pkt = TLSRecord(version=magic) / \
TLSHandshakes(handshakes=[TLSHandshake() /
Expand Down
7 changes: 4 additions & 3 deletions examples/sslv2_client_hello_valid.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# If you installed this package via pip, you just need to execute this
from scapy.layers.ssl_tls import *

from scapy_ssl_tls.py3compat import bytes
import socket

if __name__ == "__main__":
Expand All @@ -30,15 +31,15 @@
s.connect(target)

# create SSLv2 Handhsake / Client Hello packet
p = SSLv2Record() / SSLv2ClientHello(cipher_suites=SSLv2_CIPHER_SUITES.keys(),
p = SSLv2Record() / SSLv2ClientHello(cipher_suites=list(SSLv2_CIPHER_SUITES.keys()),
challenge='a' * 16,
session_id='a' * 16)
p.show()

SSL(str(p)).show()
SSL(bytes(p)).show()

print ("sending TLS payload")
s.sendall(str(p))
s.sendall(bytes(p))
resp = s.recv(8 * 1024)
print ("received, %s" % repr(resp))
SSL(resp).show()
Expand Down
12 changes: 5 additions & 7 deletions scapy_ssl_tls/pkcs7.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
# -*- coding: UTF-8 -*-
# Author : janglin <http://japrogbits.blogspot.co.at>
# http://japrogbits.blogspot.co.at/2011/02/using-encrypted-data-between-python-and.html
import binascii
import StringIO

import scapy_ssl_tls.py3compat as py3compat

class PKCS7Encoder(object):

Expand Down Expand Up @@ -43,7 +41,7 @@ def decode(self, text):
Remove the PKCS#7 padding from a text string
"""
nl = len(text)
val = int(binascii.hexlify(text[-1]), 16)
val = int(py3compat.hexlify(text[-1]), 16)
if val > self.k:
raise ValueError('Input is not padded or padding is corrupt')

Expand All @@ -59,8 +57,8 @@ def encode(self, text):

def get_padding(self, text):
l = len(text)
output = StringIO.StringIO()
output = py3compat.StringIO()
val = self.k - (l % self.k)
for _ in xrange(val):
for _ in py3compat.xrange(val):
output.write('%02x' % val)
return binascii.unhexlify(output.getvalue())
return py3compat.unhexlify(output.getvalue())
209 changes: 209 additions & 0 deletions scapy_ssl_tls/py3compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
#
#
# https://github.com/jbouse-debian/paramiko/blob/master/paramiko/py3compat.py
import sys
import base64

__all__ = ['PY2', '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', 'builtins', 'str', 'py2range']

PY2 = sys.version_info[0] < 3

if PY2:
string_types = basestring
text_type = unicode
bytes_types = str
bytes = str
integer_types = (int, long)
long = long
input = raw_input
decodebytes = base64.decodestring
encodebytes = base64.encodestring

xrange = xrange
py2range = range

import __builtin__ as builtins


def bytestring(s): # NOQA
if isinstance(s, unicode):
return s.encode('utf-8')
return s


byte_ord = ord # NOQA
byte_chr = chr # NOQA


def byte_mask(c, mask):
return chr(ord(c) & mask)


def b(s, encoding='utf8'): # NOQA
"""cast unicode or bytes to bytes"""
if isinstance(s, str):
return s
elif isinstance(s, unicode):
return s.encode(encoding)
elif isinstance(s, buffer):
return s
else:
raise TypeError("Expected unicode or bytes, got %r" % s)


def u(s, encoding='utf8'): # NOQA
"""cast bytes or unicode to unicode"""
if isinstance(s, str):
return s.decode(encoding)
elif isinstance(s, unicode):
return s
elif isinstance(s, buffer):
return s.decode(encoding)
else:
raise TypeError("Expected unicode or bytes, got %r" % s)


def b2s(s):
return s

def tobytes(s):
if isinstance(s, unicode):
return s.encode("latin-1")
else:
return ''.join(s)

try:
import cStringIO

StringIO = cStringIO.StringIO # NOQA
except ImportError:
import StringIO

StringIO = StringIO.StringIO # NOQA

BytesIO = StringIO

from binascii import hexlify, unhexlify

def is_callable(c): # NOQA
return callable(c)


def get_next(c): # NOQA
return c.next


def next(c):
return c.next()

# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31


try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1) # NOQA
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1) # NOQA
del X
else:
import collections
import struct
import builtins
string_types = str, bytearray, bytes
text_type = str
bytes = bytes
bytes_types = bytes
integer_types = int
class long(int):
pass
input = input
decodebytes = base64.decodebytes
encodebytes = base64.encodebytes
xrange = range

def py2range(it):
return list(range(it))

def bytestring(s):
return s

def byte_ord(c):
# In case we're handed a string instead of an int.
if not isinstance(c, int):
c = ord(c)
return c

def byte_chr(c):
assert isinstance(c, int)
return struct.pack('B', c)

def byte_mask(c, mask):
assert isinstance(c, int)
return struct.pack('B', c & mask)

def b(s, encoding='utf8'):
"""cast unicode or bytes to bytes"""
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return s.encode(encoding)
else:
raise TypeError("Expected unicode or bytes, got %r" % s)

def u(s, encoding='utf8'):
"""cast bytes or unicode to unicode"""
if isinstance(s, bytes):
return s.decode(encoding)
elif isinstance(s, str):
return s
else:
raise TypeError("Expected unicode or bytes, got %r" % s)

def b2s(s):
return s.decode() if isinstance(s, bytes) else s

def tobytes(s):
if isinstance(s,bytes):
return s
else:
if isinstance(s,str):
return s.encode("latin-1")
else:
return bytes([s])

import io
StringIO = io.StringIO # NOQA
BytesIO = io.BytesIO # NOQA

import binascii

hexlify = binascii.hexlify
if sys.version_info[1] <= 2:
_unhexlify = binascii.unhexlify


def unhexlify(x):
return _unhexlify(tobytes(x))
else:
unhexlify = binascii.unhexlify
del binascii

def is_callable(c):
return isinstance(c, collections.Callable)

def get_next(c):
return c.__next__

next = next

MAXSIZE = sys.maxsize # NOQA
Loading

0 comments on commit e0f3be0

Please sign in to comment.