Пример #1
0
    def list(self, prefix=None, delimiter=None, marker=None, limit=None):
        """ List objects of the bucket.

        Keyword arguments:
        prefix - Limits the response to keys that begin with the specified prefix
        delimiter - A character you use to group keys
        marker - Specifies the key to start with when listing objects
        limit - The count of objects that the request returns
        """
        params = {}
        if prefix:
            params["prefix"] = prefix
        if delimiter:
            params["delimiter"] = delimiter
        if marker:
            params["marker"] = marker
        if limit:
            params["limit"] = str(limit)
        response = self.connection.make_request("GET", self.name, params=params)
        if response.status == 200:
            resp = json.loads(response.read())
            result_set = []
            for k in resp["keys"]:
                key = Key(self, k["key"])
                key.content_type = k["mime_type"]
                result_set.append(key)
            return result_set
        else:
            err = get_response_error(response)
            raise err
    def __init__(self, aKey=None):
        if aKey is None:
            self.itsKey = Key()
        else:
            self.itsKey = Key(aKey)

        self.majorKeyName = self.itsKey.key[0]
Пример #3
0
  def nestKey(self, key):
    '''Returns a nested `key`.'''

    nest = self.nest_keyfn(key)

    # if depth * length > len(key.name), we need to pad.
    mult = 1 + int(self.nest_depth * self.nest_length / len(nest))
    nest = nest * mult

    pref = Key(self.nestedPath(nest, self.nest_depth, self.nest_length))
    return pref.child(key)
Пример #4
0
 def set_public_key(self):
     self.public_key = Key(None, None)
     print("Set modulus of public key.")
     user_input = il.input_positive_integer()
     self.public_key.set_modulus(user_input)
     print("Set exponent of public key.")
     user_input = il.input_positive_integer()
     while (not bt.is_relative_prime(user_input,
                                     bt.phi(self.public_key.get_modulus()))
            ) or user_input >= bt.phi(self.public_key.get_modulus()):
         print("Requirements for exponent has not been.\nPlease try again.")
         user_input = il.input_positive_integer()
     self.public_key.set_exponent(user_input)
Пример #5
0
    def handover(self, peer_id) -> dict:
        storage = dict()
        replica = dict()

        for k in list(self.storage):
            key = int(k)
            if Key.between(key, peer_id, self.id):
                storage[k] = self.storage.pop(k)
        for k in list(self.replica):
            key = int(k)
            if Key.between(key, self.predecessor[0], peer_id):
                replica[k] = self.replica.pop(k)
        return (storage, replica)
Пример #6
0
	def recursive_chi_crack(self,p):
		

		
			stime = time()
			lolz=[]
			parent = ""
			champion = ""
			candidate = ""
			fr_score = 20000000
			for x in range(0,p):
				parent = parent + 'a'
			for y in range(0,p):
				for combo in product(ascii_lowercase, repeat=1):
					liste = list(parent)
					liste[y] = ''.join(combo)
					candidate = ''.join(liste)
					temp = Key(candidate)
					lolz = decode_it(self.sliced,temp)
					stringer = "".join(lolz)
					if (chi_score(stringer)<fr_score):
						champion = candidate
						fr_score = chi_score(stringer)
				fr_score = 20000000
				parent = champion
				
			for z in range(0,p):
				for combo in product(ascii_lowercase, repeat=1):
					liste = list(parent)
					liste[p-(1+z)] = ''.join(combo)
					candidate = ''.join(liste)
					temp = Key(candidate)
					lolz = decode_it(self.sliced,temp)
					stringer = "".join(lolz)
					if (chi_score(stringer)<fr_score):
						champion = candidate
						fr_score = chi_score(stringer)
				fr_score = 20000000
				parent = champion
			
			print "The key found: %s\n" % parent
			puk = Key(parent)
			lolek = decode_it(self.sliced,puk)
			print "Decrypted message: %s\n" % " ".join(lolek)
			summ = open('summary.txt','a')
			etime = time()
			summ.write("\nRecursive Test:\nTime elapsed: %s\nMax_key_lenght: %s\nFile size: %s\n"% (str(etime-stime),p,os.path.getsize("test_recursive.txt")))
			summ.close()
			return True
Пример #7
0
    def test_dataset_prefix(self):
        key = Key(dataset=Dataset('dset'))
        protokey = key.to_protobuf()
        self.assertEqual('s~dset', protokey.partition_id.dataset_id)

        key = Key(dataset=Dataset('s~dset'))
        protokey = key.to_protobuf()
        self.assertEqual('s~dset', protokey.partition_id.dataset_id)

        key = Key(dataset=Dataset('e~dset'))
        protokey = key.to_protobuf()
        self.assertEqual('e~dset', protokey.partition_id.dataset_id)
Пример #8
0
def enter():
    global map
    map = Map()
    game_world.add_object(map, 0)

    global horn
    horn = Horn()
    game_world.add_object(horn, 1)

    global boss
    boss = Boss()
    game_world.add_object(boss, 1)

    global character
    character = Character()
    game_world.add_object(character, 1)

    global butterflys
    butterflys = [Butterfly(character) for i in range(7)]
    game_world.add_objects(butterflys, 1)

    key = Key()
    game_world.add_object(key, 1)

    map.set_center_object(character)
    character.set_background(map)
    horn.set_background(map)
    boss.set_background(map)
Пример #9
0
 def test_constructor(self):
     k = Key()
     self.assertEqual(k.sf, 0)
     self.assertEqual(k.key_type, constants.TREBLE)
     self.assertEqual(k.add_pitch, 0)
     self.assertEqual(k.root, 2)
     self.assertEqual(k.root_acc, constants.A_NT)
    def __init__(self, world):
        self.__world = world
        self.__platforms = pg.sprite.Group()
        self.__items = pg.sprite.Group()
        self.__exit = pg.sprite.Group()
        self.__bg = (BLUE)

        row_count = 0
        for row in self.__world:
            col_count = 0
            for tile in row:
                if tile == 1:
                    wall = Platform(col_count * TILE_SIZE_W,
                                    row_count * TILE_SIZE_H, TILE_SIZE_W,
                                    TILE_SIZE_H, BLUE)
                    self.__platforms.add(wall)
                    #tile = (wall.image, wall.rect)
                elif tile == 2:
                    grogu = Key(col_count * TILE_SIZE_W,
                                row_count * TILE_SIZE_H, 20, 20, GREEN)
                    self.__items.add(grogu)
                elif tile == 3:
                    ship = Extraction_point(col_count * TILE_SIZE_W,
                                            row_count * TILE_SIZE_H,
                                            TILE_SIZE_W, TILE_SIZE_H, PURPLE)
                    self.__exit.add(ship)
                col_count += 1
            row_count += 1

        self.__spawn_point = ((WIDTH, HEIGHT))
Пример #11
0
class NamespaceDatastore(KeyTransformDatastore):
  '''Represents a simple ShimDatastore that namespaces all incoming keys.
     For example:

      >>> import datastore.core
      >>>
      >>> ds = datastore.DictDatastore()
      >>> ds.put(datastore.Key('/a/b'), 'ab')
      >>> ds.put(datastore.Key('/c/d'), 'cd')
      >>> ds.put(datastore.Key('/a/b/c/d'), 'abcd')
      >>>
      >>> nd = datastore.NamespaceDatastore('/a/b', ds)
      >>> nd.get(datastore.Key('/a/b'))
      None
      >>> nd.get(datastore.Key('/c/d'))
      'abcd'
      >>> nd.get(datastore.Key('/a/b/c/d'))
      None
      >>> nd.put(datastore.Key('/c/d'), 'cd')
      >>> ds.get(datastore.Key('/a/b/c/d'))
      'cd'

  '''

  def __init__(self, namespace, *args, **kwargs):
    '''Initializes NamespaceDatastore with `key` namespace.'''
    super(NamespaceDatastore, self).__init__(*args, **kwargs)
    self.keytransform = self.namespaceKey
    self.namespace = Key(namespace)

  def namespaceKey(self, key):
    '''Returns a namespaced `key`: namespace.child(key).'''
    return self.namespace.child(key)
Пример #12
0
    def setNote(self, noteabout, note=""):
        # Format the Key.
        key = Key(pub=noteabout)
        noteabout = key.pubkey

        newnote = {
            "user": self.Keys['master'].pubkey,
            "noteabout": noteabout,
            "note": note
        }

        # Retrieve any existing note, so that the _id is the same. Then, we'll
        # gut it, and put in our own values.
        newnote = self.server.db.unsafe.find_one('notes', {
            "user": self.Keys['master'].pubkey,
            "noteabout": noteabout
        })
        if newnote is None:
            newnote = {
                "user": self.Keys['master'].pubkey,
                "noteabout": noteabout,
                "note": note
            }
        newnote['note'] = note
        self.server.db.unsafe.save('notes', newnote)
        self.getNote(noteabout=noteabout, invalidate=True)
Пример #13
0
def key_exchange(conn) -> tuple[int, int]:
    client_public_key = conn.recv(2048).decode('utf-8')
    print("Received client public key: " +
          client_public_key.replace('\n', " "))

    client_public_key = client_public_key.split('\n')
    calc_key_client = Key(create_param(), int(client_public_key[0]),
                          int(client_public_key[1]))
    B_attr_server = str(calc_key_client.AB) + '\n'
    conn.send(B_attr_server.encode('utf-8'))
    print("Sent server B attribute to the client: " +
          B_attr_server.replace('\n', " "))

    server_public_key = read_key("public_key_server.pem")
    conn.send(server_public_key.encode('utf-8'))
    print('Sent server public key to the client: ' +
          server_public_key.replace('\n', " "))

    B_attr_client = conn.recv(2048).decode('utf-8')
    print("Received client B attribute key: " +
          B_attr_client.replace('\n', " "))
    B_attr_client = B_attr_client.split('\n')

    server_private_key = read_key("private_key_server.pem").split('\n')
    server_public_key = server_public_key.split('\n')

    K_client = create_sym_key(calc_key_client.ab, int(client_public_key[2]),
                              calc_key_client.p)
    print('Calculated common private key for the client: ' + str(K_client))
    K_server = create_sym_key(int(server_private_key[0]),
                              int(B_attr_client[0]), int(server_public_key[1]))
    print('Calculated common private key for the server: ' + str(K_server))

    return K_client, K_server
Пример #14
0
 def send_create_account_tx(self, new_account_id, base_block_hash=None):
     self.prep_tx()
     new_key = Key(new_account_id, self.key.pk, self.key.sk)
     tx = sign_create_account_with_full_access_key_and_balance_tx(
         self.key, new_account_id, new_key, 100 * NEAR_BASE, self.nonce,
         base_block_hash or self.base_block_hash)
     return self.send_tx(tx)
Пример #15
0
 def notify(self, id: int, peer: tuple):
     if self.predecessor is None or Key.between(id, self.predecessor[0],
                                                self.id):
         self.predecessor = (id, peer[0])
         logging.debug(f"Got a new predecessor: [{self.predecessor}]")
         return self.handover(id)
     return None
Пример #16
0
def get_key(file_in):
    """
    Estimates the key and scale for an audio file.
    """
    loader = streaming.MonoLoader(filename=file_in)
    framecutter = streaming.FrameCutter()
    windowing = streaming.Windowing(type="blackmanharris62")
    spectrum = streaming.Spectrum()
    spectralpeaks = streaming.SpectralPeaks(orderBy="magnitude",
                                            magnitudeThreshold=1e-05,
                                            minFrequency=40,
                                            maxFrequency=5000,
                                            maxPeaks=10000)
    pool = Pool()
    hpcp = streaming.HPCP()
    key = streaming.Key()

    loader.audio >> framecutter.signal
    framecutter.frame >> windowing.frame >> spectrum.frame
    spectrum.spectrum >> spectralpeaks.spectrum
    spectralpeaks.magnitudes >> hpcp.magnitudes
    spectralpeaks.frequencies >> hpcp.frequencies
    hpcp.hpcp >> key.pcp
    key.key >> (pool, 'tonal.key_key')
    key.scale >> (pool, 'tonal.key_scale')
    key.strength >> (pool, 'tonal.key_strength')

    run(loader)

    return Key(pool['tonal.key_key'], pool['tonal.key_scale'])
Пример #17
0
class NamespaceDatastore(KeyTransformDatastore):
  '''Represents a simple ShimDatastore that namespaces all incoming keys.
     For example:

      >>> import datastore.core
      >>>
      >>> ds = datastore.DictDatastore()
      >>> ds.put(datastore.Key('/a/b'), 'ab')
      >>> ds.put(datastore.Key('/c/d'), 'cd')
      >>> ds.put(datastore.Key('/a/b/c/d'), 'abcd')
      >>>
      >>> nd = datastore.NamespaceDatastore('/a/b', ds)
      >>> nd.get(datastore.Key('/a/b'))
      None
      >>> nd.get(datastore.Key('/c/d'))
      'abcd'
      >>> nd.get(datastore.Key('/a/b/c/d'))
      None
      >>> nd.put(datastore.Key('/c/d'), 'cd')
      >>> ds.get(datastore.Key('/a/b/c/d'))
      'cd'

  '''

  def __init__(self, namespace, *args, **kwargs):
    '''Initializes NamespaceDatastore with `key` namespace.'''
    super(NamespaceDatastore, self).__init__(*args, **kwargs)
    self.keytransform = self.namespaceKey
    self.namespace = Key(namespace)

  def namespaceKey(self, key):
    '''Returns a namespaced `key`: namespace.child(key).'''
    return self.namespace.child(key)
Пример #18
0
    def __init__(self):
        self.rooms = []
        self.currentRoom = 0
        self.inventory = []

        firstRoom = Room(
            1,
            "Je staat in de keuken. Er staan een aanrecht en een koelkast, en er is 1 deur.",
            [Door(123, 1)],
            [Key(123, "woonkamersleutel"),
             Key(321, "schatkistsleutel")])
        secondRoom = Room(2, "Je staat in de woonkamer, er is een deur",
                          [Door(123, 0)], [])
        self.rooms.append(firstRoom)
        self.rooms.append(secondRoom)
        print(self.rooms[self.currentRoom].description)
Пример #19
0
def decode(file_path, out_path):

    if out_path == "":
        out_path = file_path.replace('.pi', '')

    print("Generating array from encryption key...")
    encryption_key = Key('data/pi.dat')

    CHUNK_SIZE = 1

    print("Reading file to decrypt...")
    with open(file_path, 'rb') as infile:
        indexes = infile.read().split(',')

    print("Decrypting file...")
    pointer_array = map(encryption_key.get_data, indexes)

    print("Dumping decrypted file...")
    with open(out_path, 'a') as outfile:

        b64string = ''.join(map(chr, pointer_array))

        missing_padding = 4 - len(b64string) % 4
        if missing_padding:
            b64string += b'=' * missing_padding

        outfile.write(base64.decodestring(b64string))

    os.remove('cache.db')
Пример #20
0
    def updatefinger(self, newnode, firstnode):
        '''

        UPdate finger table for all ring in a clockwise around successor fashion

        finger is an array of dict {resp, key}

            `resp` is the Node responsible for `key`

        @param newnode: new node which imply this update

        @param firstnode: node which launch the update

        '''

        for i in range(0, self.uid.idlength):

            fingerkey = self.calcfinger(i)

            resp = self.lookup(fingerkey, useOnlySucc=True)

            self.finger[i] = {"resp": resp, "key": Key(fingerkey)}

            #self.finger[i] = self.lookupfinger(i, useOnlySucc=True)

        if firstnode is not self.successor:

            self.successor.updatefinger(newnode, firstnode)
Пример #21
0
 def kitchen2(self):
     room = Room()
     moldyCheese = Item('moldy cheese')
     moldyCheese.movable = True
     moldyCheese.effects['healing'] = 5
     room.inventory.add(moldyCheese)
     cat = Item('cat')
     cat.movable = False
     cat.messages['nopickup'] = 'It seems like a cat but its actually an alien.'
     room.inventory.add((cat))
     wierdThing = Item('???')
     wierdThing.movable = False
     wierdThing.messages['nopickup'] = "Its seems to be a slimy looking thing that is stuck to the floor and tried to eat your hand when you touched it."
     key2 = Item("cake key")
     key2.effects["description"] = "A key the looks like a cake but is actually the key for the kings office."
     key2.key = Key("cake key", "The king's office unlocks.")
     room.inventory.add(key2)
     room.inventory.add((wierdThing))
     room.long_description = """It's the castle kitchen but its hard to tell because it also could be a pet room, for aliens, which the room is full of."""
     room.short_description = """An old kitchen, or pet room, for aliens"""
     room.name = "Kitchen"
     room.exits = {'n': Connection(7) }        
     #room.exits = {'e': 0}
     room.monster = Monster("Musclar spoon", 6, 3, 10)
     return room
Пример #22
0
    def shack(self):
        room = Room()
        lantern = Item('lantern')
        lantern.effects['description'] = 'You would light up the room but the lantern was too sick.'
        room.inventory.add(lantern)
        kitchenKey = Item("kitchen key")
        kitchenKey.shortname = 'key'
        kitchenKey.movable = True
        kitchenKey.key = Key("kitchen key", "The door is unlocked.")
        kitchenKey.effects['description'] = "It's a key to the kitchen."
        room.inventory.add(kitchenKey)
        room.long_description = """You are in a small shack. It has a creaky floor, leaky roof and you are scared.oh not of the room but the cage with a lion in it."""
        room.short_description = """A small wooden shack."""
        room.name = "Shack"
        #room.exits = {'e': 1, 'w': -3}
        room.exits = {
                'e': Connection(1), 
                'w': Connection( 3,
                    'kitchen door',
                    'locked',
                    kitchenKey, 
                    'The kitchen door is firmly locked. There should be a key somewhere around.') }
        #room.locked = {'w': }

        return room
Пример #23
0
def trySerialize(obj):
    if isinstance(obj, basestring):
        return Key(obj).serialize()
    if hasattr(obj, 'serialize'):
        return obj.serialize()
    else:
        return obj
Пример #24
0
    def populate_map(self, map):
        # define rooms and items
        # furniture
        couch = Furniture("couch")
        piano = Furniture("piano")
        double_bed = Furniture("double bed")
        queen_bed = Furniture("queen bed")
        dresser = Furniture("dresser")
        dining_table = Furniture("dining table")

        # doors
        door_a = Door("door a")
        door_b = Door("door b")
        door_c = Door("door c")
        door_d = Door("door d")

        # keys
        key_a = Key("key for door a", door_a)
        key_b = Key("key for door b", door_b)
        key_c = Key("key for door c", door_c)
        key_d = Key("key for door d", door_d)

        # rooms
        game_room = Room("game room")
        bedroom_1 = Room("bedroom 1")
        bedroom_2 = Room("bedroom 2")
        living_room = Room("living room")
        outside = Room("outside")

        # setting start and end rooms
        map.set_start_room(game_room)
        map.set_end_room(outside)

        # object relations
        map.add_relation("game room", [couch, piano, door_a])
        map.add_relation("bedroom 1", [queen_bed, door_a, door_b, door_c])
        map.add_relation("bedroom 2", [double_bed, dresser, door_b])
        map.add_relation("living room", [dining_table, door_c, door_d])
        map.add_relation("outside", [door_d])
        map.add_relation("piano", [key_a])
        map.add_relation("double bed", [key_c])
        map.add_relation("dresser", [key_d])
        map.add_relation("queen bed", [key_b])
        map.add_relation("door a", [game_room, bedroom_1])
        map.add_relation("door b", [bedroom_1, bedroom_2])
        map.add_relation("door c", [bedroom_1, living_room])
        map.add_relation("door d", [living_room, outside])
Пример #25
0
 def __init__(self, name, eth_secret_key, near_sk, near_pk):
     self.name = name
     self.eth_secret_key = eth_secret_key
     self.near_account_name = name + '.test0'
     self.tokens_expected = dict()
     self.near_signer_key = Key(self.near_account_name, near_pk, near_sk)
     # Following fields will be initialized when Bridge starts
     self.eth_address = None
Пример #26
0
    def add_key(self, key, qtd=0):
        k = Key(key)

        if qtd == 0:
            self.bag.append(k)
        else:
            for i in range(0, qtd):
                self.bag.append(k)
Пример #27
0
    def get(self,key):
        """ Gets the given key. """
        try:

            res = self._remoteSend(PAGE_GET, { KEY : key })
            return Key(self,key,self._keyToDict(res))
        except H2OException:
            return None
Пример #28
0
def Start():
    """ Start of game || Sets the room up """
    global Plyr, instances
    print("Objective: Escape the room")
    print("Commands:")
    print("       search, take, use, examine, exit")
    print("       Try 'examine player'")
    Plyr = Player("Player")  # Player Obj
    Exit = ExitDoor("Door_Exit")  # Door_Exit Obj
    instances.append(Plyr)
    instances.append(Exit)
    Bathroom = Room("Bathroom")  # Room Obj
    Plyr.moveTo(Bathroom)
    instances.append(Bathroom)

    Cupboard_1 = Storage("Left_Cupboard")  # Storage Obj
    instances.append(Cupboard_1)
    Cupboard_2 = Storage("Right_Cupboard")  # Storage Obj
    instances.append(Cupboard_2)

    Cupboard_1.locked = True  # Whether its locked or not
    Cupboard_1.lock_id = 61  # The Id to unlock it
    Cupboard_2.lock_id = 312  # The Id to unlock it
    Cupboard_2.locked = True  # Whether its locked or not

    Key_1 = Key("Silver_Key", Cupboard_1.lock_id)  # Key Obj
    instances.append(Key_1)
    Plyr.inventory.append(Key_1)
    Key_1.parent = Plyr  # The Parent Of The Key
    Exit.lock_id = 31  # The id to unlock it
    Exit.locked = True  # Whether its locked or not
    Key_2 = Key("Gold_Key", Exit.lock_id)  # Key Obj
    instances.append(Key_2)
    Cupboard_1.AddContent(Key_2)

    Bathroom.AddContent(Cupboard_1)
    Bathroom.AddContent(Cupboard_2)
    Bathroom.AddContent(Exit)
    while True:
        op = rec()  # Output from rec() function
        if isinstance(op, list):
            if len(op) >= 2:
                # String to be executed
                strng = ("op[0]" + "." + op[1] + "(Plyr, instances)")
                exec(strng)
Пример #29
0
 def __delitem__(self, key):
     key = Key(key)
     # dd(f'__delitem__:[{key}]')
     try:
         super(NoCaseDict, self).__delitem__(key)
         if self.is_operational:
             self.is_dirty = True
     except Exception as e:
         df.LOG(f'{e};', error=True)
Пример #30
0
    def assembly():
        rounded_1u = Key(
            key_shape=rounded_key,
            z=11,
            depth=2.5,
            dish_type="sphere",  # text="E")
        )
        rounded_1p5u = Key(key_shape=rounded_key,
                           size=[1, 1.5],
                           depth=1.5,
                           dish_type="sphere")
        rounded_2u = Key(key_shape=rounded_key,
                         size=[1, 2],
                         depth=2.5,
                         dish_type="sphere")
        out = make_insert(rounded_1u)

        return out
Пример #31
0
    def create_key(self, name, value, is_storage=True):
        if is_storage:
            self.keys[value] = StorageKey(name=name, value=value)
            self.available_storage += 1
            return self.keys[value]

        self.keys[value] = Key(name=name, value=value)
        self.key_name_to_value_mapping[name] = value
        return self.keys[value]
Пример #32
0
    def new_key(self, key_name=None, key_type=Key.KEY_REGULAR_FILE):
        """
        Creates a new key

        :type key_name: string
        :param key_name: The name of the key to create

        :rtype: :class:`boto.file.key.Key`
        :returns: An instance of the newly created key object
        """
        if key_name == '-':
            return Key(self.name, '-', key_type=Key.KEY_STREAM_WRITABLE)
        else:
            dir_name = os.path.dirname(key_name)
            if dir_name and not os.path.exists(dir_name):
                os.makedirs(dir_name)
            fp = open(key_name, 'wb')
            return Key(self.name, key_name, fp)
Пример #33
0
 def __getitem__(self, key):
     key = Key(key)
     try:
         value = super(NoCaseDict, self).__getitem__(key)
         # dd(f'__getitem__:[{key}], value:[{value}]')
         return value
     except Exception as e:
         df.LOG(f'{e}', error=True)
         return None
Пример #34
0
 def _link_for_value(self, value):
   '''Returns the linked key if `value` is a link, or None.'''
   try:
     key = Key(value)
     if key.name == self.sentinel:
       return key.parent
   except:
     pass
   return None
Пример #35
0
	def initialize(self, naive):

		self.keys = []
		
		naive_key = Key(self.alphabet)
		naive_key.compute_naive(self.exp_stats, self.ciph_stats)
		naive_key.reverse()
		
		for i in xrange(0, self.max_pop):
			if naive:
				new_key = naive_key.clone()
				new_key.shuffle(3)
			else:
				new_key = Key(self.alphabet)
				new_key.randomize()

			self.keys.append(new_key)
class KeySigQuestion(object):
    def __init__(self, aKey=None):
        if aKey is None:
            self.itsKey = Key()
        else:
            self.itsKey = Key(aKey)

        self.majorKeyName = self.itsKey.key[0]

    def ask(self):
        choice = []
        choice.append(self.givenKeyGiveAccidentals)
        choice.append(self.givenSignatureGiveKey)
        choice.append(self.givenAccidentalsGiveKey)
        return random.choice(choice)()

    def givenKeyGiveAccidentals(self):
        self.q = "What's the key signature of " + self.majorKeyName + "? "
        self.correctAns = self.itsKey.textual_key_signature()
        self.a = my_input(self.q).strip()
        result = (self.a == self.correctAns)
        
        return result
    
    def givenSignatureGiveKey(self):
        self.q = "What key has " + self.itsKey.textual_key_signature() + "? "
        self.correctAns = self.majorKeyName
        self.a = my_input(self.q).strip()
        result = (self.a == self.correctAns)
        
        return result

    def givenAccidentalsGiveKey(self):
        self.q = "What key has " + ", ".join(self.itsKey.accidentals()) + "? "
        self.correctAns = self.majorKeyName
        self.a = my_input(self.q).strip()
        result = (self.a == self.correctAns)
        
        return result
Пример #37
0
def get_credentials(username=None, password=None):
    """Asks the user to input a username & password, using previous values or appropriately derived defaults"""
    if username is None:
        username = getpass.getuser()
    input_username = raw_input("username (" + username + ")")
    if len(input_username) > 0:
        username = input_username
    if password is None:
        input_password = getpass.getpass("password (random)")
        if len(input_password) == 0:
            password = Key.generate_password(config["password_length"])
        else:
            password = input_password
    else:
        input_password = raw_input("password (previous)")
        if len(input_password) > 0:
            password = input_password
    return {"username": username, "password": password}
Пример #38
0
def get_credentials(username=None, password=None):
    """Asks the user to input a username & password, using previous values or appropriately derived defaults"""
    if username is None:
        username = getpass.getuser()
    input_username = raw_input('username ('+username+')')
    if len(input_username) > 0:
        username = input_username
    if password is None:
        input_password = getpass.getpass('password (random)')
        if len(input_password) == 0:
            password = Key.generate_password(config['password_length'])
        else:
            password = input_password
    else:
        input_password = raw_input('password (previous)')
        if len(input_password) > 0:
            password = input_password
    return {'username': username, 'password': password}
Пример #39
0
 def test_init_no_arguments(self):
   key = Key()
   self.assertEqual([{'kind': ''}], key.path())
   self.assertEqual('', key.kind())
   self.assertEqual(None, key.dataset())
   self.assertEqual(None, key.namespace())
Пример #40
0
def main():
    args = docopt(__doc__, version="keyfor " + VERSION)

    masterkey = get_masterkey(username=args["--username"])
    keychain = KeyChain(path=os.path.expanduser(config["key_path"]), masterkey=masterkey)

    if "<label>" in args and args["<label>"]:
        label = args["<label>"]
        subset = args["<subset>"]

        if "add" in args and args["add"]:
            keys = keychain.list_keys()
            if label in keys:
                print "Key already stored for label: " + label + ", -u to update or ommit flags to read"
                return
            print "Create a new key for: " + label
            credentials = get_credentials(username=masterkey.username)
            key = Key(label=label, username=credentials["username"], password=credentials["password"])
            keychain.save_key(key)
            print "created new key for: " + key.label
            show_key(key, subset)

        elif "edit" in args and args["edit"]:
            key = read_key(keychain, label)
            if key:
                credentials = get_credentials(username=key.username, password=key.password)
                key.username = credentials["username"]
                key.password = credentials["password"]
                keychain.save_key(key)
                print "Updated key for label: " + label
                show_key(key, subset)

        elif "delete" in args and args["delete"]:
            if key_exists(keychain, label):
                keychain.delete_key(label)

        elif "refresh" in args and args["refresh"]:
            if key_exists(keychain, label):
                refresh_key(keychain, label)

        elif "verify" in args and args["verify"]:
            if key_exists(keychain, label):
                verify_key(keychain, label)

        else:
            key = read_key(keychain, label)
            if key:
                shoud_print = "--print" in args and args["--print"]
                show_key(key, subset, shoud_print=shoud_print)

    elif "all" in args and args["all"]:

        if "refresh" in args and args["refresh"]:
            for label in keychain.list_keys():
                refresh_key(keychain, label)

        elif "verify" in args and args["verify"]:
            for label in keychain.list_keys():
                verify_key(keychain, label)

        elif "list" in args and args["list"]:
            for label in keychain.list_keys():
                print label

    else:
        print __doc__
Пример #41
0
    def create_key(self, key, name):

        data = {"name": name, "public_key": key}
        return Key.create_new(data, self.authentication_token)
Пример #42
0
    def get_key(self, key_id):

        return Key.from_existing(key_id, self.authentication_token)
Пример #43
0
 def key(self):
     Key.generate_key()
     self.insert_image(self._key_img, filename=Key.FILENAME)
Пример #44
0
def main():    
    args = docopt(__doc__, version='keyfor '+VERSION)
    
    # print repr(args)

    masterkey = get_masterkey(username=args['--username'])
    keychain = KeyChain(path=os.path.expanduser(config['key_path']), masterkey=masterkey)
    
    if '<label>' in args and args['<label>']:
        label = args['<label>']
        
        if 'add' in args and args['add']:
            keys = keychain.list_keys()
            if label in keys:
                print "Key already stored for label: " + label +", -u to update or ommit flags to read"
                return
            print "Create a new key for: " + label
            credentials = get_credentials(username=masterkey.username)
            key = Key(label=label, username=credentials['username'], password=credentials['password'])
            keychain.save_key(key)
            print "created new key for: "+key.label
            show_key(key)
            
        elif 'edit' in args and args['edit']:
            key = read_key(keychain, label)
            if key:
                credentials = get_credentials(username=key.username, password=key.password)
                key.username = credentials['username']
                key.password = credentials['password']
                keychain.save_key(key)
                print "Updated key for label: " + label
                show_key(key)
                
        elif 'delete' in args and args['delete']:
            if key_exists(keychain, label):
                keychain.delete_key(label)
                
        elif 'refresh' in args and args['refresh']:
            if key_exists(keychain, label):
                refresh_key(keychain, label)
                
        elif 'verify' in args and args['verify']:
            if key_exists(keychain, label):
                verify_key(keychain, label)
                    
        else:
            key = read_key(keychain, label)
            if key:
                show_key(key)
                
    elif 'all' in args and args['all']:
                
        if 'refresh' in args and args['refresh']:
            for label in keychain.list_keys():
                refresh_key(keychain, label)
        
        elif 'verify' in args and args['verify']:
            for label in keychain.list_keys():
                verify_key(keychain, label)
        
        elif 'list' in args and args['list']:
            for label in keychain.list_keys():
                print label
        
    else:
        print __doc__
Пример #45
0
    def __init__(self, settingsfile=None, workingdir=None, slot='default'):

        super().__init__(slot)

        # Don't run this more than once.
        if self.__dict__.get('set') is True:
            return
        else:
            self.set = True

        self.logger = logging.getLogger('Tavern')

        # Should the server run in debug mode
        self.debug = False

        self.serversettings = ServerSettings.ServerSettings(settingsfile)
        if self.serversettings.updateconfig():
            self.serversettings.saveconfig()

        if not 'pubkey' in self.serversettings.settings or not 'privkey' in self.serversettings.settings:
            # Generate New config
            self.logger.info("Generating new Config")
            self.ServerKeys = Key()
            self.ServerKeys.generate()

            # We can't encrypt this.. We'd need to store the key here on the machine...
            # If you're worried about it, encrypt the disk, or use a loopback.
            self.serversettings.settings['pubkey'] = self.ServerKeys.pubkey
            self.serversettings.settings['privkey'] = self.ServerKeys.privkey

            self.serversettings.updateconfig()
            self.serversettings.saveconfig()

        self.mc = OrderedDict
        self.unusedkeycache = multiprocessing.Queue(
            self.serversettings.settings['KeyGenerator']['num_pregens'])
        # Break out the settings into it's own file, so we can include it without including all of server
        # This does cause a few shenanigans while loading here, but hopefully
        # it's minimal

        self.ServerKeys = Key(pub=self.serversettings.settings['pubkey'],
                              priv=self.serversettings.settings['privkey'])

        self.db = DBWrapper(
            name=self.serversettings.settings['dbname'],
            dbtype=self.serversettings.settings['dbtype'],
            host=self.serversettings.settings['mongo-hostname'],
            port=self.serversettings.settings['mongo-port'])
        self.sessions = DBWrapper(
            name=self.serversettings.settings['sessions-db-name'],
            dbtype=self.serversettings.settings['dbtype'],
            host=self.serversettings.settings['sessions-db-hostname'],
            port=self.serversettings.settings['sessions-db-port'])
        self.binaries = DBWrapper(
            name=self.serversettings.settings['bin-mongo-db'],
            dbtype='mongo',
            host=self.serversettings.settings['bin-mongo-hostname'],
            port=self.serversettings.settings['bin-mongo-port'])
        self.bin_GridFS = GridFS(self.binaries.unsafe.mongo)

        # Ensure we have Proper indexes.
        self.db.safe.ensure_index('envelope', 'envelope.local.time_added')
        self.db.safe.ensure_index('envelope', 'envelope.local.sorttopic')
        self.db.safe.ensure_index('envelope', 'envelope.local.payload_sha512')
        self.db.safe.ensure_index('envelope', 'envelope.payload.class')
        self.db.safe.ensure_index('envelope', 'envelope.payload.regarding')
        self.db.safe.ensure_index(
            'envelope',
            'envelope.payload.binaries.sha_512')
        self.db.safe.ensure_index('envelope', 'envelope.local.payload_sha512')
        self.db.safe.ensure_index('envelope', 'envelope.payload.author.pubkey')
        self.db.safe.ensure_index('envelope', 'envelope.payload.author.pubkey')
        self.db.safe.ensure_index('envelope', 'usertrusts.asking')
        self.db.safe.ensure_index('envelope', 'incomingtrust')

        self.binaries.safe.ensure_index('fs.files', 'filename')
        self.binaries.safe.ensure_index('fs.files', 'uploadDate')
        self.binaries.safe.ensure_index('fs.files', '_id')
        self.binaries.safe.ensure_index('fs.files', 'uploadDate')

        # Get a list of all the valid templates that can be used, to compare
        # against later on.
        self.availablethemes = []
        for name in os.listdir('themes'):
            if os.path.isdir(os.path.join('themes', name)):
                if name[:1] != ".":
                    self.availablethemes.append(name)

        self.serversettings.settings['static-revision'] = int(time.time())

        self.fortune = TavernUtils.randomWords(fortunefile="data/fortunes")
        self.wordlist = TavernUtils.randomWords(fortunefile="data/wordlist")

        # Define out logging options.
        formatter = logging.Formatter('[%(levelname)s] %(message)s')
        self.consolehandler = logging.StreamHandler()
        self.consolehandler.setFormatter(formatter)
        self.handler_file = logging.FileHandler(
            filename=self.serversettings.settings['logfile'])
        self.handler_file.setFormatter(formatter)

        self.logger.setLevel(self.serversettings.settings['loglevel'])
        level = self.serversettings.settings['loglevel']

        # Cache our JS, so we can include it later.
        file = open("static/scripts/instance.min.js")
        self.logger.info("Cached JS")
        TavernCache.cache['instance.js'] = file.read()
        file.close()
        self.guestacct = None
Пример #46
0
	def prototype(self,p):
		# laduje zmienne do petli
		
		if p<= 7:
			plc = 0
		else:
			plc = p-7
		
		count = 0
		outtie = 0
		tnum = 0
		before = 0
		after = 0
		stime = time()
		lolz=self.sliced
		dict_score =0
		# laduje zeslicowany slownik i pliki
		
		summ = open('summary.txt','a')
		f = open('test_smeeris.txt','w')
		
		dicts = self.dict_slicer()
		
		#lista popularnych slowek 3 literowych
		lyst = ['the' ,'and' ,'for' ,'not' ,'you' ,'but','say','her','she','all','one','out','who','get','can','him','see','now','did','big']
		#lista wkladow do szablonu hasla
		wklady = []
		surowka = []
		
		
		#wyrabianie wkladow
		
		for word in self.sliced:
			if len(word) == 3:
				surowka.append(word)
				break
		
		for combo in product(ascii_lowercase, repeat=3):
			temp = Key(''.join(combo))
			print temp
			outus = decode_it(surowka,temp)
			if outus[0] in lyst:
				wklady.append(temp.to_string())
		
		#koniec wyrabiania wkladow
		
		#robienie szablonu
		tnum = 0
		dict_score=0
		for ex in lolz:
			if not len(ex) == 3 :
				tnum += len(ex)
			else:
				passw = p*'*'
								
				mess = list(passw) 
								

				tnum = tnum % p
				stri = "123"

				numerra = 0
				for iks in range(tnum,tnum+3 ):
					print iks
					safe = iks % p
					mess[safe] = stri[numerra]
					numerra +=1
								
				numerra = 0
				passw = "".join(mess)
				break
		available = []
		passer = ""
		for a in range(0,len(passw)):
			if passw[a] == '*':
				available.append(a)
				passer += 'a'
			else:
				passer += passw[a]
		print wklady
		print passer
	#	return True
		print available
		combos= []
		for kombo in product(ascii_lowercase, repeat=len(available)):
			combos.append(kombo)
		
		for part in wklady:
			my_key = ""
			dict_score=0 
			
			for letter in passer:
				
				if letter == "1":
					my_key += part[0]
				if letter == "2":
					my_key += part[1]
				if letter == "3":
					my_key += part[2]
				if letter == "a":
					my_key += "a"
					
			dict_cracks = False
			for nummie in combos:
				liste = list(my_key)

				for av in range(0,len(nummie)):	
					liste[available[av]] =   nummie[av]
				candidate = ''.join(liste)

				if dict_cracks==False and 	candidate[available[plc]] == "l":
					break			
					
				print candidate
							
				temp = Key(candidate)
				lolz = decode_it(self.sliced,temp)
				stringer = "".join(lolz)
				# wynik analizy slownikowej
				if(60 > chi_score(stringer)):
					result = self.dict_check(lolz,dicts)
					dict_cracks = True	
					if ( result > dict_score and result > float(1)/len(lolz)):
						my_key = candidate
						dict_score = self.dict_check(lolz,dicts)
						f.write( "Key:%s\n" % (my_key)+"\n" + str(lolz)+"\n\n  " + str(chi_score(stringer)) +"\n\n" )
					
								
		f.close()
		etime = time()
		summ.write("\Proto Test:\nTime elapsed: %s\nMax_key_lenght: %s\nFile size: %s\n"% (str(etime-stime),p,os.path.getsize("test_smeeris.txt")))
		summ.close()
		#print combos
		return True 
Пример #47
0
class Server(TavernUtils.instancer):

    # We want to share state across all Server instances.
    # This way we can create a new instance, anywhere, in any subclass, and
    # get the same settings/etc

    class FancyDateTimeDelta(object):

        """Format the date / time difference between the supplied date and the
        current time using approximate measurement boundaries."""

        def __init__(self, dt):
            now = datetime.datetime.now()
            delta = now - dt
            self.year = round(delta.days / 365)
            self.month = round(delta.days / 30 - (12 * self.year))
            if self.year > 0:
                self.day = 0
            else:
                self.day = delta.days % 30
            self.hour = round(delta.seconds / 3600)
            self.minute = round(delta.seconds / 60 - (60 * self.hour))
            self.second = delta.seconds - (self.hour * 3600) - \
                                          (60 * self.minute)
            self.millisecond = delta.microseconds / 1000

        def format(self):
            # Round down. People don't want the exact time.
            # For exact time, reverse array.
            fmt = ""
            for period in ['millisecond', 'second', 'minute', 'hour', 'day', 'month', 'year']:
                value = getattr(self, period)
                if value:
                    if value > 1:
                        period += "s"

                    fmt = str(value) + " " + period
            return fmt + " ago"

    def getnextint(self, queuename, forcewrite=False):
        if not 'queues' in self.serversettings.settings:
            self.serversettings.settings['queues'] = {}

        if not queuename in self.serversettings.settings['queues']:
            self.serversettings.settings['queues'][queuename] = 0

        self.serversettings.settings['queues'][queuename] += 1

        if forcewrite:
            self.serversettings.saveconfig()

        return self.serversettings.settings['queues'][queuename]

    def __init__(self, settingsfile=None, workingdir=None, slot='default'):

        super().__init__(slot)

        # Don't run this more than once.
        if self.__dict__.get('set') is True:
            return
        else:
            self.set = True

        self.logger = logging.getLogger('Tavern')

        # Should the server run in debug mode
        self.debug = False

        self.serversettings = ServerSettings.ServerSettings(settingsfile)
        if self.serversettings.updateconfig():
            self.serversettings.saveconfig()

        if not 'pubkey' in self.serversettings.settings or not 'privkey' in self.serversettings.settings:
            # Generate New config
            self.logger.info("Generating new Config")
            self.ServerKeys = Key()
            self.ServerKeys.generate()

            # We can't encrypt this.. We'd need to store the key here on the machine...
            # If you're worried about it, encrypt the disk, or use a loopback.
            self.serversettings.settings['pubkey'] = self.ServerKeys.pubkey
            self.serversettings.settings['privkey'] = self.ServerKeys.privkey

            self.serversettings.updateconfig()
            self.serversettings.saveconfig()

        self.mc = OrderedDict
        self.unusedkeycache = multiprocessing.Queue(
            self.serversettings.settings['KeyGenerator']['num_pregens'])
        # Break out the settings into it's own file, so we can include it without including all of server
        # This does cause a few shenanigans while loading here, but hopefully
        # it's minimal

        self.ServerKeys = Key(pub=self.serversettings.settings['pubkey'],
                              priv=self.serversettings.settings['privkey'])

        self.db = DBWrapper(
            name=self.serversettings.settings['dbname'],
            dbtype=self.serversettings.settings['dbtype'],
            host=self.serversettings.settings['mongo-hostname'],
            port=self.serversettings.settings['mongo-port'])
        self.sessions = DBWrapper(
            name=self.serversettings.settings['sessions-db-name'],
            dbtype=self.serversettings.settings['dbtype'],
            host=self.serversettings.settings['sessions-db-hostname'],
            port=self.serversettings.settings['sessions-db-port'])
        self.binaries = DBWrapper(
            name=self.serversettings.settings['bin-mongo-db'],
            dbtype='mongo',
            host=self.serversettings.settings['bin-mongo-hostname'],
            port=self.serversettings.settings['bin-mongo-port'])
        self.bin_GridFS = GridFS(self.binaries.unsafe.mongo)

        # Ensure we have Proper indexes.
        self.db.safe.ensure_index('envelope', 'envelope.local.time_added')
        self.db.safe.ensure_index('envelope', 'envelope.local.sorttopic')
        self.db.safe.ensure_index('envelope', 'envelope.local.payload_sha512')
        self.db.safe.ensure_index('envelope', 'envelope.payload.class')
        self.db.safe.ensure_index('envelope', 'envelope.payload.regarding')
        self.db.safe.ensure_index(
            'envelope',
            'envelope.payload.binaries.sha_512')
        self.db.safe.ensure_index('envelope', 'envelope.local.payload_sha512')
        self.db.safe.ensure_index('envelope', 'envelope.payload.author.pubkey')
        self.db.safe.ensure_index('envelope', 'envelope.payload.author.pubkey')
        self.db.safe.ensure_index('envelope', 'usertrusts.asking')
        self.db.safe.ensure_index('envelope', 'incomingtrust')

        self.binaries.safe.ensure_index('fs.files', 'filename')
        self.binaries.safe.ensure_index('fs.files', 'uploadDate')
        self.binaries.safe.ensure_index('fs.files', '_id')
        self.binaries.safe.ensure_index('fs.files', 'uploadDate')

        # Get a list of all the valid templates that can be used, to compare
        # against later on.
        self.availablethemes = []
        for name in os.listdir('themes'):
            if os.path.isdir(os.path.join('themes', name)):
                if name[:1] != ".":
                    self.availablethemes.append(name)

        self.serversettings.settings['static-revision'] = int(time.time())

        self.fortune = TavernUtils.randomWords(fortunefile="data/fortunes")
        self.wordlist = TavernUtils.randomWords(fortunefile="data/wordlist")

        # Define out logging options.
        formatter = logging.Formatter('[%(levelname)s] %(message)s')
        self.consolehandler = logging.StreamHandler()
        self.consolehandler.setFormatter(formatter)
        self.handler_file = logging.FileHandler(
            filename=self.serversettings.settings['logfile'])
        self.handler_file.setFormatter(formatter)

        self.logger.setLevel(self.serversettings.settings['loglevel'])
        level = self.serversettings.settings['loglevel']

        # Cache our JS, so we can include it later.
        file = open("static/scripts/instance.min.js")
        self.logger.info("Cached JS")
        TavernCache.cache['instance.js'] = file.read()
        file.close()
        self.guestacct = None

    def start(self):
        """Stuff that should be done when the server is running as a process,
        not just imported as a obj."""
        self.external = embedis.embedis()
        from uasparser import UASparser
        self.logger.info("Loading Browser info")
        self.browserdetector = UASparser()

        # Start actually logging to file or console
        if self.debug:
            self.logger.setLevel("DEBUG")
            self.logger.addHandler(self.consolehandler)
      #      logging.getLogger('gnupg').setLevel("DEBUG")
            logging.getLogger('gnupg').addHandler(self.consolehandler)

        self.logger.addHandler(self.handler_file)

        print("Logging Server started at level: " +
              str(self.logger.getEffectiveLevel()))

        # Pregenerate some users in the background.
        self.keygenerator = KeyGenerator.KeyGenerator()
        self.keygenerator.start()

        if not 'guestacct' in self.serversettings.settings:
            self.logger.info("Generating a Guest user acct.")
            self.guestacct = User()
            self.guestacct.generate(AllowGuestKey=False)
            self.serversettings.settings['guestacct'] = {}
            self.serversettings.settings[
                'guestacct'][
                'pubkey'] = self.guestacct.Keys[
                'master'].pubkey
            self.serversettings.saveconfig()
            self.guestacct.savemongo()
        else:
            self.logger.info("Loading the Guest user acct.")
            self.guestacct = User()
            self.guestacct.load_mongo_by_pubkey(
                self.serversettings.settings['guestacct']['pubkey'])

    def stop(self):
        """Stop all server procs."""
        self.logger.info("Shutting down Server instance")
        self.keygenerator.stop()

    def prettytext(self):
        newstr = json.dumps(
            self.serversettings.settings, indent=2, separators=(', ', ': '))
        return newstr

    @memorise(ttl=defaultsettings.settings['cache']['sorttopic']['seconds'], maxsize=defaultsettings.settings['cache']['sorttopic']['size'])
    def sorttopic(self, topic):
        if topic is not None:
            topic = topic.lower()
            topic = self.urlize(topic)
        else:
            topic = None
        return topic

    @memorise(ttl=defaultsettings.settings['cache']['error_envelope']['seconds'], maxsize=defaultsettings.settings['cache']['error_envelope']['size'])
    def error_envelope(self, subject="Error", topic="sitecontent", body=None):

        if body is None:
            body = """
            Oh my, something seems to have happened that we weren't expecting.
            Hopefully this will get cleared up relatively quickly.
            If not, you might want to send a note to [email protected], with the URL, and notes on how you got here :/

            So sorry for the trouble.
            -The Barkeep
            """
        e = Envelope()
        e.dict['envelope']['payload'] = OrderedDict()
        e.dict['envelope']['payload']['subject'] = subject
        e.dict['envelope']['payload']['topic'] = topic
        e.dict['envelope']['payload']['formatting'] = "markdown"
        e.dict['envelope']['payload']['class'] = "message"
        e.dict['envelope']['payload'][
            'body'] = body
        e.dict['envelope']['payload']['author'] = OrderedDict()
        e.dict['envelope']['payload']['author']['pubkey'] = "1234"
        e.dict['envelope']['payload']['author']['friendlyname'] = "ERROR!"
        e.dict['envelope']['payload']['author']['useragent'] = "Error Agent"
        e.dict['envelope']['payload']['author']['friendlyname'] = "Error"
        e.addStamp(
            stampclass='author',
            keys=self.ServerKeys,
            friendlyname=defaultsettings.settings['hostname'])
        e.flatten()
        e.munge()
        e.dict['envelope']['local']['time_added'] = 1297396876
        e.dict['envelope']['local'][
            'author_wordhash'] = "Automatically generated message"
        e.dict['envelope']['local']['sorttopic'] = "error"
        e.dict['envelope']['local']['payload_sha512'] = e.payload.hash()
        return e

    # Cache to failfast on receiving dups
    @memorise(ttl=defaultsettings.settings['cache']['receiveEnvelope']['seconds'], maxsize=defaultsettings.settings['cache']['receiveEnvelope']['size'])
    def receiveEnvelope(self, envstr=None, env=None):
        """Receive an envelope for processing in the server.

        Can take either a string, or an envelope obj.

        """
        if envstr is None and env is None:
            raise Exception(
                'receiveEnvelope MUST receive an envelope. Really! ;)')

        if env is not None:
            # If we get an envelope, flatten it - The caller may not have.
            c = env.flatten()
        else:
            c = Envelope()
            c.loadstring(importstring=envstr)

        # Fill-out the message's local fields.
        c.munge()
        # Make sure the message is valid, meets our standards, and is good to
        # accept and save.
        if not c.validate():
            self.logger.info(
                "Received an Envelope which does not validate-  " + c.payload.hash())
            self.logger.debug(c.text())
            return False

        utctime = time.time()

        existing = self.db.unsafe.find_one(
            'envelopes', {'envelope.local.payload_sha512': c.dict['envelope']['local']['payload_sha512']})

        if existing is not None:
            self.logger.debug("We already have that msg.")
            return c.dict['envelope']['local']['payload_sha512']

        # Sign the message to saw we saw it.
        if self.serversettings.settings['mark-seen']:
            c.addStamp(
                stampclass='server',
                keys=self.ServerKeys,
                hostname=defaultsettings.settings['hostname'])

        # Store the time, in full UTC (with precision). This is used to skip
        # pages in the viewer later.
        c.dict['envelope']['local']['time_added'] = utctime

        if c.dict['envelope']['payload']['class'] == "message":

            # If the message referenes anyone, mark the original, for ease of finding it later.
            # Do this in the 'local' block, so we don't waste bits passing this on to others.
            # Partners can calculate this when they receive it.

            if 'regarding' in c.dict['envelope']['payload']:
                repliedTo = Envelope()
                if repliedTo.loadmongo(mongo_id=c.dict['envelope']['payload']['regarding']):
                    self.logger.debug(
                        " I am :: " + c.dict['envelope']['local']['payload_sha512'])
                    self.logger.debug(
                        " Adding a cite on my parent :: " +
                        repliedTo.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    repliedTo.addcite(
                        c.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    c.addAncestor(c.dict['envelope']['payload']['regarding'])

            print("id is :" + c.dict['envelope']['local']['payload_sha512'])

            # It could also be that this message is cited BY others we already have!
            # Sometimes we received them out of order. Better check.
            for citedict in self.db.unsafe.find('envelopes', {'envelope.payload.regarding': c.dict['envelope']['local']['payload_sha512']}):
                self.logger.debug('found existing cite, bad order. ')
                self.logger.debug(
                    " I am :: " + c.dict['envelope']['local']['payload_sha512'])
                self.logger.debug(" Found pre-existing cite at :: " +
                                  citedict['envelope']['local']['payload_sha512'])

                # If it's a message, write that in the reply, and in me.
                if citedict['envelope']['payload']['class'] == 'message':
                    citedme = Envelope()
                    citedme.loaddict(citedict)
                    c.addcite(
                        citedme.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    citedme.addAncestor(
                        c.dict[
                            'envelope'][
                            'local'][
                            'payload_sha512'])
                    citedme.saveMongo()

                # If it's an edit, write that in me.
                elif citedict['envelope']['payload']['class'] == 'messagerevision':
                    c.addEdit(citedict['envelope']['local']['payload_sha512'])

                elif citedict['envelope']['payload']['class'] == 'messagerating':
                    citedme = Envelope()
                    citedme.loaddict(citedict)
                    citedme.dict[
                        'envelope'][
                        'local'][
                        'regardingAuthor'] = c.dict[
                        'envelope'][
                        'payload'][
                        'author']
                    citedme.saveMongo()

        elif c.dict['envelope']['payload']['class'] == "messagerating":
            # If this is a rating, cache the AUTHOR of the rated message.
            regardingPost = self.db.unsafe.find_one(
                'envelopes',
                {'envelope.local.payload_sha512': c.dict['envelope']['payload']['regarding']})
            if regardingPost is not None:
                c.dict[
                    'envelope'][
                    'local'][
                    'regardingAuthor'] = regardingPost[
                    'envelope'][
                    'payload'][
                    'author']

        elif c.dict['envelope']['payload']['class'] == "messagerevision":
            # This is an edit to an existing message.

            regardingPost = self.db.unsafe.find_one(
                'envelopes',
                {'envelope.local.payload_sha512': c.dict['envelope']['payload']['regarding']})
            if regardingPost is not None:
                if 'priority' in c.dict['envelope']['payload']:
                    c.dict[
                        'envelope'][
                        'local'][
                        'priority'] = c.dict[
                        'envelope'][
                        'payload'][
                        'priority']
                else:
                    c.dict['envelope']['local']['priority'] = 0

                # Store this edit.
                # Save this message out to mongo, so we can then retrieve it in
                # addEdit().
                c.saveMongo()

                # Modify the original message.
                r = Envelope()
                r.loaddict(regardingPost)
                r.addEdit(c.dict['envelope']['local']['payload_sha512'])

                # Ensure we have the freshest version in memory.
                c.reloadmongo()
            else:
                self.logger.debug("Received an edit without the original")

        # Store our Envelope
        c.saveMongo()

        return c.dict['envelope']['local']['payload_sha512']

    @memorise(ttl=defaultsettings.settings['cache']['formatText']['seconds'], maxsize=defaultsettings.settings['cache']['formatText']['size'])
    def formatText(self, text=None, formatting='markdown'):

        # Run the text through Tornado's escape to ensure you're not a badguy.
        text = tornado.escape.xhtml_escape(text)
        if formatting == 'bbcode':
            formatted = bbcodepy.Parser().to_html(text)
        elif formatting == "plaintext":
            formatted = "<pre>" + text + "</pre>"
        else:
            # If we don't know, you get Markdown
            formatted = markdown.markdown(
                text,
                output_format="html5",
                safe_mode='escape',
                enable_attributes=False,
                extensions=['nl2br',
                            'footnotes',
                            'tables',
                            'headerid(level=3)'])
            # We can't use tornado.escape.linkify to linkify, since it ALSO
            # escapes everything.
            formatted = self.autolink(formatted)

        return formatted

    @memorise(ttl=defaultsettings.settings['cache']['getUsersPosts']['seconds'], maxsize=defaultsettings.settings['cache']['getUsersPosts']['size'])
    def getUsersPosts(self, pubkey, limit=1000):
        envelopes = []
        for envelope in self.db.safe.find('envelopes', {'envelope.local.author.pubkey': pubkey, 'envelope.payload.class': 'message'}, limit=limit, sortkey='envelope.local.time_added', sortdirection='descending'):
            messagetext = json.dumps(envelope, separators=(',', ':'))
            e = Envelope()
            e.loadstring(messagetext)
            envelopes.append(e)
        return envelopes

    def getOriginalMessage(self, messageid):

        env = Envelope()
        # First, pull the referenced message.
        if env.loadmongo(mongo_id=messageid):
            if env.dict['envelope']['payload']['class'] == 'message':
                return env.dict['envelope']['local']['payload_sha512']
            else:
                return env.dict['envelope']['payload']['regarding']

        return None

    def getTopMessage(self, messageid):
        # Find the top level of a post that we currently have.

        env = Envelope()
        # First, pull the referenced message.
        if env.loadmongo(mongo_id=messageid):
            # If we have no references, congrats, we're the top.
            if not 'regarding' in env.dict['envelope']['payload']:
                return env.dict['envelope']['local']['payload_sha512']
            if env.dict['envelope']['payload']['regarding'] is None:
                return env.dict['envelope']['local']['payload_sha512']
            # If we're here, it means we have a parent.
            # Recurse upstream
            result = self.getTopMessage(
                env.dict['envelope']['payload']['regarding'])

            # Don't blindly return it, since it might be None in broken chains.
            # In that case, return yourself.
            if result is not None:
                return result
            else:
                return env.dict['envelope']['local']['payload_sha512']
        else:
            return None

    def urlize(self, url):
        # I do NOT want to urlencode this, because that encodes the unicode characters.
        # Browsers are perfectly capable of handling these!
        url = re.sub('[/? ]', '-', url)
        url = re.sub(r'[^\w-]', '', url)
        return url

    # Autolink from http://greaterdebater.com/blog/gabe/post/4
    def autolink(self, html):
        # match all the urls
        # this returns a tuple with two groups
        # if the url is part of an existing link, the second element
        # in the tuple will be "> or </a>
        # if not, the second element will be an empty string
        urlre = re.compile(
            "(\(?https?://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|])(\">|</a>)?")
        urls = urlre.findall(html)
        clean_urls = []

        # remove the duplicate matches
        # and replace urls with a link
        for url in urls:
            # ignore urls that are part of a link already
            if url[1]:
                continue
            c_url = url[0]
            # ignore parens if they enclose the entire url
            if c_url[0] == '(' and c_url[-1] == ')':
                c_url = c_url[1:-1]

            if c_url in clean_urls:
                continue  # We've already linked this url

            clean_urls.append(c_url)
            # substitute only where the url is not already part of a
            # link element.
            html = re.sub("(?<!(=\"|\">))" + re.escape(c_url),
                          "<a rel=\"noreferrer nofollow\" href=\"" +
                          c_url + "\">" + c_url + "</a>",
                          html)
        return html
 def get_ssh_auth_key(self):
     if self.ssh_auth_key == None:
         print _("generating new key")
         new_key = Key.generate_rsa_key(4096)
         self.ssh_auth_key = new_key
     return self.ssh_auth_key
Пример #49
0
 def __init__(self, namespace, *args, **kwargs):
   '''Initializes NamespaceDatastore with `key` namespace.'''
   super(NamespaceDatastore, self).__init__(*args, **kwargs)
   self.keytransform = self.namespaceKey
   self.namespace = Key(namespace)
Пример #50
0
    def validate(self):
        """Ensures an envelope is valid, legal, and according to spec."""
        self.registerpayload()
        # Check headers
        if 'envelope' not in self.dict:
            self.server.logger.debug("Invalid Envelope. No Header")
            return False

        # Ensure we have 1 and only 1 author signature stamp
        stamps = self.dict['envelope']['stamps']
        foundauthor = 0
        for stamp in stamps:
            if stamp['class'] == "author":
                foundauthor += 1

        if foundauthor == 0:
            if self.dict['envelope']['payload']['class'] != 'privatemessage':
                self.server.logger.debug("No author stamp.")
                return False
        if foundauthor > 1:
            self.server.logger.debug("Too Many author stamps")
            return False

        # Ensure Every stamp validates.
        stamps = self.dict['envelope']['stamps']
        for stamp in stamps:

            if 'keyformat' not in stamp:
                self.server.logger.debug("Key format is not specififed.")
                return False

            if stamp['keyformat'] != 'gpg':
                self.server.logger.debug(
                    "Key not in acceptable container format.")
                return False

            # Retrieve the key, ensure it's valid.
            stampkey = Key(pub=stamp['pubkey'])
            if stampkey is None:
                self.server.logger.debug("Key is invalid.")
                return False

            if stampkey.keydetails['algorithm'] not in ['ElGamal', 'RSA', 'DSA']:
                self.server.logger.debug(
                    "Key does not use an acceptable algorithm.")
                return False

            if stampkey.keydetails['algorithm'] in ['ElGamal', 'RSA', 'DSA']:
                if int(stampkey.keydetails['length']) < 3072:
                    self.server.logger.debug("Key is too small.")
                    return False

            elif stampkey.keydetails['algorithm'] == 'ECDSA':
                if int(stampkey.keydetails['length']) < 233:
                    self.server.logger.debug("Key is too small.")
                    return False

            for uid in stampkey.keydetails['uids']:
                if uid not in [None, 'TAVERN', '']:
                    self.server.logger.debug(
                        "Key UID is potentially leaking information.")
                    return False

            # Ensure it matches the signature.
            if not stampkey.verify_string(stringtoverify=self.payload.text(), signature=stamp['signature']):
                self.server.logger.debug("Signature Failed to verify for stamp :: " +
                                         stamp['class'] + " :: " + stamp['pubkey'])
                return False

            # If they specify a proof-of-work in the stamp, make sure it's
            # valid.
            if 'proof-of-work' in stamp:
                    proof = stamp['proof-of-work']['proof']
                    difficulty = stamp['proof-of-work']['difficulty']
                    if stamp['proof-of-work']['class'] == 'sha256':
                        result = TavernUtils.checkWork(
                            self.payload.hash(),
                            proof,
                            difficulty)
                        if result is False:
                            self.server.logger.debug(
                                "Proof of work cannot be verified.")
                            return False
                    else:
                        self.server.logger.debug(
                            "Proof of work in unrecognized format. Ignoring.")

        # It's OK if they don't include a user-agent, but not if they include a
        # bad one.
        # if 'useragent' in self.dict['envelope']['payload']['author']:
        #     if not 'name' in self.dict['envelope']['payload']['author']['useragent']:
        #         self.server.logger.debug(
        #             "If you supply a user agent, it must have a valid name")
        #         return False
        #     if not isinstance(self.dict['envelope']['payload']['author']['useragent']['version'], int) and not isinstance(self.dict['envelope']['payload']['author']['useragent']['version'], float):
        #             self.server.logger.debug(
        #                 "Bad Useragent version must be a float or integer")
        #             return False

        # Do this last, so we don't waste time if the stamps are bad.
        if not self.payload.validate():
            self.server.logger.info("Payload does not validate.")
            return False

        return True