def __init__(self, hash_name=None, key=None):

        if isinstance(key, (str, unicode)):
            self.key = rsa.Key(key)

        #This should only ever be the local Switch.
        if hash_name is None:
            if key is None:
                #Fashion a new Switch from the Platonic Realm
                self.key = rsa.Key(2048)
            self._hash = self._hash_from_key(self.key)
        else:
            self._validate_hash_name(hash_name)
            self._hash = self._hash_from_string(hash_name)
Exemple #2
0
    def start(self):
        """ start
        """

        while True:
            try:
                action = random.randint(1, 5)
                if action == 1:
                    print("Relaying messages to peers.")
                    self._relay_all_messages()
                elif action == 2:
                    print("Generating an RSA key.")
                    key = rsa.Key(CONF.RSA_KEY_SIZE)
                    name = '-available'
                    if random.randint(1, 100) <= CONF.BOGUS_KEY_PCT:
                        name = '-bogus'
                    self._model.save_key(name, key.as_string())
                elif action == 3:
                    #bogus challenges
                    pass
                else:
                    print("Sleeping for %d seconds." % CONF.CLIENT_INTERVAL)
                    time.sleep(CONF.CLIENT_INTERVAL)
            except KeyboardInterrupt:
                print("Quitting worker.")
                exit(1)
Exemple #3
0
def encrypt(keytext, message):
    """ encrypt
    """

    try:
        pubkey = rsa.Key(keytext)
    except:
        print("Public key format error.")
        return None

    if len(message) < pubkey.max_payload():
        return base64.b64encode(pubkey.encrypt(message.encode('ascii')))

    return None
Exemple #4
0
def decrypt(keytext, message):
    """ decrypt
    """

    try:
        key = rsa.Key(keytext)
    except:
        print("Private key format error.")
        return None

    try:
        return key.decrypt(base64.b64decode(message)).decode()
    except:
        return None
 def found_key(self, key):
     """Validates / updates learned pub_key after .seek"""
     candidate = rsa.Key(key)
     if self.key is not None:
         if self.key.as_dict() == candidate.as_dict():
             #We must've already found it. Thanks anyway!
             return True
         else:
             #TODO: define a class of Security Exceptions
             raise ValueError("Someone is lying to you, hoss")
     candidate_hash = self._hash_from_key(candidate)
     if self.hash_name == candidate_hash:
         self.key = candidate
         return True
     else:
         """
         If a rogue Switch sends a .connect to us with a spoofed public
         key, we'll probably end up here. Just ignore that?
         """
         return False
Exemple #6
0
def main():
    """ main
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("-a",
                        "--add-peer",
                        action="store_true",
                        dest="add_peer")
    parser.add_argument("-P",
                        "--set-peer-key",
                        action="store_true",
                        dest="set_peer_key")
    parser.add_argument("-d",
                        "--delete-peer",
                        action="store_true",
                        dest="delete_peer")
    parser.add_argument("-s",
                        "--send-message",
                        action="store_true",
                        dest="send_message")
    parser.add_argument("-g",
                        "--view-messages",
                        action="store_true",
                        dest="view_messages")
    parser.add_argument("-n", "--name", type=str, dest="name")
    parser.add_argument("-H", "--host", type=str, dest="host")
    parser.add_argument("-p", "--port", type=int, dest="port")
    parser.add_argument("-k", "--pubkey-file", type=str, dest="pubkey_file")
    parser.add_argument("-S", "--source", type=str, dest="source")
    parser.add_argument("-m", "--message", type=str, dest="message")
    args = parser.parse_args()

    if args.add_peer:
        if not args.name or not args.host or not args.port:
            print("You must call --add-peer with name, host and port.")
            exit(1)

        model = Model()
        keytext = model.assign_peer(args.name)
        if keytext:
            exchange_key = rsa.Key(keytext).public.as_string()
            model.save_peer(args.name, args.host, args.port)
            print("Exchange key:")
            print(exchange_key)
        else:
            print("No RSA keys available for assignment.")
            exit(1)
        exit(0)

    if args.set_peer_key:
        if not args.name or not args.pubkey_file:
            print("You must call --set-peer-key with name, pubkey-file.")
            exit(1)
        if not os.path.exists(args.pubkey_file):
            print("pubkey-file %s doesn't exist." % args.pubkey_file)
            exit(1)
        with open(args.pubkey_file) as key_file:
            keytext = key_file.read()
            try:
                rsa.Key(keytext)
            except:
                print("Public key format error.")
                exit(1)
            model = Model()
            model.set_peer_key(args.name, keytext)
        exit(0)

    if args.delete_peer:
        if not args.name:
            print("You must call --delete-peer with name.")
            exit(1)
        model = Model()
        model.delete_peer(args.name)
        exit(0)

    if args.send_message:
        if not args.source or not args.message:
            print("You must call --send-message with source and message.")
            exit(1)
        model = Model()
        model.save_message(args.source, '*local', args.message)
        exit(0)

    if args.view_messages:
        model = Model()
        for message in model.view_messages():
            print("%s|sender:%s|delivered_by:%s|%s" %
                  (message[0], message[1], message[2], message[3]))
        exit(0)