Ejemplo n.º 1
0
    def __init__(self, cache):
        """Initialize a LoadBalancer object, which manages workflow execution.

        Args:
            cache (Cache): The Cache object
        """
        server_secret_file = os.path.join(
            walkoff.config.Config.ZMQ_PRIVATE_KEYS_PATH, "server.key_secret")
        server_public, server_secret = auth.load_certificate(
            server_secret_file)
        client_secret_file = os.path.join(
            walkoff.config.Config.ZMQ_PRIVATE_KEYS_PATH, "client.key_secret")
        _, client_secret = auth.load_certificate(client_secret_file)

        self.comm_socket = zmq.Context.instance().socket(zmq.PUB)
        self.comm_socket.curve_secretkey = server_secret
        self.comm_socket.curve_publickey = server_public
        self.comm_socket.curve_server = True
        self.comm_socket.bind(walkoff.config.Config.ZMQ_COMMUNICATION_ADDRESS)
        self.cache = cache
        key = PrivateKey(
            server_secret[:nacl.bindings.crypto_box_SECRETKEYBYTES])
        worker_key = PrivateKey(
            client_secret[:nacl.bindings.crypto_box_SECRETKEYBYTES]).public_key
        self.box = Box(key, worker_key)
Ejemplo n.º 2
0
    def __init__(self, cache, config):
        """Initializes a multiprocessed executor, which will handle the execution of workflows.
        """
        self.threading_is_initialized = False
        self.id = "controller"
        self.pids = None
        self.workflows_executed = 0

        self.ctx = None  # TODO: Test if you can always use the singleton
        self.auth = None

        self.zmq_workflow_comm = None
        self.receiver = None
        self.receiver_thread = None
        self.cache = cache
        self.config = config
        self.execution_db = ExecutionDatabase.instance
        self.results_sender = None

        key = PrivateKey(
            walkoff.config.Config.
            SERVER_PRIVATE_KEY[:nacl.bindings.crypto_box_SECRETKEYBYTES])
        worker_key = PrivateKey(
            walkoff.config.Config.CLIENT_PRIVATE_KEY[:nacl.bindings.
                                                     crypto_box_SECRETKEYBYTES]
        ).public_key
        self.__box = Box(key, worker_key)
Ejemplo n.º 3
0
    def saludo(self):
        """
        genera un mensaje tipo saludo al servidor
        :return: Diccionario con tipo = reto si existe el usuario
        """
        # genera el saludo
        saludo = {'tipo': "saludo", 'nombre': self.nombre}
        paquete = crea_paquete(saludo)
        # envía el mensaje
        self.socket_connection.send(paquete)
        # Recibe la respuesta del servidor
        self.socket_connection.recv(2)
        paquete_recibido = json.loads(self.socket_connection.recv(1024))
        if paquete_recibido["ok"]:
            # Existe el usuario, cargamos las llaves
            dicc = json.load(open("keys_" + self.nombre, "r"))

            self.sk = PrivateKey(base64.b64decode(dicc["sk"]))
            self.pk = PublicKey(base64.b64decode(dicc["pk"]))
            self.sig = nacl.signing.SigningKey(base64.b64decode(dicc["sig"]))
            self.vk = nacl.signing.VerifyKey(base64.b64decode(dicc["vk"]))
            self.medk_pub = PublicKey(base64.b64decode(dicc["medk_pub"]))
            self.medk_priv = PrivateKey(base64.b64decode(dicc["medk_priv"]))
            self.medk = base64.b64decode(dicc["medk"])
            # Se asigna el reto
            self.reto = paquete_recibido["reto"]
        else:
            print "Error. El usuario " + self.nombre + " no existe."
        return paquete_recibido
Ejemplo n.º 4
0
        def _then((entA, entB)):
            self.failUnlessEqual(entA["their_verfkey"], entB["my_verfkey"])
            self.failUnlessEqual(entB["their_verfkey"], entA["my_verfkey"])
            st = fetchone(nB.db, "mailbox_server_transports")
            sj = fetchone(nB.db, "mailbox_server_config")
            s = json.loads(sj["mailbox_config_json"])
            r_privkey = PrivateKey(s["retrieval_privkey"].decode("hex"))
            r_pubkey = r_privkey.public_key.encode().encode("hex")
            t_privkey = PrivateKey(s["transport_privkey"].decode("hex"))
            t_pubkey = t_privkey.public_key.encode().encode("hex")

            transports = nA.agent.get_transports()
            self.failUnlessEqual(len(transports), 1)
            self.failUnless(1 in transports)
            t1 = transports[1]["transport"]
            self.failUnlessEqual(t1["generic"]["type"], "http")
            self.failUnlessEqual(t1["generic"]["url"], nB.baseurl + "mailbox")
            self.failUnlessEqual(t1["generic"]["transport_pubkey"], t_pubkey)
            self.failUnlessIn("TT0", t1["sender"])
            # TODO: when RRID crypto is done, check TT0 better

            r = transports[1]["retrieval"]
            self.failUnlessEqual(r["type"], "http")
            self.failUnlessEqual(r["baseurl"], nB.baseurl + "retrieval/")
            self.failUnlessEqual(r["RT"], st["RT"])
            self.failUnlessEqual(r["retrieval_pubkey"], r_pubkey)
            self.failUnlessEqual(r["retrieval_symkey"], st["symkey"])

            retrievers = nA.agent.mailbox_retrievers
            self.failUnlessEqual(len(retrievers), 1)
            self.failUnless(isinstance(list(retrievers)[0], HTTPRetriever))
            return nA.disownServiceParent()
Ejemplo n.º 5
0
    def __init__(self, db, web, baseurl, desc):
        BaseServer.__init__(self)
        self.db = db
        assert baseurl.endswith("/")
        self.baseurl = baseurl
        self.transport_privkey = PrivateKey(
            desc["transport_privkey"].decode("hex"))
        self.TT_privkey = desc["TT_private_key"].decode("hex")
        self.TT_pubkey = desc["TT_public_key"].decode("hex")
        self.retrieval_privkey = PrivateKey(
            desc["retrieval_privkey"].decode("hex"))

        # this is how we get messages from senders
        web.get_root().putChild("mailbox", ServerResource(self.handle_msgA))

        # add a second resource for agents to retrieve messages
        r = resource.Resource()
        # TODO: retrieval should use a different key than delivery
        self.listres = RetrievalListResource(self.db, self.retrieval_privkey)
        r.putChild("list", self.listres)
        ts = internet.TimerService(self.listres.CLOCK_WINDOW * 3,
                                   self.prune_old_requests)
        ts.setServiceParent(self)
        r.putChild("fetch", RetrievalFetchResource(self.db))
        r.putChild("delete", RetrievalDeleteResource(self.db))
        web.get_root().putChild("retrieval", r)
Ejemplo n.º 6
0
    def reset(self, public_key=None, secret_key=None):
        """
        Remove any existing state and reset as a new node.
        """
        if not public_key:
            public_key, secret_key = zmq.curve_keypair()
            public_key = z85.decode(public_key)
            secret_key = z85.decode(secret_key)
        else:
            secret_key = z85.decode(secret_key)
            public_key = z85.decode(public_key)
            if public_key and HAS_NACL:
                computed_key = str(PrivateKey(secret_key).public_key)
                assert (computed_key == public_key)

        self.node = Node(self.addr, self.port, public_key, secret_key)
        self.hashtabe = {}
        if HAS_NACL:
            self.secret_key = PrivateKey(self.node.secret_key)
        self.nodetree = RoutingZone(self.node.node_id)
        # ensure we exist in own tree
        self.nodetree.add(self.node)
        self.txmap = transaction.TxMap()
        self.defrag = transport.DefragMap()
        self._dump_state()
Ejemplo n.º 7
0
    def setUpClass(cls):
        initialize_test_config()

        server_secret_file = os.path.join(walkoff.config.Config.ZMQ_PRIVATE_KEYS_PATH, "server.key_secret")
        server_public, server_secret = auth.load_certificate(server_secret_file)
        client_secret_file = os.path.join(walkoff.config.Config.ZMQ_PRIVATE_KEYS_PATH, "client.key_secret")
        client_public, client_secret = auth.load_certificate(client_secret_file)
        cls.key = PrivateKey(client_secret[:nacl.bindings.crypto_box_SECRETKEYBYTES])
        cls.server_key = PrivateKey(server_secret[:nacl.bindings.crypto_box_SECRETKEYBYTES]).public_key
        cls.box = Box(cls.key, cls.server_key)
Ejemplo n.º 8
0
 def _gen_equivalent_raw_keys_couple(self):
     rwk1 = bytearray(random(crypto_box_SECRETKEYBYTES))
     rwk2 = bytearray(rwk1)
     # mask rwk1 bits
     rwk1[0] &= 248
     rwk1[31] &= 127
     rwk1[31] |= 64
     # set rwk2 bits
     rwk2[0] |= 7
     rwk2[31] |= 128
     rwk2[31] &= 191
     sk1 = PrivateKey(bytes(rwk1))
     sk2 = PrivateKey(bytes(rwk2))
     return sk1, sk2
Ejemplo n.º 9
0
	def __init__(self):
		"""
		Initialize crypto stuff
		"""
		
		try:
			with open("SecretKey", "rb") as SecKeyFile:
				key = SecKeyFile.read()
		except Exception:
			logging.info("No secret key yet -> Generate new one")
			key = None
		
		if key:
			self.secKey = PrivateKey(key, nacl.encoding.HexEncoder)
			self.pubKey = self.secKey.public_key
		else:
			self.secKey = PrivateKey.generate()
			self.pubKey = self.secKey.public_key
		
		self.secKey_string = self.secKey.encode(nacl.encoding.HexEncoder).upper()
		self.pubKey_string = self.pubKey.encode(nacl.encoding.HexEncoder).upper()
		
		try:
			with open("SecretKey", "wb") as SecKeyFile, open("PublicKey", "wb") as PubKeyFile:
				SecKeyFile.write(self.secKey_string)
				PubKeyFile.write(self.pubKey_string)
		except Exception:
			logging.exception("Could not save secret key!")
			sys.exit(1)
Ejemplo n.º 10
0
def encrypt_text(text, secret_key, rcpt_public_key):
    """Encrypts a text
    """
    secret_key = PrivateKey(secret_key.decode('hex'))
    rcpt_public_key = PublicKey(rcpt_public_key.decode('hex'))
    box = Box(secret_key, rcpt_public_key)
    return box.encrypt(text, nacl.utils.random(Box.NONCE_SIZE))
Ejemplo n.º 11
0
    def key_select(self):
        """Environment Setup"""
        import base64, nacl.utils, zlib
        from lib.keys import PyNaCl_keys
        from nacl.public import PrivateKey, PublicKey, Box
        pynacl = PyNaCl_keys()
        kChoice = raw_input(
            '[G]enerate a Private Key or [I]mport a Private Key?\n')
        if (kChoice == 'g' or kChoice == 'G'):
            privObj, privKey = pynacl.key_gen()
            kSave = raw_input('\nSave the key? [y/N]\n')
            if (kSave == 'y' or kSave == 'Y'):
                print ''
                pynacl.key_save(privKey)
            print '\nYour Public Key is:\n%s' % pynacl.key_exp(privObj)
        elif (kChoice == 'i' or kChoice == 'I'):
            print ''
            from lib.crypto_env import GPG_env
            cType = GPG_env()
            plainKey = pynacl.key_imp()
            plainObj = zlib.decompress(base64.b64decode(plainKey))
            privObj = PrivateKey(plainObj)
            print '\nYour Public Key is:\n%s' % pynacl.key_exp(privObj)

        ## Import partner public key
        partner_plain = raw_input(
            '\nEnter Plaintext Public Key of Chat Partner:\n')
        print ''

        ## Can probably enclose this within PublicKey()
        partner_obj = zlib.decompress(base64.b64decode(partner_plain))
        partner_enc = PublicKey(partner_obj)

        ## Create a box for chat
        return Box(privObj, partner_enc), privObj, partner_enc
Ejemplo n.º 12
0
    def test_put_password_with_invalid_json(self):
        """
        Tests PUT method on password with invalid json
        """

        url = reverse('password')

        update_data_nonce = nacl.utils.random(Box.NONCE_SIZE)
        update_data_nonce_hex = nacl.encoding.HexEncoder.encode(update_data_nonce)

        crypto_box = Box(PrivateKey(self.user_private_key, encoder=nacl.encoding.HexEncoder),
                         PublicKey(self.verifier_public_key, encoder=nacl.encoding.HexEncoder))


        update_data_dec = crypto_box.encrypt('narf'.encode("utf-8"), update_data_nonce)

        update_data = update_data_dec[len(update_data_nonce):]
        update_data_hex = nacl.encoding.HexEncoder.encode(update_data)

        data = {
            'username': self.test_username,
            'recovery_authkey': self.test_recovery_authkey,
            'update_data': update_data_hex.decode(),
            'update_data_nonce': update_data_nonce_hex.decode(),
        }

        self.client.force_authenticate(user=self.test_user_obj)
        response = self.client.put(url, data)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Ejemplo n.º 13
0
def decode_server_secret_key(keyfile):
    keyfile = keyfile or SERVER_SECRET_KEY_FILE
    sk = None
    with open(keyfile) as fh:
        hex = fh.read()
        sk = PrivateKey(from_hex(hex.strip()))
    return sk
Ejemplo n.º 14
0
    def rpc_complete_order(self, sender, pubkey, encrypted):
        try:
            box = Box(
                PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)),
                PublicKey(pubkey))
            order = box.decrypt(encrypted)
            c = Contract(self.db,
                         contract=json.loads(order,
                                             object_pairs_hook=OrderedDict),
                         testnet=self.multiplexer.testnet)

            def handle_result(contract_id):
                if contract_id:
                    self.router.addContact(sender)
                    self.log.info("Received receipt for order %s" %
                                  contract_id)
                    return ["True"]
                else:
                    self.log.error("Received invalid receipt from %s" % sender)
                    return ["False"]

            d = c.accept_receipt(self.multiplexer.ws,
                                 self.multiplexer.blockchain)
            d.addCallback(handle_result)
        except Exception:
            self.log.error("Unable to decrypt order receipt from %s" % sender)
            return ["False"]
Ejemplo n.º 15
0
def decrypt_text(text, secret_key, sender_public_key):
    """Decrypts a text
    """
    secret_key = PrivateKey(secret_key.decode('hex'))
    sender_public_key = PublicKey(sender_public_key.decode('hex'))
    box = Box(secret_key, sender_public_key)
    return box.decrypt(text)
Ejemplo n.º 16
0
 def privkey(self):
     if self._privkey == "":
         self._privkey = self.file_read_hex(self.path_privatekey)
     key = self.decryptSymmetric(self._privkey)
     privkey = PrivateKey(key)
     self._pubkey = privkey.public_key
     return privkey
Ejemplo n.º 17
0
    def decrypt(self, file):
        # read encrypted data from file
        with open(file) as f:
            content = f.read()
        f.close()

        # read 1st public key and 2nd private key from config.json
        with open('config.json') as json_file:
            data = json.load(json_file)
            pub_key1 = data['public_key1']
            priv_key2 = data['private_key2']
        json_file.close()

        # Convert public key, private key, and encrypted data to byte strings
        priv_keyb2 = self.str_to_bytestring(priv_key2)
        pub_keyb1 = self.str_to_bytestring(pub_key1)
        content2 = self.str_to_bytestring(content)

        # decrypt encrypted data and write back to file
        private_key2 = PrivateKey(priv_keyb2)
        public_key1 = PublicKey(pub_keyb1)
        user_box2 = Box(private_key2, public_key1)
        decrypted = user_box2.decrypt(content2).decode("utf-8")

        with open(file, "w") as text_file:
            text_file.write(decrypted)
        text_file.close()
Ejemplo n.º 18
0
    def send_message(self, receiving_node, public_key, message_type, message, subject=None):
        """
        Sends a message to another node. If the node isn't online it
        will be placed in the dht for the node to pick up later.
        """
        pro = Profile().get()
        if len(message) > 1500:
            return
        p = objects.Plaintext_Message()
        p.sender_guid = self.kserver.node.id
        p.signed_pubkey = self.kserver.node.signed_pubkey
        p.encryption_pubkey = PrivateKey(self.signing_key.encode()).public_key.encode()
        p.type = message_type
        p.message = message
        if subject is not None:
            p.subject = subject
        if pro.handle:
            p.handle = pro.handle
        if pro.avatar_hash:
            p.avatar_hash = pro.avatar_hash
        p.timestamp = int(time.time())
        signature = self.signing_key.sign(p.SerializeToString())[:64]
        p.signature = signature

        skephem = PrivateKey.generate()
        pkephem = skephem.public_key.encode(nacl.encoding.RawEncoder)
        box = Box(skephem, PublicKey(public_key, nacl.encoding.HexEncoder))
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        ciphertext = box.encrypt(p.SerializeToString(), nonce)

        def get_response(response):
            if not response[0]:
                self.kserver.set(receiving_node.id, pkephem, ciphertext)
        self.protocol.callMessage(receiving_node, pkephem, ciphertext).addCallback(get_response)
Ejemplo n.º 19
0
def generate_fileserver_info():
    cluster_crypto_box = Box(
        PrivateKey(CLUSTER_PRIVATE_KEY, encoder=nacl.encoding.HexEncoder),
        PublicKey(SERVER_PUBLIC_KEY, encoder=nacl.encoding.HexEncoder))

    nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
    encrypted = cluster_crypto_box.encrypt(
        json.dumps({
            'VERSION': VERSION,
            'HOSTNAME': HOSTNAME,
            'CLUSTER_ID': CLUSTER_ID,
            'FILESERVER_ID': FILESERVER_ID,
            'FILESERVER_PUBLIC_KEY': PUBLIC_KEY,
            'FILESERVER_SESSION_KEY': FILESERVER_SESSION_KEY,
            'SHARDS_PUBLIC': SHARDS_PUBLIC,
            'READ': READ,
            'WRITE': WRITE,
            'DELETE': DELETE,
            'ALLOW_LINK_SHARES': ALLOW_LINK_SHARES,
            'IP_READ_WHITELIST': IP_READ_WHITELIST,
            'IP_WRITE_WHITELIST': IP_WRITE_WHITELIST,
            'IP_READ_BLACKLIST': IP_READ_BLACKLIST,
            'IP_WRITE_BLACKLIST': IP_WRITE_BLACKLIST,
            'HOST_URL': HOST_URL,
        }).encode("utf-8"), nonce)

    return nacl.encoding.HexEncoder.encode(encrypted).decode()
Ejemplo n.º 20
0
 def rpc_order(self, sender, pubkey, encrypted):
     try:
         box = Box(PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)), PublicKey(pubkey))
         order = box.decrypt(encrypted)
         c = Contract(self.db, contract=json.loads(order, object_pairs_hook=OrderedDict),
                      testnet=self.multiplexer.testnet)
         if c.verify(sender.signed_pubkey[64:]):
             self.router.addContact(sender)
             self.log.info("received an order from %s, waiting for payment..." % sender)
             payment_address = c.contract["buyer_order"]["order"]["payment"]["address"]
             chaincode = c.contract["buyer_order"]["order"]["payment"]["chaincode"]
             masterkey_b = c.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"]
             buyer_key = derive_childkey(masterkey_b, chaincode)
             amount = c.contract["buyer_order"]["order"]["payment"]["amount"]
             listing_hash = c.contract["buyer_order"]["order"]["ref_hash"]
             signature = self.signing_key.sign(
                 str(payment_address) + str(amount) + str(listing_hash) + str(buyer_key))[:64]
             c.await_funding(self.multiplexer.ws, self.multiplexer.blockchain, signature, False)
             return [signature]
         else:
             self.log.warning("received invalid order from %s" % sender)
             return ["False"]
     except Exception:
         self.log.error("unable to decrypt order from %s" % sender)
         return ["False"]
Ejemplo n.º 21
0
 def parse_messages(messages):
     if messages is not None:
         for message in messages:
             try:
                 value = objects.Value()
                 value.ParseFromString(message)
                 try:
                     box = Box(PrivateKey(self.signing_key.encode()), PublicKey(value.valueKey))
                     ciphertext = value.serializedData
                     plaintext = box.decrypt(ciphertext)
                     p = objects.Plaintext_Message()
                     p.ParseFromString(plaintext)
                     signature = p.signature
                     p.ClearField("signature")
                     verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:])
                     verify_key.verify(p.SerializeToString(), signature)
                     h = nacl.hash.sha512(p.signed_pubkey)
                     pow_hash = h[64:128]
                     if int(pow_hash[:6], 16) >= 50 or hexlify(p.sender_guid) != h[:40]:
                         raise Exception('Invalid guid')
                     listener.notify(p.sender_guid, p.encryption_pubkey, p.subject,
                                     objects.Plaintext_Message.Type.Name(p.type), p.message)
                 except Exception:
                     pass
                 signature = self.signing_key.sign(value.valueKey)[:64]
                 self.kserver.delete(self.kserver.node.id, value.valueKey, signature)
             except Exception:
                 pass
Ejemplo n.º 22
0
def main():
    if argv[1] == 'public' and argv[2] == 'sample':
        aliceKp = generate_keypair()
        alicePrivateKey = aliceKp['privateKey']
        alicePublicKey = aliceKp['publicKey']
        bobKp = generate_keypair()
        bobPrivateKey = bobKp['privateKey']
        bobPublicKey = bobKp['publicKey']
        message = 'Hello World!'
        cipher, nonce = encrypt(message, alicePrivateKey, bobPublicKey)

        data = {}
        data['aliceKp'] = export_keypair(aliceKp)
        data['bobKp'] = export_keypair(bobKp)
        data['encrypted'] = cipher
        data['decrypted'] = decrypt(cipher, bobPrivateKey, alicePublicKey)
        data['message'] = message
        data['nonce'] = base64url_encode(nonce)

        print(json.dumps(data, indent=2))

    if argv[1] == 'public' and argv[2] == 'decrypt':
        encoder = URLSafeBase64Encoder
        alicePublicKey = PublicKey(fix_base64url_decode(argv[5]), encoder)
        bobPrivateKey = PrivateKey(fix_base64url_decode(argv[4]), encoder)
        cipher = argv[3]

        data = {}
        data['decrypted'] = decrypt(cipher, bobPrivateKey, alicePublicKey)

        print(json.dumps(data, indent=2))
Ejemplo n.º 23
0
 def _checkInitiate(self, clientID, data, host_port):
     cookieNonce, encryptedCookie, nonce = _initiateStruct.unpack_from(data)
     try:
         decryptedCookie = self._secretBox.decrypt(encryptedCookie,
                                                   'c' * 8 + cookieNonce)
     except CryptoError:
         return
     clientShortPubkey = PublicKey(decryptedCookie[:32])
     serverShortKey = PrivateKey(decryptedCookie[32:])
     serverShortClientShort = Box(serverShortKey, clientShortPubkey)
     try:
         decrypted = serverShortClientShort.decrypt(
             data[176:], 'CurveCP-client-I' + nonce)
     except CryptoError:
         return
     clientPubkeyString, vouchNonce, encryptedVouch, serverDomain = _initiateInnerStruct.unpack_from(
         decrypted)
     clientPubkey = PublicKey(clientPubkeyString)
     serverLongClientLong = Box(self.serverKey.key, clientPubkey)
     try:
         vouchKey = serverLongClientLong.decrypt(encryptedVouch,
                                                 'CurveCPV' + vouchNonce)
     except CryptoError:
         return
     if vouchKey != str(clientShortPubkey):
         return
     transport = CurveCPServerTransport(self.reactor, self.serverKey,
                                        self.factory, clientID,
                                        clientPubkey, host_port,
                                        serverShortClientShort,
                                        dnsToName(serverDomain))
     return transport, decrypted[352:]
Ejemplo n.º 24
0
 def generate_recovery_key(prv_key):
     rec_key = _GCE.generate_key()
     pub_key = PrivateKey(prv_key,
                          Base64Encoder).public_key.encode(Base64Encoder)
     bkp_key = _GCE.symmetric_encrypt(rec_key, prv_key)
     rec_key = _GCE.asymmetric_encrypt(pub_key, rec_key)
     return Base64Encoder.encode(bkp_key), Base64Encoder.encode(rec_key)
Ejemplo n.º 25
0
 def asymmetric_decrypt(prv_key, data):
     """
     Perform asymmetric decryption using libsodium sealedbox (Curve25519, XSalsa20-Poly1305)
     """
     prv_key = PrivateKey(prv_key, RawEncoder)
     data = _convert_to_bytes(data)
     return SealedBox(prv_key).decrypt(data)
Ejemplo n.º 26
0
def read_config(section=None, config_path='/tmp/secrets.conf', private_key=''):
    """
    reads credentials section or app with data in specific configuration path using a private key
    data keys prefixed with __ are considered private and will be encrypted.

    @param section str: application or section name.
        e.g: myapp, githubuser, gitlaborg
    @param config_path str: secretconf path defaults to /tmp/secrets.conf
    @param private_key: key of 32 bytes (you should use sha256 or hash32 function on the bytes of your private key)
     """

    data = {}
    if not os.path.exists(config_path):
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        os.mknod(config_path)

    conf = ConfigParser()
    conf.read_file(open(config_path))

    sk = PrivateKey(private_key, nacl.encoding.Base64Encoder())
    pk = sk.public_key
    box = Box(sk, pk)

    for s in conf.sections():
        secdict = {}
        for k, v in conf[s].items():
            if k.startswith("__"):
                v = decrypt(v, box)
            secdict[k] = v
        data[s] = secdict

    return data
Ejemplo n.º 27
0
    def encrypt(self, file):
        with open('config.json') as json_file:
            data = json.load(json_file)
            pub_key2 = data['public_key2']
            priv_key1 = data['private_key1']
        json_file.close()

        # Convert public key and private key to byte strings, then actual PublicKey and PrivateKey objects
        priv_keyb1 = self.str_to_bytestring(priv_key1)
        pub_keyb2 = self.str_to_bytestring(pub_key2)
        private_key1 = PrivateKey(priv_keyb1)
        public_key2 = PublicKey(pub_keyb2)

        # Read in contents of file, encrypt them, then write back
        with open(file) as f:
            content = f.read()
        f.close()
        bytesData = content.encode()

        user_box1 = Box(private_key1, public_key2)
        nonce = nacl.utils.random(Box.NONCE_SIZE)
        encrypted = user_box1.encrypt(bytesData, nonce)

        with open(file, "w") as text_file:
            text_file.write(str(encrypted))
        text_file.close()
Ejemplo n.º 28
0
def make_config(section=None,
                data=None,
                config_path='/tmp/secrets.conf',
                private_key=''):
    """
    stores credentials section or app with data in specific configuration path using a private key
    data keys prefixed with __ are considered private and will be encrypted.

    @param section str: application or section name.
        e.g: myapp, githubuser, gitlaborg
    @param data dict: dict of fields and their values [fields prefixed with __ are private]
        e.g: {'name': 'xmonader', '__password': '******'}

    @param config_path str: secretconf path defaults to /tmp/secrets.conf
    @param private_key: key of 32 bytes (you should use sha256 or hash32 function on the bytes of your private key)
     """
    data = data or {}
    if not os.path.exists(config_path):
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        os.mknod(config_path)
    conf = ConfigParser()
    conf.read_file(open(config_path))
    conf[section] = {}
    sk = PrivateKey(private_key, nacl.encoding.Base64Encoder())

    pk = sk.public_key
    box = Box(sk, pk)

    for k, v in data.items():
        if k.startswith("__"):
            v = encrypt(v, box)
        conf[section][k] = v

    with open(config_path, "w") as cf:
        conf.write(cf)
Ejemplo n.º 29
0
def decrypt_X25519_Chacha20_Poly1305(encrypted_part,
                                     privkey,
                                     sender_pubkey=None):
    #LOG.debug('-----------  Encrypted data: %s', encrypted_part.hex())
    LOG.debug('    my secret key: %s', privkey.hex())
    LOG.debug('Sender public key: %s',
              sender_pubkey.hex() if sender_pubkey else None)

    peer_pubkey = encrypted_part[:32]
    if sender_pubkey and sender_pubkey != peer_pubkey:
        raise ValueError("Invalid Peer's Public Key")

    nonce = encrypted_part[32:44]
    packet_data = encrypted_part[44:]

    LOG.debug('   peer pubkey: %s', peer_pubkey.hex())
    LOG.debug('         nonce: %s', nonce.hex())
    LOG.debug('encrypted data: %s', packet_data.hex())

    # X25519 shared key
    pubkey = bytes(
        PrivateKey(privkey).public_key)  # slightly inefficient, but working
    shared_key, _ = crypto_kx_client_session_keys(pubkey, privkey, peer_pubkey)
    LOG.debug('shared key: %s', shared_key.hex())

    # Chacha20_Poly1305
    return crypto_aead_chacha20poly1305_ietf_decrypt(packet_data, None, nonce,
                                                     shared_key)  # no add
Ejemplo n.º 30
0
 def rpc_message(self, sender, pubkey, encrypted):
     try:
         box = Box(
             PrivateKey(self.signing_key.encode(nacl.encoding.RawEncoder)),
             PublicKey(pubkey))
         plaintext = box.decrypt(encrypted)
         p = Plaintext_Message()
         p.ParseFromString(plaintext)
         signature = p.signature
         p.ClearField("signature")
         verify_key = nacl.signing.VerifyKey(p.signed_pubkey[64:])
         verify_key.verify(p.SerializeToString(), signature)
         h = nacl.hash.sha512(p.signed_pubkey)
         pow_hash = h[64:128]
         if int(pow_hash[:6], 16) >= 50 or hexlify(
                 p.sender_guid) != h[:40] or p.sender_guid != sender.id:
             raise Exception('Invalid guid')
         self.log.info("Received a message from %s" % sender)
         self.router.addContact(sender)
         for listener in self.listeners:
             try:
                 verifyObject(MessageListener, listener)
                 listener.notify(p, signature)
             except DoesNotImplement:
                 pass
         return ["True"]
     except Exception:
         self.log.error("Received invalid message from %s" % sender)
         return ["False"]