def remove_by_id(self, uid):
     """
         Remove an account by uid
         :param uid: (int) account uid
         :return:
     """
     secret_code = self.get_secret_code(uid)
     if secret_code:
         found = False
         (result, ids) = GK.list_item_ids_sync("TwoFactorAuth")
         for gid in ids:
             (result, item) = GK.item_get_info_sync("TwoFactorAuth", gid)
             if result == GK.Result.OK:
                 if item.get_display_name().strip("'") == secret_code:
                     found = True
                     break
         if found:
             GK.item_delete_sync("TwoFactorAuth", gid)
     query = "DELETE FROM accounts WHERE uid=?"
     try:
         self.conn.execute(query, (uid, ))
         self.conn.commit()
     except Exception as e:
         logging.error(
             "SQL: Couldn't remove account by uid : %s with error : %s" %
             (uid, str(e)))
 def remove_by_id(self, uid):
     """
         Remove an account by uid
         :param uid: (int) account uid
         :return:
     """
     secret_code = self.get_secret_code(uid)
     if secret_code:
         found = False
         (result, ids) = GK.list_item_ids_sync("TwoFactorAuth")
         for gid in ids:
             (result, item) = GK.item_get_info_sync("TwoFactorAuth", gid)
             if result == GK.Result.OK:
                 if item.get_display_name().strip("'") == secret_code:
                     found = True
                     break
         if found:
             GK.item_delete_sync("TwoFactorAuth", gid)
     query = "DELETE FROM accounts WHERE uid=?"
     try:
         self.conn.execute(query, (uid,))
         self.conn.commit()
     except Exception as e:
         logging.error(
             "SQL: Couldn't remove account by uid : %s with error : %s" % (uid, str(e)))
    def test_item_create_info(self):
        '''item_create_sync(),  item_get_info_sync(), list_item_ids_sync()'''

        self.assertEqual(GnomeKeyring.create_sync(TEST_KEYRING, TEST_PWD),
                         GnomeKeyring.Result.OK)
        self.assertEqual(
            GnomeKeyring.get_info_sync(TEST_KEYRING)[0],
            GnomeKeyring.Result.OK)

        attrs = GnomeKeyring.Attribute.list_new()
        GnomeKeyring.Attribute.list_append_string(attrs, 'context',
                                                  'testsuite')
        GnomeKeyring.Attribute.list_append_uint32(attrs, 'answer', 42)

        (result, id) = GnomeKeyring.item_create_sync(
            TEST_KEYRING, GnomeKeyring.ItemType.GENERIC_SECRET, 'my_password',
            attrs, 'my_secret', False)
        self.assertEqual(result, GnomeKeyring.Result.OK)

        # now query for it
        (result, info) = GnomeKeyring.item_get_info_sync(TEST_KEYRING, id)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(info.get_display_name(), 'my_password')
        self.assertEqual(info.get_secret(), 'my_secret')

        # list_item_ids_sync()
        (result, items) = GnomeKeyring.list_item_ids_sync(TEST_KEYRING)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(items, [id])
Beispiel #4
0
def get_master_key():
    ids = GnomeKeyring.list_item_ids_sync(KEYRING)[1]
    for id in ids:
        info = GnomeKeyring.item_get_info_sync('login', id)[1]
        if info.get_display_name() == 'gpwg:masterkey':
            return info.get_secret()
    return None
Beispiel #5
0
 def _get_first_key(self, keyring):
     item_keys = gk.list_item_ids_sync(keyring)
     if len(item_keys[1]) > 0:
         item_info = gk.item_get_info_sync(keyring, item_keys[1][0])
         return (item_info[1].get_display_name(), item_info[1].get_secret())
     else:
         return False
Beispiel #6
0
    def test_item_create_info(self):
        '''item_create_sync(),  item_get_info_sync(), list_item_ids_sync()'''

        self.assertEqual(GnomeKeyring.create_sync(TEST_KEYRING, TEST_PWD),
                GnomeKeyring.Result.OK)
        self.assertEqual(GnomeKeyring.get_info_sync(TEST_KEYRING)[0], GnomeKeyring.Result.OK)

        attrs = GnomeKeyring.Attribute.list_new()
        GnomeKeyring.Attribute.list_append_string(attrs, 'context', 'testsuite')
        GnomeKeyring.Attribute.list_append_uint32(attrs, 'answer', 42)

        (result, id) = GnomeKeyring.item_create_sync(TEST_KEYRING,
                GnomeKeyring.ItemType.GENERIC_SECRET, 'my_password', attrs,
                'my_secret', False)
        self.assertEqual(result, GnomeKeyring.Result.OK)

        # now query for it
        (result, info) = GnomeKeyring.item_get_info_sync(TEST_KEYRING, id)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(info.get_display_name(), 'my_password')
        self.assertEqual(info.get_secret(), 'my_secret')

        # list_item_ids_sync()
        (result, items) = GnomeKeyring.list_item_ids_sync(TEST_KEYRING)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(items, [id])
Beispiel #7
0
	def set(self, protocol, user, server, password):
		if password != '':
			displayNameDict = {}
			(result, ids) = GnomeKeyring.list_item_ids_sync(self._defaultKeyring)
			for identity in ids:
				(result, item) = GnomeKeyring.item_get_info_sync(self._defaultKeyring, identity)
				displayNameDict[item.get_display_name()] = identity

			attrs = GnomeKeyring.Attribute.list_new()
			GnomeKeyring.Attribute.list_append_string(attrs, 'application',	'Mailnag')
			GnomeKeyring.Attribute.list_append_string(attrs, 'protocol',	protocol)
			GnomeKeyring.Attribute.list_append_string(attrs, 'user',		user)
			GnomeKeyring.Attribute.list_append_string(attrs, 'server',		server)
			
			if self.KEYRING_ITEM_NAME % (protocol, user, server) in displayNameDict:
				(result, item) = GnomeKeyring.item_get_info_sync(self._defaultKeyring, \
					displayNameDict[self.KEYRING_ITEM_NAME % \
					(protocol, user, server)])
				
				if password != item.get_secret():
					GnomeKeyring.item_create_sync(self._defaultKeyring, \
						GnomeKeyring.ItemType.GENERIC_SECRET, \
						self.KEYRING_ITEM_NAME % (protocol, user, server), \
						attrs, password, True)
			else:
				GnomeKeyring.item_create_sync(self._defaultKeyring, \
					GnomeKeyring.ItemType.GENERIC_SECRET, \
					self.KEYRING_ITEM_NAME % (protocol, user, server), \
					attrs, password, True)
Beispiel #8
0
	def get(self, protocol, user, server):
		(result, ids) = GnomeKeyring.list_item_ids_sync(self._defaultKeyring)		
		if result == GnomeKeyring.Result.OK:
			displayNameDict = {}
			for identity in ids:
				(result, item) = GnomeKeyring.item_get_info_sync(self._defaultKeyring, identity)
				displayNameDict[item.get_display_name()] = identity

			if self.KEYRING_ITEM_NAME % (protocol, user, server) in displayNameDict:
				(result, item) = GnomeKeyring.item_get_info_sync(self._defaultKeyring, \
					displayNameDict[self.KEYRING_ITEM_NAME % \
					(protocol, user, server)])

				if item.get_secret() != '':
					return item.get_secret()
				else:
					# DEBUG print "Keyring.get(): No Keyring Password for %s://%s@%s." % (protocol, user, server)
					return ''

			else:
				# DEBUG print "Keyring.get(): %s://%s@%s not in Keyring." % (protocol, user, server)
				return ''

		else:
			# DEBUG print "Keyring.get(): Neither default- nor 'login'-Keyring available."
			return ''
Beispiel #9
0
def get_master_key():
    ids = GnomeKeyring.list_item_ids_sync(KEYRING)[1]
    for id in ids:
        info = GnomeKeyring.item_get_info_sync('login', id)[1]
        if info.get_display_name() == 'gpwg:masterkey':
            return info.get_secret()
    return None
Beispiel #10
0
 def _find(self, displayName, keyring):
     item_keys = gk.list_item_ids_sync(keyring)
     for k in item_keys[1]:
         item_info = gk.item_get_info_sync(keyring, k)
         if item_info.get_display_name() == displayName:
             return (k, item_info.get_display_name(), item_info.get_secret())
     return False
Beispiel #11
0
    def __init__(self):
        self.loginDetails = False
        if gk.is_available() is True:
            if "Gusic" in gk.list_keyring_names_sync()[1]:
                self.keyring = gk.list_item_ids_sync("Gusic")[1]

                self.loginDetails = self._get_first_key("Gusic")

            else:
                gk.create_sync("Gusic", "Gusic")
Beispiel #12
0
def set_secrets(krname, to_write, overwrite_all):
    item_ids = verify(gk.list_item_ids_sync(krname),
                      'list pre-existing items in keyring=%s' % krname)

    if overwrite_all:
        # Remove existing items from the keyring, leaving the container intact.
        for i in item_ids:
            verify(gk.item_delete_sync(krname, i),
                   'delete pre-existing item from keyring=%s' % krname)
        item_ids = []

    existing_items = {}
    for i in item_ids:
        item = verify(get_item(krname, i),
                      'access pre-existing item in keyring=%s' % krname)
        existing_items[item.get_display_name()] = i

    try:
        typ = gk.ItemType.GENERIC_SECRET
    except AttributeError:
        typ = gk.ITEM_GENERIC_SECRET

    # Write out new items.
    for i in to_write:
        needle = encode_label(i[DICT_ATTRIBUTES])
        secret = i[DICT_SECRET]
        label = pretty_print_label(needle)
        if needle in existing_items:
            # Matched an existing item; update it in-place.
            info = gk.ItemInfo()
            info.set_type(typ)
            info.set_display_name(needle)
            info.set_secret(secret)
            verify(gk.item_set_info_sync(krname, existing_items[needle], info),
                   'edit item (%s) in keyring=%s' % (label, krname))
        else:
            #
            # No existing item was present. Create a new one.
            #
            # XXX: We must pass update_if_exists=False because if we did not,
            # every item would collide with every other. In other words, we
            # would only be able to store a single item in the keyring, as we
            # are forced to use the same identifying attributes for every item
            # we create. This is because the only GLib.Array we can create is
            # the empty Array(). Awful.
            #
            item_id = verify(
                gk.item_create_sync(krname,
                                    typ,
                                    display_name=needle,
                                    attributes=Array(),
                                    secret=secret,
                                    update_if_exists=False),
                'create new item (%s) in keyring=%s' % (label, krname))
Beispiel #13
0
def get_gnome_keyrings():
    keyrings = {}
    for keyring_name in chk(GnomeKeyring.list_keyring_names_sync()):
        keyring_items = []
        keyrings[keyring_name] = keyring_items
        for id in chk(GnomeKeyring.list_item_ids_sync(keyring_name)):
            item = get_item(keyring_name, id)
            if item is not None:
                keyring_items.append(item)

    return keyrings
Beispiel #14
0
def import_keyrings(from_file):
    with open(from_file, "r") as f:
        keyrings = json.loads(f.read())

    for keyring_name, keyring_items in list(keyrings.items()):
        try:
            existing_ids = GnomeKeyring.list_item_ids_sync(keyring_name)
        except GnomeKeyring.NoSuchKeyringError:
            sys.stderr.write(
                "No keyring '%s' found. Please create this keyring first" %
                keyring_name)
            sys.exit(1)

        existing_items = [get_item(keyring_name, id) for id in existing_ids]
        existing_items = [i for i in existing_items if i is not None]

        for item in keyring_items:
            if any(items_roughly_equal(item, i) for i in existing_items):
                print("Skipping %s because it already exists" %
                      item['display_name'])
            else:
                nearly = [
                    i for i in existing_items
                    if items_roughly_equal(i, item, ignore_secret=True)
                ]
                if nearly:
                    print("Existing secrets found for '%s'" %
                          item['display_name'])
                    for i in nearly:
                        print(" " + i['secret'])

                    print("So skipping value from '%s':" % from_file)
                    print(" " + item['secret'])
                else:
                    schema = item['attributes']['xdg:schema']
                    item_type = None
                    if schema == 'org.freedesktop.Secret.Generic':
                        item_type = GnomeKeyring.ITEM_GENERIC_SECRET
                    elif schema == 'org.gnome.keyring.Note':
                        item_type = GnomeKeyring.ITEM_NOTE
                    elif schema == 'org.gnome.keyring.NetworkPassword':
                        item_type == GnomeKeyring.ITEM_NETWORK_PASSWORD

                    if item_type is not None:
                        item_id = GnomeKeyring.item_create_sync(
                            keyring_name, item_type, item['display_name'],
                            fix_attributes(item['attributes']), item['secret'],
                            False)
                        print("Copying secret %s" % item['display_name'])
                    else:
                        print(
                            "Can't handle secret '%s' of type '%s', skipping" %
                            (item['display_name'], schema))
Beispiel #15
0
	def __get_entry_id(self, entry):
		"""Get entry ID"""
		result = None

		for item_id in keyring.list_item_ids_sync(self.KEYRING_NAME)[1]:
			info = keyring.item_get_info_sync(self.KEYRING_NAME, item_id)[1]

			if info.get_display_name() == entry:
				result = item_id
				break

		return result
def import_keyrings(from_file):
    with open(from_file, "r") as f:
        keyrings = json.loads(f)

    for keyring_name, keyring_items in list(keyrings.items()):
        try:
            existing_ids = GnomeKeyring.list_item_ids_sync(keyring_name)
        except GnomeKeyring.NoSuchKeyringError:
            sys.stderr.write("No keyring '%s' found. Please create this keyring first" % keyring_name)
            sys.exit(1)

        existing_items = [get_item(keyring_name, id) for id in existing_ids]
        existing_items = [i for i in existing_items if i is not None]

        for item in keyring_items:
            if any(items_roughly_equal(item, i) for i in existing_items):
                print("Skipping %s because it already exists" % item['display_name'])
            else:
                nearly = [i for i in existing_items if items_roughly_equal(i, item, ignore_secret=True)]
                if nearly:
                    print("Existing secrets found for '%s'" % item['display_name'])
                    for i in nearly:
                        print(" " + i['secret'])

                    print("So skipping value from '%s':" % from_file)
                    print(" " + item['secret'])
                else:
                    schema = item['attributes']['xdg:schema']
                    item_type = None
                    if schema ==  'org.freedesktop.Secret.Generic':
                        item_type = GnomeKeyring.ITEM_GENERIC_SECRET
                    elif schema == 'org.gnome.keyring.Note':
                        item_type = GnomeKeyring.ITEM_NOTE
                    elif schema == 'org.gnome.keyring.NetworkPassword':
                        item_type == GnomeKeyring.ITEM_NETWORK_PASSWORD

                    if item_type is not None:
                        item_id = GnomeKeyring.item_create_sync(keyring_name,
                                                                item_type,
                                                                item['display_name'],
                                                                fix_attributes(item['attributes']),
                                                                item['secret'],
                                                                False)
                        print("Copying secret %s" % item['display_name'])
                    else:
                        print("Can't handle secret '%s' of type '%s', skipping" % (item['display_name'], schema))
Beispiel #17
0
	def get_entries(self):
		"""Return list of tuples containing entry names and description"""
		if not self.keyring_exists():
			raise InvalidKeyringError('Keyring does not exist!')

		result = []

		# if keyring is locked, try to unlock it
		if self.is_locked() and not self.__unlock_keyring():
			return result

		# populate result list
		for item_id in keyring.list_item_ids_sync(self.KEYRING_NAME)[1]:
			info = keyring.item_get_info_sync(self.KEYRING_NAME, item_id)[1]
			result.append((item_id, info.get_display_name(), info.get_mtime()))

		return result
Beispiel #18
0
def remove_secrets(krname, to_remove):
    item_ids = verify(gk.list_item_ids_sync(krname),
                      'list pre-existing items in keyring=%s' % krname)

    existing_items = {}
    for i in item_ids:
        item = verify(get_item(krname, i),
                      'access pre-existing item in keyring=%s' % krname)
        existing_items[item.get_display_name()] = i

    for i in to_remove:
        needle = encode_label(i[DICT_ATTRIBUTES])
        label = pretty_print_label(needle)
        if needle not in existing_items:
            err('Cannot find item (%s) in keyring=%s' % (label, krname))
        verify(gk.item_delete_sync(krname, existing_items[needle]),
               'remove item (%s) from keyring=%s' % (label, krname))
Beispiel #19
0
def get_secrets(krname):
    item_ids = verify(gk.list_item_ids_sync(krname),
                      'list items in keyring=%s' % krname)

    result = []
    for i in item_ids:
        # Get this item's label and secret.
        item = verify(get_item(krname, i),
                      'access item in keyring=%s' % krname)
        # Emit this item as a standard Python object.
        tmp = {
            DICT_LABEL: pretty_print_label(item.get_display_name()),
            DICT_SECRET: item.get_secret(),
            DICT_ATTRIBUTES: decode_label(item.get_display_name())
        }
        result.append(tmp)
    return result
Beispiel #20
0
	def remove(self, accounts):
		# create list of all valid accounts
		valid_accounts = []
		for acc in accounts:
			protocol = 'imap' if acc.imap else 'pop'
			valid_accounts.append(self.KEYRING_ITEM_NAME % \
			(protocol, acc.user, acc.server))

		# find and delete invalid entries
		(result, ids) = GnomeKeyring.list_item_ids_sync(self._defaultKeyring)
		if result == GnomeKeyring.Result.OK:
			displayNameDict = {}
			for identity in ids:
				(result, item) = GnomeKeyring.item_get_info_sync(self._defaultKeyring, identity)
				displayNameDict[item.get_display_name()] = identity
			for key in displayNameDict.keys():
				if key.startswith('Mailnag password for') \
				and key not in valid_accounts:
					GnomeKeyring.item_delete_sync(self._defaultKeyring, displayNameDict[key])
 def dump(self, print_passwords=False):
     """Get all keyring entries (with or without passwords)
     """
     from gi.repository import GnomeKeyring
     dump = ""
     (result, ids) = GnomeKeyring.list_item_ids_sync(self.KEYRING_NAME)
     for id in ids:	
         (result, item) = GnomeKeyring.item_get_info_sync(self.KEYRING_NAME, id)
         if result == GnomeKeyring.Result.IO_ERROR:
             return None
         if result == GnomeKeyring.Result.NO_MATCH:
             return None
         if result == GnomeKeyring.Result.CANCELLED:
             # The user pressed "Cancel" when prompted to unlock their keyring.
             return None
         dump += item.get_display_name()
         if print_passwords:
             dump += " = " + item.get_secret()
         dump += "\n"
     return dump
def main(args):
    cache_file = os.path.join(BaseDirectory.save_cache_path('password_reset'),
                              'old-passwords.gpg')
    old_password = getpass.getpass("Enter the password we are looking for: ")
    new_password = getpass.getpass("Enter the new password: "******"Failed to fetch keyrings")

        return 1

    update_count = 0

    for keyring in keyrings:
        result, items = GnomeKeyring.list_item_ids_sync(keyring)

        # Read contents of the keyring
        if result != GnomeKeyring.Result.OK:
            print("Failed to fetch keyring items from {}".format(keyring))

            continue

        # Iterate over all keys
        for itemid in items:
            result, info = GnomeKeyring.item_get_info_full_sync(
                keyring,
                itemid,
                GnomeKeyring.ItemInfoFlags.SECRET)

            if result != GnomeKeyring.Result.OK:
                print("Failed to get item {} from keyring {}".format(
                    itemid,
                    keyring))

                continue

            if check_password(info, passwords, new_password=new_password):
                result = GnomeKeyring.item_set_info_sync(keyring, itemid, info)

                if result != GnomeKeyring.Result.OK:
                    print("Failed to save item {} in keyring {}".format(
                        info.get_display_name(), keyring))
                else:
                    update_count += 1

    print("Updated {} keys".format(update_count))
Beispiel #23
0
import sys
from gi.repository import GnomeKeyring as gk

if len(sys.argv) < 3:
    print >> sys.stderr, "invalid arguments\n    python gnomekeyring.py keyring itemname"
    exit(1)

ringname = sys.argv[1]
keyname = sys.argv[2]

(result, keyrings) = gk.list_keyring_names_sync()
if not ringname in keyrings:
    print >> sys.stderr, "keyring '%s' not found" % ringname
    exit(2)


result = gk.unlock_sync(ringname, None)
if not result == gk.Result.OK:
    print >> sys.stderr, "keyring '%s' is locked" % ringname
    exit(3)

(result, ids) = gk.list_item_ids_sync(ringname)
for id in ids:
    (result, info) = gk.item_get_info_sync(ringname, id)
    if info.get_display_name() == keyname:
        print info.get_secret()
        exit(0)

print >> sys.stderr, "keyname '%s' in '%s' not found" % (keyname, ringname)
exit(4)