Python port of ShadowsocksR
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

246 lines
6.9 KiB

12 years ago
#!/usr/bin/env python
#
# Copyright 2012-2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
12 years ago
#
# http://www.apache.org/licenses/LICENSE-2.0
12 years ago
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
12 years ago
from __future__ import absolute_import, division, print_function, \
with_statement
import os
12 years ago
import sys
import hashlib
import logging
7 years ago
from shadowsocks import common, lru_cache
from shadowsocks.crypto import rc4_md5, openssl, sodium, table
10 years ago
method_supported = {}
method_supported.update(rc4_md5.ciphers)
method_supported.update(openssl.ciphers)
method_supported.update(sodium.ciphers)
method_supported.update(table.ciphers)
12 years ago
def random_string(length):
try:
return os.urandom(length)
except NotImplementedError as e:
return openssl.rand_bytes(length)
7 years ago
cached_keys = lru_cache.LRUCache(timeout=180)
11 years ago
def try_cipher(key, method=None):
Encryptor(key, method)
12 years ago
7 years ago
def EVP_BytesToKey(password, key_len, iv_len, cache):
12 years ago
# equivalent to OpenSSL's EVP_BytesToKey() with count 1
# so that we make the same key and iv as nodejs version
cached_key = '%s-%d-%d' % (password, key_len, iv_len)
r = cached_keys.get(cached_key, None)
11 years ago
if r:
return r
12 years ago
m = []
i = 0
while len(b''.join(m)) < (key_len + iv_len):
12 years ago
md5 = hashlib.md5()
data = password
if i > 0:
data = m[i - 1] + password
md5.update(data)
m.append(md5.digest())
i += 1
ms = b''.join(m)
12 years ago
key = ms[:key_len]
iv = ms[key_len:key_len + iv_len]
7 years ago
if cache:
cached_keys[cached_key] = (key, iv)
cached_keys.sweep()
10 years ago
return key, iv
12 years ago
class Encryptor(object):
7 years ago
def __init__(self, key, method, iv = None, cache = False):
self.key = key
self.method = method
self.iv = None
self.iv_sent = False
self.cipher_iv = b''
self.iv_buf = b''
self.cipher_key = b''
self.decipher = None
7 years ago
self.cache = cache
method = method.lower()
self._method_info = self.get_method_info(method)
if self._method_info:
8 years ago
if iv is None or len(iv) != self._method_info[1]:
self.cipher = self.get_cipher(key, method, 1,
random_string(self._method_info[1]))
8 years ago
else:
self.cipher = self.get_cipher(key, method, 1, iv)
12 years ago
else:
logging.error('method %s not supported' % method)
sys.exit(1)
def get_method_info(self, method):
method = method.lower()
m = method_supported.get(method)
return m
def iv_len(self):
return len(self.cipher_iv)
def get_cipher(self, password, method, op, iv):
10 years ago
password = common.to_bytes(password)
m = self._method_info
if m[0] > 0:
7 years ago
key, iv_ = EVP_BytesToKey(password, m[0], m[1], self.cache)
else:
# key_length == 0 indicates we should use the key directly
key, iv = password, b''
iv = iv[:m[1]]
if op == 1:
# this iv is for cipher not decipher
self.cipher_iv = iv[:m[1]]
self.cipher_key = key
return m[2](method, key, iv, op)
12 years ago
def encrypt(self, buf):
if len(buf) == 0:
7 years ago
if not self.iv_sent:
self.iv_sent = True
return self.cipher_iv
return buf
if self.iv_sent:
return self.cipher.update(buf)
12 years ago
else:
self.iv_sent = True
return self.cipher_iv + self.cipher.update(buf)
12 years ago
def decrypt(self, buf):
if len(buf) == 0:
return buf
if self.decipher is not None: #optimize
return self.decipher.update(buf)
decipher_iv_len = self._method_info[1]
if len(self.iv_buf) <= decipher_iv_len:
self.iv_buf += buf
if len(self.iv_buf) > decipher_iv_len:
decipher_iv = self.iv_buf[:decipher_iv_len]
self.decipher = self.get_cipher(self.key, self.method, 0,
iv=decipher_iv)
buf = self.iv_buf[decipher_iv_len:]
9 years ago
del self.iv_buf
return self.decipher.update(buf)
else:
return b''
11 years ago
7 years ago
def dispose(self):
if self.decipher is not None:
self.decipher.clean()
self.decipher = None
11 years ago
def encrypt_all(password, method, op, data):
result = []
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
10 years ago
if key_len > 0:
7 years ago
key, _ = EVP_BytesToKey(password, key_len, iv_len, True)
10 years ago
else:
key = password
if op:
iv = random_string(iv_len)
result.append(iv)
11 years ago
else:
iv = data[:iv_len]
data = data[iv_len:]
cipher = m(method, key, iv, op)
result.append(cipher.update(data))
return b''.join(result)
def encrypt_key(password, method):
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
if key_len > 0:
7 years ago
key, _ = EVP_BytesToKey(password, key_len, iv_len, True)
else:
key = password
return key
def encrypt_iv_len(method):
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
return iv_len
def encrypt_new_iv(method):
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
return random_string(iv_len)
def encrypt_all_iv(key, method, op, data, ref_iv):
result = []
method = method.lower()
(key_len, iv_len, m) = method_supported[method]
if op:
iv = ref_iv[0]
result.append(iv)
else:
iv = data[:iv_len]
data = data[iv_len:]
ref_iv[0] = iv
cipher = m(method, key, iv, op)
result.append(cipher.update(data))
return b''.join(result)
CIPHERS_TO_TEST = [
10 years ago
'aes-128-cfb',
'aes-256-cfb',
'rc4-md5',
'salsa20',
'chacha20',
'table',
]
def test_encryptor():
from os import urandom
plain = urandom(10240)
for method in CIPHERS_TO_TEST:
logging.warn(method)
encryptor = Encryptor(b'key', method)
decryptor = Encryptor(b'key', method)
cipher = encryptor.encrypt(plain)
plain2 = decryptor.decrypt(cipher)
assert plain == plain2
def test_encrypt_all():
from os import urandom
plain = urandom(10240)
for method in CIPHERS_TO_TEST:
logging.warn(method)
cipher = encrypt_all(b'key', method, 1, plain)
plain2 = encrypt_all(b'key', method, 0, cipher)
assert plain == plain2
if __name__ == '__main__':
10 years ago
test_encrypt_all()
test_encryptor()