class UserDatabaseTests(TestCase, UserDatabaseTestsMixin):
    """
    Tests for L{UserDatabase}.
    """
    def setUp(self):
        """
        Create a L{UserDatabase} with no user data in it.
        """
        self.database = UserDatabase()
        self._counter = SYSTEM_UID_MAX + 1


    def getExistingUserInfo(self):
        """
        Add a new user to C{self.database} and return its information.
        """
        self._counter += 1
        suffix = '_' + str(self._counter)
        username = 'username' + suffix
        password = 'password' + suffix
        uid = self._counter
        gid = self._counter + 1000
        gecos = 'gecos' + suffix
        dir = 'dir' + suffix
        shell = 'shell' + suffix

        self.database.addUser(username, password, uid, gid, gecos, dir, shell)
        return (username, password, uid, gid, gecos, dir, shell)


    def test_addUser(self):
        """
        L{UserDatabase.addUser} accepts seven arguments, one for each field of
        a L{pwd.struct_passwd}, and makes the new record available via
        L{UserDatabase.getpwuid}, L{UserDatabase.getpwnam}, and
        L{UserDatabase.getpwall}.
        """
        username = 'alice'
        password = 'secr3t'
        uid = 123
        gid = 456
        gecos = 'Alice,,,'
        home = '/users/alice'
        shell = '/usr/bin/foosh'

        db = self.database
        db.addUser(username, password, uid, gid, gecos, home, shell)

        for [entry] in [[db.getpwuid(uid)], [db.getpwnam(username)],
                        db.getpwall()]:
            self.assertEqual(entry.pw_name, username)
            self.assertEqual(entry.pw_passwd, password)
            self.assertEqual(entry.pw_uid, uid)
            self.assertEqual(entry.pw_gid, gid)
            self.assertEqual(entry.pw_gecos, gecos)
            self.assertEqual(entry.pw_dir, home)
            self.assertEqual(entry.pw_shell, shell)
Example #2
0
 def test_pwdGetByName(self):
     """
     L{_pwdGetByName} returns a tuple of items from the UNIX /etc/passwd
     database if the L{pwd} module is present.
     """
     userdb = UserDatabase()
     userdb.addUser(
         'alice', 'secrit', 1, 2, 'first last', '/foo', '/bin/sh')
     self.patch(checkers, 'pwd', userdb)
     self.assertEqual(
         checkers._pwdGetByName('alice'), userdb.getpwnam('alice'))
Example #3
0
 def test_passInCheckers(self):
     """
     L{UNIXPasswordDatabase} takes a list of functions to check for UNIX
     user information.
     """
     password = crypt.crypt('secret', 'secret')
     userdb = UserDatabase()
     userdb.addUser('anybody', password, 1, 2, 'foo', '/bar', '/bin/sh')
     checker = checkers.UNIXPasswordDatabase([userdb.getpwnam])
     self.assertLoggedIn(
         checker.requestAvatarId(UsernamePassword('anybody', 'secret')),
         'anybody')
Example #4
0
class MemorySSHPublicKeyDatabase(SSHPublicKeyDatabase):
    def __init__(self, users):
        self._users = users
        self._userdb = UserDatabase()
        for i, username in enumerate(self._users):
            self._userdb.addUser(
                username, b"garbage", 123 + i, 456, None, None, None)


    def getAuthorizedKeysFiles(self, credentials):
        try:
            return self._users[credentials.username]
        except KeyError:
            return []
Example #5
0
    def setUp(self):
        self.checker = checkers.SSHPublicKeyDatabase()
        self.key1 = base64.encodestring("foobar")
        self.key2 = base64.encodestring("eggspam")
        self.content = "t1 %s foo\nt2 %s egg\n" % (self.key1, self.key2)

        self.mockos = MockOS()
        self.mockos.path = FilePath(self.mktemp())
        self.mockos.path.makedirs()
        self.patch(util, 'os', self.mockos)
        self.sshDir = self.mockos.path.child('.ssh')
        self.sshDir.makedirs()

        userdb = UserDatabase()
        userdb.addUser(
            'user', 'password', 1, 2, 'first last',
            self.mockos.path.path, '/bin/shell')
        self.checker._userdb = userdb
Example #6
0
    def setUp(self):
        self.checker = checkers.SSHPublicKeyDatabase()
        self.key1 = _b64encodebytes(b"foobar")
        self.key2 = _b64encodebytes(b"eggspam")
        self.content = (b"t1 " + self.key1 + b" foo\nt2 " + self.key2 +
                        b" egg\n")

        self.mockos = MockOS()
        self.mockos.path = FilePath(self.mktemp())
        self.mockos.path.makedirs()
        self.patch(util, 'os', self.mockos)
        self.sshDir = self.mockos.path.child('.ssh')
        self.sshDir.makedirs()

        userdb = UserDatabase()
        userdb.addUser(
            b'user', b'password', 1, 2, b'first last',
            self.mockos.path.path, b'/bin/shell')
        self.checker._userdb = userdb
Example #7
0
    def setUp(self):
        self.admin = credentials.UsernamePassword('admin', 'asdf')
        self.alice = credentials.UsernamePassword('alice', 'foo')
        self.badPass = credentials.UsernamePassword('alice', 'foobar')
        self.badUser = credentials.UsernamePassword('x', 'yz')
        self.checker = strcred.makeChecker('unix')

        # Hack around the pwd and spwd modules, since we can't really
        # go about reading your /etc/passwd or /etc/shadow files
        if pwd:
            database = UserDatabase()
            for username, password in self.users.items():
                database.addUser(
                    username, crypt.crypt(password, 'F/'),
                    1000, 1000, username, '/home/' + username, '/bin/sh')
            self.patch(pwd, 'getpwnam', database.getpwnam)
        if spwd:
            self._spwd_getspnam = spwd.getspnam
            spwd.getspnam = self._spwd
Example #8
0
    def setUp(self):
        self.admin = credentials.UsernamePassword("admin", "asdf")
        self.alice = credentials.UsernamePassword("alice", "foo")
        self.badPass = credentials.UsernamePassword("alice", "foobar")
        self.badUser = credentials.UsernamePassword("x", "yz")
        self.checker = strcred.makeChecker("unix")

        # Hack around the pwd and spwd modules, since we can't really
        # go about reading your /etc/passwd or /etc/shadow files
        if pwd:
            database = UserDatabase()
            for username, password in self.users.items():
                database.addUser(
                    username, crypt.crypt(password, "F/"), 1000, 1000, username, "/home/" + username, "/bin/sh"
                )
            self.patch(pwd, "getpwnam", database.getpwnam)
        if spwd:
            self._spwd_getspnam = spwd.getspnam
            spwd.getspnam = self._spwd
Example #9
0
def patchUserDatabase(patch, user, uid, group, gid):
    """
    Patch L{pwd.getpwnam} so that it behaves as though only one user exists
    and patch L{grp.getgrnam} so that it behaves as though only one group
    exists.

    @param patch: A function like L{TestCase.patch} which will be used to
        install the fake implementations.

    @type user: C{str}
    @param user: The name of the single user which will exist.

    @type uid: C{int}
    @param uid: The UID of the single user which will exist.

    @type group: C{str}
    @param group: The name of the single user which will exist.

    @type gid: C{int}
    @param gid: The GID of the single group which will exist.
    """
    # Try not to be an unverified fake, but try not to depend on quirks of
    # the system either (eg, run as a process with a uid and gid which
    # equal each other, and so doesn't reliably test that uid is used where
    # uid should be used and gid is used where gid should be used). -exarkun
    pwent = pwd.getpwuid(os.getuid())
    grent = grp.getgrgid(os.getgid())

    database = UserDatabase()
    database.addUser(
        user, pwent.pw_passwd, uid, pwent.pw_gid,
        pwent.pw_gecos, pwent.pw_dir, pwent.pw_shell)

    def getgrnam(name):
        result = list(grent)
        result[result.index(grent.gr_name)] = group
        result[result.index(grent.gr_gid)] = gid
        result = tuple(result)
        return {group: result}[name]

    patch(pwd, "getpwnam", database.getpwnam)
    patch(grp, "getgrnam", getgrnam)
Example #10
0
    def test_defaultCheckers(self):
        """
        L{UNIXPasswordDatabase} with no arguments has checks the C{pwd} database
        and then the C{spwd} database.
        """
        checker = checkers.UNIXPasswordDatabase()

        def crypted(username, password):
            salt = crypt.crypt(password, username)
            crypted = crypt.crypt(password, '$1$' + salt)
            return crypted

        pwd = UserDatabase()
        pwd.addUser('alice', crypted('alice', 'password'),
                    1, 2, 'foo', '/foo', '/bin/sh')
        # x and * are convention for "look elsewhere for the password"
        pwd.addUser('bob', 'x', 1, 2, 'bar', '/bar', '/bin/sh')
        spwd = ShadowDatabase()
        spwd.addUser('alice', 'wrong', 1, 2, 3, 4, 5, 6, 7)
        spwd.addUser('bob', crypted('bob', 'password'),
                     8, 9, 10, 11, 12, 13, 14)

        self.patch(checkers, 'pwd', pwd)
        self.patch(checkers, 'spwd', spwd)

        mockos = MockOS()
        self.patch(checkers, 'os', mockos)
        self.patch(util, 'os', mockos)

        mockos.euid = 2345
        mockos.egid = 1234

        cred = UsernamePassword("alice", "password")
        self.assertLoggedIn(checker.requestAvatarId(cred), 'alice')
        self.assertEquals(mockos.seteuidCalls, [])
        self.assertEquals(mockos.setegidCalls, [])
        cred.username = "bob"
        self.assertLoggedIn(checker.requestAvatarId(cred), 'bob')
        self.assertEquals(mockos.seteuidCalls, [0, 2345])
        self.assertEquals(mockos.setegidCalls, [0, 1234])
Example #11
0
    def setUp(self):
        mockos = MockOS()
        mockos.path = FilePath(self.mktemp())
        mockos.path.makedirs()

        self.userdb = UserDatabase()
        self.userdb.addUser('alice', 'password', 1, 2, 'alice lastname',
                            mockos.path.path, '/bin/shell')

        self.sshDir = mockos.path.child('.ssh')
        self.sshDir.makedirs()
        authorized_keys = self.sshDir.child('authorized_keys')
        authorized_keys.setContent('key 1\nkey 2')
Example #12
0
    def test_failOnSpecial(self):
        """
        If the password returned by any function is C{""}, C{"x"}, or C{"*"} it
        is not compared against the supplied password.  Instead it is skipped.
        """
        pwd = UserDatabase()
        pwd.addUser('alice', '', 1, 2, '', 'foo', 'bar')
        pwd.addUser('bob', 'x', 1, 2, '', 'foo', 'bar')
        pwd.addUser('carol', '*', 1, 2, '', 'foo', 'bar')
        self.patch(checkers, 'pwd', pwd)

        checker = checkers.UNIXPasswordDatabase([checkers._pwdGetByName])
        cred = UsernamePassword('alice', '')
        self.assertUnauthorizedLogin(checker.requestAvatarId(cred))

        cred = UsernamePassword('bob', 'x')
        self.assertUnauthorizedLogin(checker.requestAvatarId(cred))

        cred = UsernamePassword('carol', '*')
        self.assertUnauthorizedLogin(checker.requestAvatarId(cred))
Example #13
0
 def __init__(self, users):
     self._users = users
     self._userdb = UserDatabase()
     for i, username in enumerate(self._users):
         self._userdb.addUser(
             username, b"garbage", 123 + i, 456, None, None, None)
Example #14
0
class UNIXAuthorizedKeysFilesTests(TestCase):
    """
    Tests for L{checkers.UNIXAuthorizedKeysFiles}.
    """
    skip = dependencySkip


    def setUp(self):
        mockos = MockOS()
        mockos.path = FilePath(self.mktemp())
        mockos.path.makedirs()

        self.userdb = UserDatabase()
        self.userdb.addUser('alice', 'password', 1, 2, 'alice lastname',
                            mockos.path.path, '/bin/shell')

        self.sshDir = mockos.path.child('.ssh')
        self.sshDir.makedirs()
        authorizedKeys = self.sshDir.child('authorized_keys')
        authorizedKeys.setContent('key 1\nkey 2')

        self.expectedKeys = ['key 1', 'key 2']


    def test_implementsInterface(self):
        """
        L{checkers.UNIXAuthorizedKeysFiles} implements
        L{checkers.IAuthorizedKeysDB}.
        """
        keydb = checkers.UNIXAuthorizedKeysFiles(self.userdb)
        verifyObject(checkers.IAuthorizedKeysDB, keydb)


    def test_noKeysForUnauthorizedUser(self):
        """
        If the user is not in the user database provided to
        L{checkers.UNIXAuthorizedKeysFiles}, an empty iterator is returned
        by L{checkers.UNIXAuthorizedKeysFiles.getAuthorizedKeys}.
        """
        keydb = checkers.UNIXAuthorizedKeysFiles(self.userdb,
                                                 parseKey=lambda x: x)
        self.assertEqual([], list(keydb.getAuthorizedKeys('bob')))


    def test_allKeysInAllAuthorizedFilesForAuthorizedUser(self):
        """
        If the user is in the user database provided to
        L{checkers.UNIXAuthorizedKeysFiles}, an iterator with all the keys in
        C{~/.ssh/authorized_keys} and C{~/.ssh/authorized_keys2} is returned
        by L{checkers.UNIXAuthorizedKeysFiles.getAuthorizedKeys}.
        """
        self.sshDir.child('authorized_keys2').setContent('key 3')
        keydb = checkers.UNIXAuthorizedKeysFiles(self.userdb,
                                                 parseKey=lambda x: x)
        self.assertEqual(self.expectedKeys + ['key 3'],
                         list(keydb.getAuthorizedKeys('alice')))


    def test_ignoresNonexistantFile(self):
        """
        L{checkers.UNIXAuthorizedKeysFiles.getAuthorizedKeys} returns only
        the keys in C{~/.ssh/authorized_keys} and C{~/.ssh/authorized_keys2}
        if they exist.
        """
        keydb = checkers.UNIXAuthorizedKeysFiles(self.userdb,
                                                 parseKey=lambda x: x)
        self.assertEqual(self.expectedKeys,
                         list(keydb.getAuthorizedKeys('alice')))


    def test_ignoresUnreadableFile(self):
        """
        L{checkers.UNIXAuthorizedKeysFiles.getAuthorizedKeys} returns only
        the keys in C{~/.ssh/authorized_keys} and C{~/.ssh/authorized_keys2}
        if they are readable.
        """
        self.sshDir.child('authorized_keys2').makedirs()
        keydb = checkers.UNIXAuthorizedKeysFiles(self.userdb,
                                                 parseKey=lambda x: x)
        self.assertEqual(self.expectedKeys,
                         list(keydb.getAuthorizedKeys('alice')))
Example #15
0
 def setUp(self):
     """
     Create a L{UserDatabase} with no user data in it.
     """
     self.database = UserDatabase()
     self._counter = SYSTEM_UID_MAX + 1
Example #16
0
class UNIXAuthorizedKeysFilesTestCase(TestCase):
    """
    Tests for L{UNIXAuthorizedKeysFiles}
    """
    def setUp(self):
        mockos = MockOS()
        mockos.path = FilePath(self.mktemp())
        mockos.path.makedirs()

        self.userdb = UserDatabase()
        self.userdb.addUser('alice', 'password', 1, 2, 'alice lastname',
                            mockos.path.path, '/bin/shell')

        self.sshDir = mockos.path.child('.ssh')
        self.sshDir.makedirs()
        authorized_keys = self.sshDir.child('authorized_keys')
        authorized_keys.setContent('key 1\nkey 2')

    def test_implements_interface(self):
        """
        L{AuthorizedKeysFilesMapping} implements L{IAuthorizedKeysDB}
        """
        keydb = UNIXAuthorizedKeysFiles(self.userdb)
        verifyObject(IAuthorizedKeysDB, keydb)

    def test_no_keys_for_unauthorized_user(self):
        """
        If the user is not in the user database provided to
        L{UNIXAuthorizedKeysFiles}, an empty iterator is returned
        by L{UNIXAuthorizedKeysFiles.getAuthorizedKeys}
        """
        keydb = UNIXAuthorizedKeysFiles(self.userdb, parsekey=lambda x: x)
        self.assertEqual([], list(keydb.getAuthorizedKeys('bob')))

    def test_all_keys_in_all_authorized_files_for_authorized_user(self):
        """
        If the user is in the user database provided to
        L{UNIXAuthorizedKeysFiles}, an iterator with all the keys in
        C{~/.ssh/authorized_keys} and C{~/.ssh/authorized_keys2} is returned
        by L{UNIXAuthorizedKeysFiles.getAuthorizedKeys}
        """
        self.sshDir.child('authorized_keys2').setContent('key 3')
        keydb = UNIXAuthorizedKeysFiles(self.userdb, parsekey=lambda x: x)
        self.assertEqual(['key 1', 'key 2', 'key 3'],
                         list(keydb.getAuthorizedKeys('alice')))

    def test_ignores_nonexistant_file(self):
        """
        L{AuthorizedKeysFilesMapping.getAuthorizedKeys} returns only the
        keys in C{~/.ssh/authorized_keys} and C{~/.ssh/authorized_keys2} if
        they exist
        """
        keydb = UNIXAuthorizedKeysFiles(self.userdb, parsekey=lambda x: x)
        self.assertEqual(['key 1', 'key 2'],
                         list(keydb.getAuthorizedKeys('alice')))

    def test_ignores_unreadable_file(self):
        """
        L{AuthorizedKeysFilesMapping.getAuthorizedKeys} returns only the
        keys in C{~/.ssh/authorized_keys} and C{~/.ssh/authorized_keys2} if
        they are readable
        """
        self.sshDir.child('authorized_keys2').makedirs()
        keydb = UNIXAuthorizedKeysFiles(self.userdb, parsekey=lambda x: x,
                                        runas=None)
        self.assertEqual(['key 1', 'key 2'],
                         list(keydb.getAuthorizedKeys('alice')))

    def test_opens_unreadable_file_as_user_given_runas(self):
        """
        L{AuthorizedKeysFilesMapping.getAuthorizedKeys}, if unable to read
        an C{authorized_keys} file, will attempt to open it as the user
        """
        self.sshDir.child('authorized_keys2').makedirs()

        def runas(uid, gid, callable):
            self.assertEqual((1, 2), (uid, gid))
            return StringIO('key 3')

        keydb = UNIXAuthorizedKeysFiles(self.userdb, parsekey=lambda x: x,
                                        runas=runas)
        self.assertEqual(['key 1', 'key 2', 'key 3'],
                         list(keydb.getAuthorizedKeys('alice')))