def __init__(self, host, port, token): asyncore.dispatcher.__init__(self) self.buffer_send_raw += token magic = bytearray(os.urandom(MAGIC_LEN)) self.buffer_send_raw += magic self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect((host, port)) self.cipher = AESCipher()
def __init__(self, loop: asyncio.AbstractEventLoop, key: str, public_key_addr: str, remote_addr, listen_addr) -> None: self.loop = loop self.remote_addr = remote_addr self.listen_addr = listen_addr self.aes_key = AESCipher.generate_key() self.aes = AESCipher(self.aes_key) self.share_aes_key(key, public_key_addr)
def new_account(self, user, pwd, custom_file=None): self.cipher = AESCipher(user, pwd) self.content = '{"username":"******", "accounts":{}}' if custom_file: self.filename = custom_file else: self.filename = "account_" + user encrypted = self.cipher.encrypt(self.content) with open(self.filename, 'wb') as f: f.write(encrypted)
class User: def __init__(self): self.user = None self.filename = None self.cipher = None self.content = None def get_cipher(self): return self.cipher def get_username(self): return self.user def get_filename(self): return self.filename def update_content(self, new_content): self.content = new_content def new_account(self, user, pwd, custom_file=None): self.cipher = AESCipher(user, pwd) self.content = '{"username":"******", "accounts":{}}' if custom_file: self.filename = custom_file else: self.filename = "account_" + user encrypted = self.cipher.encrypt(self.content) with open(self.filename, 'wb') as f: f.write(encrypted) def existing_account(self, user, pwd, custom_file=None): self.user = user self.cipher = AESCipher(user, pwd) if custom_file: self.filename = custom_file else: self.filename = "account_" + user with open(self.filename, 'rb') as f: data = f.read() try: self.content = json.loads(self.cipher.decrypt(data)) return True except json.decoder.JSONDecodeError: print("Decryption failed.") return False
class RemoteConnection(asyncore.dispatcher): buffer_send_raw = b'' buffer_send = b'' buffer_recv_raw = b'' buffer_recv = b'' local = None cipher = None def __init__(self, host, port, token): asyncore.dispatcher.__init__(self) self.buffer_send_raw += token magic = bytearray(os.urandom(MAGIC_LEN)) self.buffer_send_raw += magic self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect((host, port)) self.cipher = AESCipher() def handle_connect(self): pass def handle_close(self): LOGGER.info('%s remote close', id(self)) self.local.handle_close() self.close() def handle_read(self): data = self.recv(BUF_SIZE) #LOGGER.debug('%s remote recv: %s', id(self), data) self.buffer_recv += data ddata, dlen = self.cipher.decrypt_all(self.buffer_recv) self.buffer_recv_raw += ddata self.buffer_recv = self.buffer_recv[dlen:] if len(self.buffer_recv_raw) > 0: self.local.buffer_send += self.buffer_recv_raw self.buffer_recv_raw = b'' def writable(self): if len(self.buffer_send_raw) > 0: self.buffer_send += self.cipher.encrypt_all(self.buffer_send_raw) self.buffer_send_raw = b'' return (len(self.buffer_send) > 0) def handle_write(self): sent = self.send(self.buffer_send) #LOGGER.debug('%s remote send %s', id(self), self.buffer[:sent]) self.buffer_send = self.buffer_send[sent:]
def existing_account(self, user, pwd, custom_file=None): self.user = user self.cipher = AESCipher(user, pwd) if custom_file: self.filename = custom_file else: self.filename = "account_" + user with open(self.filename, 'rb') as f: data = f.read() try: self.content = json.loads(self.cipher.decrypt(data)) return True except json.decoder.JSONDecodeError: print("Decryption failed.") return False
def main(): global PATH, PASSWORD, CHUNK_SIZE, FILE_SIZE, CIPHER parser = argparse.ArgumentParser(description=DESC) parser.add_argument("file_path", type=str, help="The encrypted file to be played.") parser.add_argument("password", type=str, help="Password to decrypt the file.") parser.add_argument("-c", "--chunk_size", dest="chunk_size", type=int, default=8192, help="The size of encryption chunks.") parser.add_argument("-p", "--port", dest="port", type=int, default=8080, help="The port where the internal server will run.") args = parser.parse_args() PATH = args.file_path PASSWORD = args.password CHUNK_SIZE = args.chunk_size CIPHER = AESCipher(PASSWORD, CHUNK_SIZE) FILE_SIZE = get_plain_size(PATH, CIPHER) logging.basicConfig(level=logging.INFO) HOST = "127.0.0.1" http_server = HTTPServer(WSGIContainer(app)) t1 = threading.Thread( target=start_tornado, args=[asyncio.get_event_loop(), http_server, args.port]) t1.daemon = True t1.start() pid = subprocess.Popen( ["vlc", "http://" + HOST + ":" + str(args.port) + "/video"]) pid.wait() http_server.stop() IOLoop.instance().stop() sys.exit(0)
import socket, os, time, getpass, hashlib, sys from cipher import AESCipher def SEND(message): server.send(cipher.encrypt(message)) def RECV(): return cipher.decrypt(server.recv(2048)) if len(sys.argv) < 4: sys.exit() cipher = AESCipher("") #####some random string that is same as server##### server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) IP_address = "127.0.0.1" #####change to server ip##### Port = 5321 server.connect((IP_address, Port)) SEND(hashlib.sha256(RECV()).hexdigest()) if RECV() != "AUTHORISED": server.close() sys.exit() SEND("OUTPUT") os.system("title Output " + sys.argv[2]) SEND(sys.argv[1] + " " + sys.argv[2]) if RECV() != "ACCEPTED": server.close()
def RECV(): return cipher.decrypt(server.recv(2048)) def serverThread(): while True: command = raw_input() SEND(key.encrypt("<" + sys.argv[1] + "> " + command)) if len(sys.argv) < 4: sys.exit() cipher = AESCipher("") #####some random string that is same as server##### server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) IP_address = "127.0.0.1" #####change to server ip##### Port = 5321 server.connect((IP_address, Port)) SEND(hashlib.sha256(RECV()).hexdigest()) if RECV() != "AUTHORISED": server.close() sys.exit() SEND("INPUT") os.system("title Input " + sys.argv[2]) SEND(sys.argv[1] + " " + sys.argv[2]) if RECV() != "ACCEPTED": server.close()
try: clients[i].activeConnections.remove(self.name) except: pass for i in self.pendingInbounds: clients[i].pendingOutbounds.remove(self.name) for i in self.pendingOutbounds: clients[i].pendingInbounds.remove(self.name) del clients[self.name] print "<" + self.addr[0] + "> " + self.name + " logged off" cipher = AESCipher("") #####some random string##### server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) IP_address = "0.0.0.0" Port = 5321 server.bind((IP_address, Port)) server.listen(8) clients = {} file = open("names.txt") names = file.read().splitlines() file.close() file = open("passwords.txt") passwords = file.read().splitlines() file.close()
def __init__(self, sock): super().__init__(sock) self.cipher = AESCipher()
class LocalConnection(asyncore.dispatcher): buffer_recv = b'' buffer_recv_raw = b'' buffer_send = b'' buffer_send_raw = b'' server = None remote = None stage = STAGE_INIT cipher = None token = None def __init__(self, sock): super().__init__(sock) self.cipher = AESCipher() def handle_read(self): data = self.recv(BUF_SIZE) if not data: return if self.token: self.server.add_traffic(self.token, len(data) / (1024.0 * 1024.0)) self.buffer_recv += data ddata, dlen = self.cipher.decrypt_all(self.buffer_recv) self.buffer_recv_raw += ddata self.buffer_recv = self.buffer_recv[dlen:] #LOGGER.debug('%s local recv %s', id(self), data) while True: if self.stage == STAGE_INIT: if len(self.buffer_recv_raw) < TOKEN_LEN + MAGIC_LEN: return token = self.buffer_recv_raw[0:TOKEN_LEN] self.token = token magic = self.buffer_recv_raw[TOKEN_LEN:TOKEN_LEN + MAGIC_LEN] LOGGER.info("%s accept token: %s, magic: %s", id(self), token.hex(), magic.hex()) # auth if not self.server.query_token(token): LOGGER.warning('%s token not exist!', id(self)) self.handle_close() return if not self.server.query_magic(magic): LOGGER.warning('%s duplicated magic!', id(self)) self.handle_close() return self.buffer_recv_raw = self.buffer_recv_raw[TOKEN_LEN + MAGIC_LEN:] self.stage = STAGE_HANDSHAKE continue elif self.stage == STAGE_HANDSHAKE: if len(self.buffer_recv_raw) < 1: return atyp = self.buffer_recv_raw[0] addr = "" port = 0 if atyp == 1: if len(self.buffer_recv_raw) < 7: return addr = str(self.buffer_recv_raw[1]) + '.' + str(self.buffer_recv_raw[2]) + \ '.' + str(self.buffer_recv_raw[3]) + '.' + str(self.buffer_recv_raw[4]) port = self.buffer_recv_raw[ 5] * 256 + self.buffer_recv_raw[6] self.buffer_recv_raw = self.buffer_recv_raw[7:] elif atyp == 3: if len(self.buffer_recv_raw) < 2: return alen = self.buffer_recv_raw[1] if len(self.buffer_recv_raw) < 2 + alen + 2: return addr = self.buffer_recv_raw[2:2 + alen].decode('utf-8') port = self.buffer_recv_raw[ 2 + alen] * 256 + self.buffer_recv_raw[2 + alen + 1] self.buffer_recv_raw = self.buffer_recv_raw[2 + alen + 2:] LOGGER.info('%s local handshake: %s:%d', id(self), addr, port) try: self.remote = RemoteConnection(addr, port) except Exception: LOGGER.error('%s cannot connect to %s:%d', id(self), addr, port) return self.remote.local = self self.remote.buffer += self.buffer_recv_raw self.buffer_recv_raw = b'' self.stage = STAGE_STREAM continue elif self.stage == STAGE_STREAM: self.remote.buffer += self.buffer_recv_raw self.buffer_recv_raw = b'' return def writable(self): if len(self.buffer_send_raw) > 0: self.buffer_send += self.cipher.encrypt_all(self.buffer_send_raw) self.buffer_send_raw = b'' return (len(self.buffer_send) > 0 and self.stage == STAGE_STREAM) def handle_write(self): sent = self.send(self.buffer_send) #LOGGER.debug('%s local send %s', id(self), self.buffer[:sent]) self.buffer_send = self.buffer_send[sent:] if self.token: self.server.add_traffic(self.token, sent / (1024.0 * 1024.0)) def handle_close(self): LOGGER.info('%s local close', id(self)) if self in self.server.conn_list: self.server.conn_list.remove(self) self.close()
def acknowledge_token(request, token): """Acknowledge a host or service alert using an encrypted token.""" time_now = time.time() cipher = AESCipher('ABCDEF0123456789', iv='iv1234567890ABCD') host_command_line = "COMMAND [{timestamp}] {command};" \ "{hostname};" \ "{sticky};" \ "{notify};" \ "{persistent};" \ "{author};" \ "Ack by email, working on it." svc_command_line = "COMMAND [{timestamp}] {command};" \ "{hostname};" \ "{service_description};" \ "{sticky};" \ "{notify};" \ "{persistent};" \ "{author};" \ "Ack by email, working on it." # Try to decode the encrypted token to a python object (dict) try: token = str(token) json_token = cipher.decrypt(urlsafe_b64decode(token)) ack_data = json.loads(json_token) except: logger.exception("Unable to decrypt the provided token !") logger.debug("Token received: %s", token) return HttpResponse('Token is not valid !\n', status=400) # Check token validity in time if time_now > ack_data['expire_time']: if 'service_description' in ack_data: logger.warning( "Token validity for service alert \"%s / %s\" has expired !", ack_data['hostname'], ack_data['service_description']) else: logger.warning( "Token validity for host alert \"%s\" has expired !", ack_data['hostname']) return render(request, 'nagios/ack_email_expired.html', ack_data) # Send the ack command to Nagios if 'service_description' in ack_data: command_line = svc_command_line.format(timestamp=time_now, **ack_data) else: command_line = host_command_line.format(timestamp=time_now, **ack_data) # Establish a connection to satellites and send the command to ack try: satellites = Satellite.live_connect() for conn in satellites.connections: site = conn[0] satellites.command(command_line, sitename=site) except Satellite.SatelliteConnectError as e: logger.exception('Error connecting on satellites !') return HttpResponse('Unable to connect to Nagios.\n' 'Error: {}\n'.format(e), status=400) logger.info("Processed ack by email: %s", command_line) return render(request, 'nagios/ack_email_passed.html', ack_data)
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from werkzeug.contrib.cache import SimpleCache from cipher import AESCipher # TODO cache should be easily configurable cache = SimpleCache() app = Flask(__name__) app.config.from_object('config') cipher = AESCipher(app.config['SECRET_KEY']) if 'DATABASE' in os.environ: # For tests... app.config['DATABASE'] = os.environ['DATABASE'] def rst2html(path): try: from docutils.core import publish_parts f = open(path, 'r') readme = publish_parts( f.read(), writer_name='html', )['html_body'] f.close() except ImportError: # pragma: no cover readme = False
#!/usr/bin/env python from cipher import AESCipher import time import os ciphering_info = {'key':'1111111111111111'} aes = AESCipher(ciphering_info) src_filename = 'test0' des_filename = 'filename' tempfile = 'test.txt' print "encrypt_file begin" items = [] for i in range(1): start_time = time.time() aes_length = aes.encrypt_file(des_filename,src_filename) # print "hello" end_time = time.time() duration = end_time - start_time print duration items.append(duration) print 'item',items times = sum(items) / len(items) print "the time is = %f,the speed is = %f MB/s" % (times,os.path.getsize(des_filename)/1024/1024/times) print aes_length print "decrypt_file begin" detm = [] for i in range(1): start1_time = time.time() dec_length = aes.decrypt_file(tempfile,des_filename) #print "test decry"
async def handle(self, src_conn, src_addr): src_ip, _ = src_addr data = await self.loop.sock_recv(src_conn, self.buffer_size) # Handshake by hash hit = False if len(data) >= 4: h = data[0: 4] if h in self.hash.hash_tuple(self.password): # print(" > Detect hash hit") data = self.rsa.decode(data[4:]) if len(data) < 16: src_conn.close() return password = data[16:] if password != self.password: # print(" > Wrong password, close connection") src_conn.close() return print(" > Correct Password and exchange AES key with {}".format(src_ip)) hit = True R = data[:16] self.ip_aes_pool[src_ip] = AESCipher(R) ok_data = b"OK" ok_data = self.ip_aes_pool[src_ip].encode(ok_data) await self.loop.sock_sendall(src_conn, ok_data) if hit: print(" > Authentication OK") else: if src_ip not in self.ip_aes_pool: src_conn.close() return else: # 1. Method negotiation # noinspection PyBroadException try: aes = self.ip_aes_pool[src_ip] data = self.unpack_decode(data, aes) assert data and data[0] == 0x05 except Exception: src_conn.close() return # 2. Send response, select a method. Choose 0x00 for no verification response_data = self.pack_encode(bytearray((0x05, 0x00)), aes) await self.loop.sock_sendall(src_conn, response_data) # 3. Request data = await self.loop.sock_recv(src_conn, self.buffer_size) data = self.unpack_decode(data, aes) if len(data) < 7: src_conn.close() return if data[1] != 0x01: # Ensure connect src_conn.close() return dst_family = None dst_socket = None dst_addr = None dst_port = data[-2:] dst_port = int(dst_port.hex(), 16) if data[3] == 0x01: # IPv4 address dst_ip = socket.inet_ntop(socket.AF_INET, data[4:4 + 4]) dst_addr = (dst_ip, dst_port) dst_family = socket.AF_INET elif data[3] == 0x03: # URL dst_ip = data[5:-2].decode() elif data[3] == 0x04: # IPv6 address dst_ip = socket.inet_ntop(socket.AF_INET6, data[4:4 + 16]) dst_addr = (dst_ip, dst_port, 0, 0) dst_family = socket.AF_INET6 else: src_conn.close() return if dst_family is not None: # noinspection PyBroadException try: dst_socket = socket.socket(family=dst_family, type=socket.SOCK_STREAM) dst_socket.setblocking(False) await self.loop.sock_connect(dst_socket, dst_addr) except Exception: if dst_socket is not None: dst_socket.close() dst_socket = None else: for info in await self.loop.getaddrinfo(dst_ip, dst_port): dst_family, socket_type, proto, _, dst_addr = info # noinspection PyBroadException try: dst_socket = socket.socket(family=dst_family, type=socket_type, proto=proto) dst_socket.setblocking(False) await self.loop.sock_connect(dst_socket, dst_addr) break except Exception: if dst_socket is not None: dst_socket.close() dst_socket = None if dst_family is None: return # 4. End negotiation end_data = self.pack_encode( bytearray((0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)), aes) await self.loop.sock_sendall(src_conn, end_data) src_to_dst_task = self.loop.create_task(self.recv_and_send(src_conn, dst_socket, True, False, aes.decode)) dst_to_src_task = self.loop.create_task(self.recv_and_send(dst_socket, src_conn, False, True, aes.encode)) def clean_up(_): dst_socket.close() src_conn.close() asyncio.gather(src_to_dst_task, dst_to_src_task, loop=self.loop, return_exceptions=True).\ add_done_callback(clean_up)
class WaziLocal: buffer_size = 1024 def __init__(self, loop: asyncio.AbstractEventLoop, key: str, public_key_addr: str, remote_addr, listen_addr) -> None: self.loop = loop self.remote_addr = remote_addr self.listen_addr = listen_addr self.aes_key = AESCipher.generate_key() self.aes = AESCipher(self.aes_key) self.share_aes_key(key, public_key_addr) def share_aes_key(self, key: str, public_key_addr: str): # noinspection PyBroadException try: # Prepare authentication rsa = RSACipher(public_key_addr) key = key.encode() hash_value = Hash().hash_tuple(key)[1] assert len(hash_value) == 4 # Connect to remote and share AES key remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote.connect(self.remote_addr) remote.send(hash_value + rsa.encode(self.aes_key + key)) # Verify response response = self.aes.decode(remote.recv(self.buffer_size)) if response == b"OK": print("Successful authentication") else: raise ConnectionError("Response not correct") remote.close() except Exception as exception: print("Failed to do authentication: {}".format(exception)) exit(-1) def run(self) -> None: self.loop.create_task(self.listen()) try: self.loop.run_forever() except KeyboardInterrupt: print("Local server shuts down") async def listen(self) -> None: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind(self.listen_addr) listener.listen(socket.SOMAXCONN) listener.setblocking(False) print("Local server starts successfully") # print("Listening for new connections ...") while True: client, addr = await self.loop.sock_accept(listener) self.loop.create_task(self.handle(client)) async def handle(self, client: socket.socket) -> None: remote = await self.new_remote() # Communicators client2remote = self.loop.create_task( self.communicator(client, remote, False, True, self.aes.encode)) remote2client = self.loop.create_task( self.communicator(remote, client, True, False, self.aes.decode)) # Clean up def clean_up(_) -> None: client.close() remote.close() # print(" > Connections close: {}".format(addr)) asyncio.gather(client2remote, remote2client, loop=self.loop, return_exceptions=True).add_done_callback(clean_up) async def new_remote(self) -> socket.socket: remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remote.setblocking(False) await self.loop.sock_connect(remote, self.remote_addr) return remote async def communicator(self, src: socket.socket, dst: socket.socket, unpack_src_length: bool, pack_dst_length: bool, cipher_func) -> None: while True: data = b"" if unpack_src_length: running = True while len(data) < 32 and running: packet = await self.loop.sock_recv(src, 32 - len(data)) if not packet: running = False break data = data + packet if not running: break assert len(data) == 32 length = int.from_bytes(cipher_func(data), "little") data = b"" while len(data) < length and running: packet = await self.loop.sock_recv( src, min(self.buffer_size, length - len(data))) if not packet: running = False break data = data + packet if not running: break else: data = await self.loop.sock_recv(src, self.buffer_size) if not data: break data = cipher_func(data) if pack_dst_length: encoded_length = cipher_func( int(len(data)).to_bytes(16, "little")) # `cipher_func` must encode 16 bytes into 32 bytes assert len(encoded_length) == 32 data = encoded_length + data await self.loop.sock_sendall(dst, data)