Exemplo n.º 1
0
    def add_authorizedkey(self, key, comment=None):
        """
        Add the given key to the user. Adding the key to his `authorized_keys`
        file if it exists and adding it to database.
        """
        # Parse and validate ssh key
        assert key
        key = authorizedkeys.check_publickey(key)
        if not key:
            raise ValueError(_("Invalid SSH key."))
        # Remove option, replace comments.
        key = authorizedkeys.AuthorizedKey(options=None,
                                           keytype=key.keytype,
                                           key=key.key,
                                           comment=comment or key.comment)

        # If a filename exists, use it by default.
        filename = os.path.join(self.user_root, '.ssh', 'authorized_keys')
        if os.path.isfile(filename):
            with open(filename, mode="r+", encoding='utf-8') as fh:
                if authorizedkeys.exists(fh, key):
                    raise ValueError(_("SSH key already exists"))
                logger.info("add key [%s] to [%s] authorized_keys", key,
                            self.username)
                authorizedkeys.add(fh, key)
        else:
            # Also look in database.
            logger.info("add key [%s] to [%s] database", key, self.username)
            self._db.add_authorizedkey(self._username,
                                       fingerprint=key.fingerprint,
                                       key=key.getvalue())
        self._userdb._notify('user_attr_changed', self,
                             {'authorizedkeys': True})
Exemplo n.º 2
0
    def get_authorizedkeys(self):
        """
        Return an iterator on the authorized key. Either from his
        `authorized_keys` file if it exists or from database.
        """
        # If a filename exists, use it by default.
        filename = os.path.join(self.user_root, '.ssh', 'authorized_keys')
        if os.path.isfile(filename):
            for k in authorizedkeys.read(filename):
                yield k

        # Also look in database.
        for record in self._db.find('sshkeys', userid=self._userid):
            yield authorizedkeys.check_publickey(record['key'])