def key_for_hostname(hostname): # fireball mode is an implementation of ansible firing up zeromq via SSH # to use no persistent daemons or key management if not KEYCZAR_AVAILABLE: raise errors.AnsibleError( "python-keyczar must be installed to use fireball mode") key_path = os.path.expanduser("~/.fireball.keys") if not os.path.exists(key_path): os.makedirs(key_path) key_path = os.path.expanduser("~/.fireball.keys/%s" % hostname) # use new AES keys every 2 hours, which means fireball must not allow running for longer either if not os.path.exists(key_path) or ( time.time() - os.path.getmtime(key_path) > 60 * 60 * 2): key = AesKey.Generate() fh = open(key_path, "w") fh.write(str(key)) fh.close() return key else: fh = open(key_path) key = AesKey.Read(fh.read()) fh.close() return key
def key_for_hostname(hostname): # fireball mode is an implementation of ansible firing up zeromq via SSH # to use no persistent daemons or key management if not KEYCZAR_AVAILABLE: raise AnsibleError("python-keyczar must be installed on the control machine to use accelerated modes") key_path = os.path.expanduser(C.ACCELERATE_KEYS_DIR) if not os.path.exists(key_path): os.makedirs(key_path, mode=0o700) os.chmod(key_path, int(C.ACCELERATE_KEYS_DIR_PERMS, 8)) elif not os.path.isdir(key_path): raise AnsibleError('ACCELERATE_KEYS_DIR is not a directory.') if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_DIR_PERMS, 8): raise AnsibleError('Incorrect permissions on the private key directory. Use `chmod 0%o %s` to correct this issue, and make sure any of the keys files contained within that directory are set to 0%o' % (int(C.ACCELERATE_KEYS_DIR_PERMS, 8), C.ACCELERATE_KEYS_DIR, int(C.ACCELERATE_KEYS_FILE_PERMS, 8))) key_path = os.path.join(key_path, hostname) # use new AES keys every 2 hours, which means fireball must not allow running for longer either if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60*60*2): key = AesKey.Generate(size=256) fd = os.open(key_path, os.O_WRONLY | os.O_CREAT, int(C.ACCELERATE_KEYS_FILE_PERMS, 8)) fh = os.fdopen(fd, 'w') fh.write(str(key)) fh.close() return key else: if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_FILE_PERMS, 8): raise AnsibleError('Incorrect permissions on the key file for this host. Use `chmod 0%o %s` to correct this issue.' % (int(C.ACCELERATE_KEYS_FILE_PERMS, 8), key_path)) fh = open(key_path) key = AesKey.Read(fh.read()) fh.close() return key
def __init__(self, config): super(SessionAction, self).__init__(config) #self._username = self.config['username'] #self._password = self.config['password'] #self._enable_username = self.config['enable_username'] #self._enable_password = self.config['enable_password'] # Get Encryption Setup and Key is_encryption_enabled = cfg.CONF.keyvalue.enable_encryption if is_encryption_enabled: crypto_key_path = cfg.CONF.keyvalue.encryption_key_path with open(crypto_key_path) as key_file: crypto_key = AesKey.Read(key_file.read()) # Retrieve and decrypt values client = Client(base_url='http://localhost') key = client.keys.get_by_name('campus_ztp.username') if key: self._username = key.value key = client.keys.get_by_name('campus_ztp.password') if key: self._password = symmetric_decrypt(crypto_key, key.value) key = client.keys.get_by_name('campus_ztp.enable_username') if key: self._enable_username = key.value key = client.keys.get_by_name('campus_ztp.enable_password') if key: self._enable_password = symmetric_decrypt(crypto_key, key.value)
def key_for_hostname(hostname): # fireball mode is an implementation of ansible firing up zeromq via SSH # to use no persistent daemons or key management if not KEYCZAR_AVAILABLE: raise AnsibleError("python-keyczar must be installed on the control machine to use accelerated modes") key_path = os.path.expanduser(C.ACCELERATE_KEYS_DIR) if not os.path.exists(key_path): # avoid race with multiple forks trying to create paths on host # but limit when locking is needed to creation only with(_LOCK): if not os.path.exists(key_path): # use a temp directory and rename to ensure the directory # searched for only appears after permissions applied. tmp_dir = tempfile.mkdtemp(dir=os.path.dirname(key_path)) os.chmod(tmp_dir, int(C.ACCELERATE_KEYS_DIR_PERMS, 8)) os.rename(tmp_dir, key_path) elif not os.path.isdir(key_path): raise AnsibleError('ACCELERATE_KEYS_DIR is not a directory.') if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_DIR_PERMS, 8): raise AnsibleError('Incorrect permissions on the private key directory. Use `chmod 0%o %s` to correct this issue, and make sure any of the keys files ' 'contained within that directory are set to 0%o' % (int(C.ACCELERATE_KEYS_DIR_PERMS, 8), C.ACCELERATE_KEYS_DIR, int(C.ACCELERATE_KEYS_FILE_PERMS, 8))) key_path = os.path.join(key_path, hostname) # use new AES keys every 2 hours, which means fireball must not allow running for longer either if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60 * 60 * 2): # avoid race with multiple forks trying to create key # but limit when locking is needed to creation only with(_LOCK): if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60 * 60 * 2): key = AesKey.Generate() # use temp file to ensure file only appears once it has # desired contents and permissions with tempfile.NamedTemporaryFile(mode='w', dir=os.path.dirname(key_path), delete=False) as fh: tmp_key_path = fh.name fh.write(str(key)) os.chmod(tmp_key_path, int(C.ACCELERATE_KEYS_FILE_PERMS, 8)) os.rename(tmp_key_path, key_path) return key if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_FILE_PERMS, 8): raise AnsibleError('Incorrect permissions on the key file for this host. Use `chmod 0%o %s` to ' 'correct this issue.' % (int(C.ACCELERATE_KEYS_FILE_PERMS, 8), key_path)) fh = open(key_path) key = AesKey.Read(fh.read()) fh.close() return key
def __init__(self, server_address, RequestHandlerClass, module, password, timeout, use_ipv6=False): self.module = module self.key_list.append(AesKey.Read(password)) self.allow_reuse_address = True self.timeout = timeout if use_ipv6: self.address_family = socket.AF_INET6 if self.module.params.get('multi_key', False): vv("starting thread to handle local connections for multiple keys") self.local_thread = LocalSocketThread(kwargs=dict(server=self)) self.local_thread.start() SocketServer.ThreadingTCPServer.__init__(self, server_address, RequestHandlerClass)
def __init__(self): # check if the key.kz file exists try: with open("keys.kz", "r") as fd: data = fd.read() except IOError: print "ERROR: no key file found, generating the file" self.key = AesKey.Generate() with open("keys.kz", "w+") as fd: fd.write(str(self.key)) else: self.key = AesKey.Read(data) if DEBUG: print self.key.key_string print self.key.hmac_key # If keyczar changes their header format this would need to change: # 5 bytes for the header and 16 for the IV self.header_len = 5 + 16 self.block_len = self.key.block_size self.hmac_len = self.key.hmac_key.size / 8 self.overhead = self.header_len + self.hmac_len
def serve(module, password, port, minutes): log("serving") context = zmq.Context() socket = context.socket(zmq.REP) addr = "tcp://*:%s" % port log("zmq serving on %s" % addr) socket.bind(addr) # password isn't so much a password but a serialized AesKey object that we xferred over SSH # password as a variable in ansible is never logged though, so it serves well key = AesKey.Read(password) while True: data = socket.recv() try: data = key.Decrypt(data) except: continue data = json.loads(data) mode = data['mode'] response = {} if mode == 'command': response = command(module, data) elif mode == 'put': response = put(data) elif mode == 'fetch': response = fetch(data) data2 = json.dumps(response) data2 = key.Encrypt(data2) socket.send(data2)
def run(self): try: if os.path.exists(SOCKET_FILE): os.remove(SOCKET_FILE) else: dir = os.path.dirname(SOCKET_FILE) if os.path.exists(dir): if not os.path.isdir(dir): log("The socket file path (%s) exists, but is not a directory. No local connections will be available" % dir) return else: # make sure the directory is accessible only to this # user, as socket files derive their permissions from # the directory that contains them os.chmod(dir, int('0700', 8)) elif not os.path.exists(dir): os.makedirs(dir, int('O700', 8)) except OSError: pass self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.s.bind(SOCKET_FILE) self.s.listen(5) while not self.terminated: try: conn, addr = self.s.accept() vv("received local connection") data = "" while "\n" not in data: data += conn.recv(2048) try: try: new_key = AesKey.Read(data.strip()) found = False for key in self.server.key_list: try: new_key.Decrypt(key.Encrypt("foo")) found = True break except: pass if not found: vv("adding new key to the key list") self.server.key_list.append(new_key) conn.sendall("OK\n") else: vv("key already exists in the key list, ignoring") conn.sendall("EXISTS\n") # update the last event time so the server doesn't # shutdown sooner than expected for new clients try: self.server.last_event_lock.acquire() self.server.last_event = datetime.datetime.now() finally: self.server.last_event_lock.release() except Exception: e = get_exception() vv("key loaded locally was invalid, ignoring (%s)" % e) conn.sendall("BADKEY\n") finally: try: conn.close() except: pass except: pass
#!/usr/bin/python import zmq import json from keyczar.keys import AesKey context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:5099") file = open('shared_secret.junk') key = AesKey.Read(file.read()) for i in range(10): data = dict(operation="put", param1="alpha", param2="beta") data = json.dumps(data) data = key.Encrypt(data) socket.send(data) msg_in = socket.recv() data = key.Decrypt(data) print json.loads(data)
def _read_crypto_key(key_path): with open(key_path) as key_file: key = AesKey.Read(key_file.read()) return key