def __init__(self, hxsServer, ctimeout, parentproxy, manager): if not isinstance(hxsServer, ParentProxy): hxsServer = ParentProxy(hxsServer, hxsServer) self.hxsServer = hxsServer self.name = self.hxsServer.name self.timeout = ctimeout self._manager = manager self._last_ping = 0 self._sock = None if parentproxy and not isinstance(parentproxy, ParentProxy): parentproxy = ParentProxy(parentproxy, parentproxy) self.parentproxy = parentproxy _psk = urlparse.parse_qs(self.hxsServer.parse.query).get('PSK', [''])[0] self.method = urlparse.parse_qs(self.hxsServer.parse.query).get('method', [DEFAULT_METHOD])[0].lower() self.hash_algo = urlparse.parse_qs(self.hxsServer.parse.query).get('hash', [DEFAULT_HASH])[0].upper() self._connection_write_lock = RLock() self.__pskcipher = Encryptor(_psk, self.method) self.__cipher = None self._next_stream_id = 1 self._client_sock = {} self._client_status = {} self._stream_status = {} self.getKey() # start read from hxsocks2 connection Thread(target=self.read_from_connection).start()
def __encrypt_decrypt_data_in_memory(self, key): """ По ключу зашифровывает данные в парсере :param key: Ключ шифрования """ current_encryptor = Encryptor(key) current_encryptor.drop_key_pointer() data_snapshot = self.__parser.get_result() for line_num, line in enumerate(data_snapshot): for block_num, block in enumerate(line): self.__parser.replace_block( line_num, block_num, current_encryptor.encrypt_decrypt_block(block))
class Socks5Server(SocketServer.StreamRequestHandler): key = 'rp1qaz@WSX' crypto = Encryptor('rp1qaz@WSX', 'table') # crypto = crypt_aes(key+'000000') def handle_tcp(self, sock, remote): fdset = [sock, remote] while True: r, w, e = select.select(fdset, [], []) if sock in r: # length = sock.recv(4) # if not length: # break # data = rc4(sock.recv(int(decrypt('rp1qaz@WSX',length))),op='decode',public_key='rp1qaz@WSX') data = sock.recv(4096) if len(data) <= 0: break # print str(len(data)) + '<<<' remote.send(self.crypto.decrypt(data)) if remote in r: # data = remote.recv(2048) # if len(data) <= 0: # break # data = rc4(data,op='encode',public_key='rp1qaz@WSX') # length = str(len(data)) # if len(length) < 4: # length = (4 - len(length)) * '0' + length # print str(len(data)) + '>>>' # sock.send(encrypt('rp1qaz@WSX',length) + data) data = remote.recv(4096) if len(data) <= 0: break sock.send(self.crypto.encrypt(data)) def handle(self): try: print 'socks connection from ', self.client_address sock = self.connection # 1. Version length = sock.recv(4) remote_ip_port = rc4(sock.recv(int(length)), op='decode', public_key='rp1qaz@WSX') print remote_ip_port if remote_ip_port: remote_ip_port = (remote_ip_port.split(',')[0], int(remote_ip_port.split(',')[1])) remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote.connect(remote_ip_port) print 'Tcp connect to', remote_ip_port sock.send('0') self.handle_tcp(sock, remote) except socket.error, e: print 'socket error: %s' % e
def load_encrypted_file_into_memory(self, key=None): """ Загружает данные из файла в парсер если Key - не None, то перед этим происходит дешифровка считанных данных по этому ключу :param key: Ключ шифрования """ with open(self.file_name, 'rb') as f: operational_data = bytearray(f.read()) if key is not None: current_encryptor = Encryptor(key) for pointer in range(int(len(operational_data) / 8)): operational_data[pointer * 8:pointer * 8 + 8] = current_encryptor.encrypt_decrypt_block( operational_data[pointer * 8:pointer * 8 + 8]) self.__parser.load_array(operational_data)
class MainApp: def __init__(self,key_file): self.e = Encryptor(key=key_file) def encrypt_file(self,text,file_name="file.encrypt"): with open(file_name, "wb") as f: text_and_tag = self.e.encrypt(text) f.write(text_and_tag) def decrypt_file(self,file_name): with open(file_name, "rb") as f: x = f.read() print(self.e.decrypt(x).decode()) def encrypt_directory(self): pass def decrypt_directory(self): pass
def handle_tcp(self, sock, remote): fdset = [sock, remote] while True: r, w, e = select.select(fdset, [], []) if sock in r: length = sock.recv(4) if not length: break data = sock.recv(int(self.crypto_table.decrypt(length))) # data = sock.recv(4096) if len(data) <= 0: break print str(len(data)) + '<<<' # print self.crypto_rc4_md5.decrypt(data) crypto_rc4_md5 = Encryptor(self.key,'rc4-md5') remote.send(crypto_rc4_md5.decrypt(data)) if remote in r: data = remote.recv(4096) if len(data) <= 0: break # print data crypto_rc4_md5 = Encryptor(self.key,'rc4-md5') data = crypto_rc4_md5.encrypt(data) length = str(len(data)) if len(length) < 4: length = (4 - len(length)) * '0' + length # print str(len(data)) + '>>>' sock.send(self.crypto_table.encrypt(length) + data)
class Player: MANAGER = ScreenManager() E = Encryptor() SCREENS = None LEADERBOARD = [] L_FILE = 'o.txt' KEYS = {'a': 0, 's': 1, 'k': 2, 'l': 3} KEY = [] ALPHA = [lt for lt in 'abcdefghijklmnopqrswxyz1234567890 '] def __init__(self): Player.SCREENS = { 'start': StartScreen(name='start'), 'game': GameScreen(name='game'), 'win': WinScreen(name='win'), 'lose': LoseScreen(name='lose') } for scr in Player.SCREENS: Player.MANAGER.add_widget(Player.SCREENS[scr]) Player.LEADERBOARD = Player.E.file_decrypt(Player.L_FILE) print(Player.LEADERBOARD) Player.change_screen('start') self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keypress) def _on_keypress(self, keyboard, keycode, text, modifiers): if Player.MANAGER.current_screen.transition_progress % 1 == 0: Player.MANAGER.current_screen._on_keypress(keyboard, keycode, text, modifiers) def _keyboard_closed(self): try: self._keyboard.unbind(on_key_down=self._on_keypress) self._keyboard = None except: pass def change_screen(target, *args, t=None): if t: Player.MANAGER.transition = t else: Player.MANAGER.transition = SlideTransition() try: Player.MANAGER.current = target except: print(' ERROR Screen does not exist')
class hxs2_connection(object): bufsize = 8192 def __init__(self, hxsServer, ctimeout, parentproxy, manager): if not isinstance(hxsServer, ParentProxy): hxsServer = ParentProxy(hxsServer, hxsServer) self.hxsServer = hxsServer self.name = self.hxsServer.name self.timeout = ctimeout self._manager = manager self._last_ping = 0 self._sock = None if parentproxy and not isinstance(parentproxy, ParentProxy): parentproxy = ParentProxy(parentproxy, parentproxy) self.parentproxy = parentproxy _psk = urlparse.parse_qs(self.hxsServer.parse.query).get('PSK', [''])[0] self.method = urlparse.parse_qs(self.hxsServer.parse.query).get('method', [DEFAULT_METHOD])[0].lower() self.hash_algo = urlparse.parse_qs(self.hxsServer.parse.query).get('hash', [DEFAULT_HASH])[0].upper() self._connection_write_lock = RLock() self.__pskcipher = Encryptor(_psk, self.method) self.__cipher = None self._next_stream_id = 1 self._client_sock = {} self._client_status = {} self._stream_status = {} self.getKey() # start read from hxsocks2 connection Thread(target=self.read_from_connection).start() def connect(self, address, timeout=3): logger.debug('hxsocks2 send connect request') payload = b''.join([chr(len(address[0])).encode('latin1'), address[0].encode(), struct.pack('>H', address[1]), b'\x00' * random.randint(64, 255), ]) stream_id = self._next_stream_id self._next_stream_id += 1 if self._next_stream_id > MAX_STREAM_ID: logger.info('MAX_STREAM_ID reached') self._manager.remove(self) self.send_frame(1, 0, stream_id, payload) # wait for server response event = Event() self._client_status[stream_id] = event event.wait(timeout=timeout) if stream_id not in self._stream_status: # server should have some response by now logger.error('not connected from %s, timeout=%.3f' % (self.name, timeout)) self.send_ping() # self._manager.remove(self) raise OSError('not connected') if self._stream_status[stream_id] == OPEN: socketpair_a, socketpair_b = socket.socketpair() socketpair_a.settimeout(5) socketpair_b.settimeout(5) self._client_status[stream_id] = OPEN self._client_sock[stream_id] = socketpair_b # TODO: start forwarding Thread(target=self.read_from_client, args=(stream_id, )).start() return socketpair_a else: raise OSError('connect to %s failed.' % ('%s:%d' % address)) def read_from_client(self, stream_id): logger.debug('start read from client') timeout = 5 if self._client_status[stream_id] & LOCAL_CLOSED else 60 sock = self._client_sock[stream_id] while True: ins, _, _ = select.select([sock], [], [], timeout) if not ins: sock.close() self._client_status[stream_id] = CLOSED self.send_frame(3, 0, stream_id, b'\x00' * random.randint(8, 256)) self._stream_status[stream_id] = CLOSED return try: data = sock.recv(self.bufsize) except OSError: try: sock.close() except OSError: pass self._client_status[stream_id] = CLOSED self.send_frame(3, 0, stream_id, b'\x00' * random.randint(8, 256)) self._stream_status[stream_id] = CLOSED return if not data: # close stream(LOCAL) self.send_frame(1, 1, stream_id, b'\x00' * random.randint(8, 256)) self._stream_status[stream_id] |= LOCAL_CLOSED self._client_status[stream_id] |= REMOTE_CLOSED return if self._stream_status[stream_id] & LOCAL_CLOSED: sock.close() self._client_status[stream_id] = CLOSED self.send_frame(3, 0, stream_id, b'\x00' * random.randint(8, 256)) self._stream_status[stream_id] = CLOSED return payload = struct.pack('>H', len(data)) + data + b'\x00' * random.randint(8, 256) self.send_frame(0, 0, stream_id, payload) def send_frame(self, type_, flags, stream_id, payload): logger.debug('send_frame type: %d, stream_id: %d' % (type_, stream_id)) if self._sock is None: logger.error('connection closed. ' + self.name) return with self._connection_write_lock: header = struct.pack('>BBH', type_, flags, stream_id) data = header + payload ct = self.__cipher.encrypt(data) self._sock.sendall(struct.pack('>H', len(ct)) + ct) def send_ping(self): if self._last_ping == 0: self._last_ping = time.time() self.send_frame(6, 0, 0, b'\x00' * random.randint(64, 256)) def read_from_connection(self): logger.debug('start read from connection') while True: # read frame_len timeout = 2 if self._last_ping else 10 ins, _, _ = select.select([self._sock], [], [], timeout) if not ins: if self._last_ping: logger.info('server no response ' + self.hxsServer.name) break self.send_ping() continue try: frame_len = self._rfile.read(2) frame_len, = struct.unpack('>H', frame_len) except Exception as e: # destroy connection logger.error('read from connection error: %r' % e) break # read frame_data try: frame_data = self._rfile.read(frame_len) frame_data = self.__cipher.decrypt(frame_data) except (OSError, IOError, InvalidTag) as e: # destroy connection logger.error('read frame data error: %r' % e) break # parse chunk_data # +------+-------------------+----------+ # | type | flags | stream_id | payload | # +------+-------------------+----------+ # | 1 | 1 | 2 | Variable | # +------+-------------------+----------+ header, payload = frame_data[:4], frame_data[4:] frame_type, frame_flags, stream_id = struct.unpack('>BBH', header) payload = io.BytesIO(payload) logger.debug('recv frame_type: %s, stream_id: %s' % (frame_type, stream_id)) if frame_type == 0: # DATA # first 2 bytes of payload indicates data_len, the rest would be padding data_len, = struct.unpack('>H', payload.read(2)) data = payload.read(data_len) if len(data) != data_len: # something went wrong, destory connection break # check if stream writable if self._client_status[stream_id] & LOCAL_CLOSED: continue # sent data to stream try: self._client_sock[stream_id].sendall(data) except (OSError, IOError) as e: # TODO: remote closed, reset stream try: self._client_sock[stream_id].close() except (OSError, IOError): pass self._client_status[stream_id] = CLOSED self.send_frame(3, 0, stream_id, b'\x00' * random.randint(8, 256)) self._stream_status[stream_id] = CLOSED elif frame_type == 1: # HEADER if self._next_stream_id == stream_id: # server is not supposed to open a new stream # send connection error? break elif stream_id < self._next_stream_id: if frame_flags == END_STREAM_FLAG: if self._stream_status[stream_id] == OPEN: self._stream_status[stream_id] = REMOTE_CLOSED try: self._client_sock[stream_id].shutdown(socket.SHUT_WR) # KeyError? except KeyError: pass self._client_status[stream_id] = LOCAL_CLOSED elif self._stream_status[stream_id] == LOCAL_CLOSED: self._stream_status[stream_id] = CLOSED self._client_sock[stream_id].close() self._client_sock[stream_id] = CLOSED del self._client_sock[stream_id] else: # something wrong pass else: # confirm a stream is opened if isinstance(self._client_status[stream_id], Event): self._stream_status[stream_id] = OPEN self._client_status[stream_id].set() else: # close stream self._stream_status[stream_id] = CLOSED self.send_frame(3, 0, stream_id, b'\x00' * random.randint(8, 256)) elif frame_type == 3: # RST_STREAM self._stream_status[stream_id] = CLOSED if stream_id in self._client_sock: self._client_status[stream_id] = CLOSED self._client_sock[stream_id].close() del self._client_sock[stream_id] elif frame_type == 6: # PING if frame_flags == 1: resp_time = time.time() - self._last_ping logger.info('server response time: %.3f %s' % (resp_time, self.hxsServer.name)) self._last_ping = 0 else: self.send_frame(6, 1, 0, b'\x00' * random.randint(64, 256)) elif frame_type == 7: # GOAWAY # no more new stream max_stream_id = payload.read(2) self._manager.remove(self) for stream_id, sock in self._client_sock: if stream_id > max_stream_id: # reset stream pass elif frame_type == 8: # WINDOW_UPDATE pass else: break # out of loop, destroy connection logger.info('out of loop ' + self.hxsServer.name) self._manager.remove(self) self._rfile.close() for sid, status in self._client_status.items(): if isinstance(status, Event): self._stream_status[sid] = CLOSED status.set() try: if self._sock: self._sock.close() self._sock = None except (OSError, IOError): pass for stream_id, sock in self._client_sock.items(): try: sock.close() except: pass def getKey(self): logger.debug('hxsocks2 getKey') host, port, usn, psw = (self.hxsServer.hostname, self.hxsServer.port, self.hxsServer.username, self.hxsServer.password) logger.debug('hxsocks2 connect to server') from connection import create_connection self._sock = create_connection((host, port), self.timeout, parentproxy=self.parentproxy, tunnel=True) self._rfile = self._sock.makefile('rb') acipher = ECC(self.__pskcipher._key_len) pubk = acipher.get_pub_key() logger.debug('hxsocks2 send key exchange request') ts = int(time.time()) // 30 ts = struct.pack('>I', ts) padding_len = random.randint(64, 255) data = b''.join([chr(len(pubk)).encode('latin1'), pubk, hmac.new(psw.encode(), ts + pubk + usn.encode(), hashlib.sha256).digest(), b'\x00' * padding_len]) data = chr(20).encode() + struct.pack('>H', len(data)) + data ct = self.__pskcipher.encrypt(data) self._sock.sendall(ct) self.__pskcipher.decrypt(self._rfile.read(self.__pskcipher._iv_len)) if encrypt.is_aead(self.method): ct_len = self.__pskcipher.decrypt(self._rfile.read(18)) ct_len, = struct.unpack('!H', ct_len) ct = self.__pskcipher.decrypt(self._rfile.read(ct_len + 16)) data = ct[2:] else: resp_len = self.__pskcipher.decrypt(self._rfile.read(2)) resp_len, = struct.unpack('>H', resp_len) data = self.__pskcipher.decrypt(self._rfile.read(resp_len)) data = io.BytesIO(data) resp_code = byte2int(data.read(1)) if resp_code == 0: logger.debug('hxsocks read key exchange respond') pklen = byte2int(data.read(1)) scertlen = byte2int(data.read(1)) siglen = byte2int(data.read(1)) server_key = data.read(pklen) auth = data.read(32) server_cert = data.read(scertlen) signature = data.read(siglen) # TODO: ask user if a certificate should be accepted or not. server_id = '%s_%d' % (host, port) if server_id not in known_hosts: logger.info('hxs: server %s new cert %s saved.' % (server_id, hashlib.sha256(server_cert).hexdigest()[:8])) with open('./.hxs_known_hosts/' + server_id + '.cert', 'wb') as f: f.write(server_cert) known_hosts[server_id] = server_cert elif known_hosts[server_id] != server_cert: logger.error('hxs: server %s certificate mismatch! PLEASE CHECK!' % server_id) raise OSError(0, 'hxs: bad certificate') if auth == hmac.new(psw.encode(), pubk + server_key + usn.encode(), hashlib.sha256).digest(): if ECC.verify_with_pub_key(server_cert, auth, signature, self.hash_algo): shared_secret = acipher.get_dh_key(server_key) logger.debug('hxs key exchange success') self.__cipher = AEncryptor(shared_secret, self.method, CTX) return else: logger.error('hxs getKey Error: server auth failed, bad signature') else: logger.error('hxs getKey Error: server auth failed, bad username or password') else: logger.error('hxs getKey Error. bad password or timestamp.') raise OSError(0, 'hxs getKey Error')
class Socks5Server(SocketServer.StreamRequestHandler): #remote_ip_port = ('45.78.14.54',1080) remote_ip_port = ('192.168.100.231',1080) key = 'rp1qaz@WSX' crypto_table = Encryptor(key,'table') # crypto = crypt_aes(key+'000000') def handle_tcp(self, sock, remote): fdset = [sock, remote] while True: r, w, e = select.select(fdset, [], []) if sock in r: data = sock.recv(4096) if len(data) <= 0: break #remote.send(self.crypto.encrypt(data)) #print data crypto_rc4_md5 = Encryptor(self.key,'rc4-md5') data = crypto_rc4_md5.encrypt(data) length = str(len(data)) if len(length) < 4: length = (4 - len(length)) * '0' + length print str(len(data)) + '>>>' remote.send(self.crypto_table.encrypt(length) + data) if remote in r: length = remote.recv(4) if not length: break data = remote.recv(int(self.crypto_table.decrypt(length))) #data = remote.recv(4096) if not data: break # print str(len(data)) + '<<<' + length #print self.crypto_rc4_md5.decrypt(data) crypto_rc4_md5 = Encryptor(self.key,'rc4-md5') sock.send(crypto_rc4_md5.decrypt(data)) # data = remote.recv(4096) # if len(data) <= 0: # break # sock.send(data) def handle(self): try: print 'socks connection from ', self.client_address sock = self.connection # 1. Version test = sock.recv(262) sock.send(b"\x05\x00"); # 2. Request data = sock.recv(4) mode = ord(data[1]) addrtype = ord(data[3]) if addrtype == 1: # IPv4 addr = socket.inet_ntoa(sock.recv(4)) elif addrtype == 3: # Domain name addr = sock.recv(ord(sock.recv(1)[0])) port = struct.unpack('>H', sock.recv(2)) reply = b"\x05\x00\x00\x01" try: if mode == 1: # 1. Tcp connect remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # remote.connect((addr, port[0])) remote.connect(self.remote_ip_port) # ip_port_crypto = self.crypto.encrypt('%s,%d' % (addr, port[0])) ip_port_crypto = rc4('%s,%d' % (addr, port[0]),op='encode',public_key='rp1qaz@WSX') length = str(len(ip_port_crypto)) if len(length) < 4: length = (4 - len(length)) * '0' + length remote.send(length + ip_port_crypto) print 'Tcp connect to', self.remote_ip_port sync_result = remote.recv(1024) if sync_result != '0': reply = b"\x05\x01\x00\x01" else: reply = b"\x05\x07\x00\x01" # Command not supported local = remote.getsockname() reply += socket.inet_aton(local[0]) + struct.pack(">H", local[1]) except socket.error: # Connection refused reply = '\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00' sock.send(reply) # 3. Transfering if reply[1] == '\x00': # Success if mode == 1: # 1. Tcp connect self.handle_tcp(sock, remote) except socket.error,e: print 'socket error: %s' % e
group.add_argument("-e", "--encrypt", help="encrypt file", action="store_true") group.add_argument("-d", "--decrypt", help="decrypt file", action="store_true") parser.add_argument("file", type=str, nargs=1) args = parser.parse_args() if not (args.encrypt or args.decrypt): print("error: you must provide a mode of operation (encrypt or decrypt)") mode = OperationMode.ENCRYPT if args.encrypt else OperationMode.DECRYPT file = open(args.file[0], "rb") if mode == OperationMode.ENCRYPT: public_key, private_key = RSACore.generate_key_pair() Encryptor.write_key_files(args.file[0], public_key, private_key) with open(f"{args.file[0]}.encrypted", "wb") as output_file: output_file.write(b"$RSA") output_file.write( os.path.getsize(args.file[0]).to_bytes(4, byteorder="little")) print("Loading...") plaintext = file.read() print("Encrypting...") encrypted_text = Encryptor.encrypt(public_key, plaintext) output_file.write(b"".join(encrypted_text)) else: orig_file_name = os.path.splitext(args.file[0])[0] print("Loading...")
def __init__(self,key_file): self.e = Encryptor(key=key_file)