示例#1
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")
        self.adminBytes = credentials.UsernamePassword(b"admin", b"asdf")
        self.aliceBytes = credentials.UsernamePassword(b"alice", b"foo")
        self.badPassBytes = credentials.UsernamePassword(b"alice", b"foobar")
        self.badUserBytes = credentials.UsernamePassword(b"x", b"yz")
        self.checkerBytes = 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.patch(spwd, "getspnam", self._spwd_getspnam)
示例#2
0
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 = '******' + suffix
        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 = '******'
        password = '******'
        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)
示例#3
0
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 = '******' + suffix
        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 = '******'
        password = '******'
        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)
示例#4
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"))
示例#5
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'))
示例#6
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'))
示例#7
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')
示例#8
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')
示例#9
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(b"anybody", b"secret")),
         b"anybody")
示例#10
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 []
示例#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')
示例#12
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 []
示例#13
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
    def test_bootstrap(self, mock_getuid, mock_getgrnam, mock_chown):
        data_path = self.makeDir()
        log_dir = self.makeDir()
        fake_pwd = UserDatabase()
        fake_pwd.addUser("landscape", None, 1234, None, None, None, None)

        mock_getgrnam("root").gr_gid = 5678

        with mock.patch("landscape.lib.bootstrap.pwd", new=fake_pwd):
            bootstrap_list.bootstrap(data_path=data_path,
                                     log_dir=log_dir)

        def path(*suffix):
            return os.path.join(data_path, *suffix)

        paths = ["package",
                 "package/hash-id",
                 "package/binaries",
                 "package/upgrade-tool",
                 "messages",
                 "sockets",
                 "custom-graph-scripts",
                 log_dir,
                 "package/database"]
        calls = [mock.call(path(path_comps), 1234, 5678)
                 for path_comps in paths]
        mock_chown.assert_has_calls([mock.call(path(), 1234, 5678)] + calls)
        self.assertTrue(os.path.isdir(path()))
        self.assertTrue(os.path.isdir(path("package")))
        self.assertTrue(os.path.isdir(path("messages")))
        self.assertTrue(os.path.isdir(path("custom-graph-scripts")))
        self.assertTrue(os.path.isdir(log_dir))
        self.assertTrue(os.path.isfile(path("package/database")))

        def mode(*suffix):
            return stat.S_IMODE(os.stat(path(*suffix)).st_mode)

        self.assertEqual(mode(), 0o755)
        self.assertEqual(mode("messages"), 0o755)
        self.assertEqual(mode("package"), 0o755)
        self.assertEqual(mode("package/hash-id"), 0o755)
        self.assertEqual(mode("package/binaries"), 0o755)
        self.assertEqual(mode("sockets"), 0o750)
        self.assertEqual(mode("custom-graph-scripts"), 0o755)
        self.assertEqual(mode("package/database"), 0o644)
示例#15
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
示例#16
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
示例#17
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
示例#18
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
示例#19
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
示例#20
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
示例#21
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)
示例#22
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)
示例#23
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 = "******"
        self.assertLoggedIn(checker.requestAvatarId(cred), 'bob')
        self.assertEquals(mockos.seteuidCalls, [0, 2345])
        self.assertEquals(mockos.setegidCalls, [0, 1234])
示例#24
0
文件: test_checkers.py 项目: alex/ess
    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')
示例#25
0
    def setUp(self):
        mockos = MockOS()
        mockos.path = FilePath(self.mktemp())
        mockos.path.makedirs()

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

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

        self.expectedKeys = [b"key 1", b"key 2"]
class WatchDogRunTests(LandscapeTest):

    helpers = [EnvironSaverHelper]

    def setUp(self):
        super(WatchDogRunTests, self).setUp()
        self.fake_pwd = UserDatabase()

    @mock.patch("os.getuid", return_value=1000)
    def test_non_root(self, mock_getuid):
        """
        The watchdog should print an error message and exit if run by a normal
        user.
        """
        self.fake_pwd.addUser(
            "landscape", None, 1001, None, None, None, None)
        with mock.patch("landscape.client.watchdog.pwd", new=self.fake_pwd):
            sys_exit = self.assertRaises(SystemExit, run, ["landscape-client"])
        self.assertIn("landscape-client can only be run"
                      " as 'root' or 'landscape'.", str(sys_exit))

    def test_landscape_user(self):
        """
        The watchdog *can* be run as the 'landscape' user.
        """
        self.fake_pwd.addUser(
            "landscape", None, os.getuid(), None, None, None, None)
        reactor = FakeReactor()
        with mock.patch("landscape.client.watchdog.pwd", new=self.fake_pwd):
            run(["--log-dir", self.makeDir()], reactor=reactor)
        self.assertTrue(reactor.running)

    def test_no_landscape_user(self):
        """
        The watchdog should print an error message and exit if the
        'landscape' user doesn't exist.
        """
        with mock.patch("landscape.client.watchdog.pwd", new=self.fake_pwd):
            sys_exit = self.assertRaises(SystemExit, run, ["landscape-client"])
        self.assertIn("The 'landscape' user doesn't exist!", str(sys_exit))

    def test_clean_environment(self):
        self.fake_pwd.addUser(
            "landscape", None, os.getuid(), None, None, None, None)
        os.environ["DEBIAN_YO"] = "yo"
        os.environ["DEBCONF_YO"] = "yo"
        os.environ["LANDSCAPE_ATTACHMENTS"] = "some attachments"
        os.environ["MAIL"] = "/some/path"
        os.environ["UNRELATED"] = "unrelated"

        reactor = FakeReactor()
        with mock.patch("landscape.client.watchdog.pwd", new=self.fake_pwd):
            run(["--log-dir", self.makeDir()], reactor=reactor)
        self.assertNotIn("DEBIAN_YO", os.environ)
        self.assertNotIn("DEBCONF_YO", os.environ)
        self.assertNotIn("LANDSCAPE_ATTACHMENTS", os.environ)
        self.assertNotIn("MAIL", os.environ)
        self.assertEqual(os.environ["UNRELATED"], "unrelated")
示例#27
0
    def setUp(self):
        self.checker = checkers.SSHPublicKeyDatabase()
        self.key1 = encodebytes(b"foobar")
        self.key2 = encodebytes(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
示例#28
0
    def setUp(self):
        """
        Create a L{cftp.StdioClient} hooked up to dummy transport and a fake
        user database.
        """
        class Connection:
            pass

        conn = Connection()
        conn.transport = StringTransport()
        conn.transport.localClosed = False

        self.client = cftp.StdioClient(conn)
        self.database = self.client._pwd = UserDatabase()

        # Intentionally bypassing makeConnection - that triggers some code
        # which uses features not provided by our dumb Connection fake.
        self.client.transport = StringTransport()
示例#29
0
 def setUp(self):
     """
     Create a L{cftp.StdioClient} hooked up to dummy transport and a fake
     user database.
     """
     self.fakeFilesystem = FilesystemAccessExpectations()
     sftpClient = InMemorySFTPClient(self.fakeFilesystem )
     self.client = cftp.StdioClient(sftpClient)
     self.client.currentDirectory = '/'
     self.database = self.client._pwd = UserDatabase()
     # Use a fixed width for all tests so that we get the same results when
     # running these tests from different terminals.
     # Run tests in a wide console so that all items are delimited by at
     # least one space character.
     self.setKnownConsoleSize(500, 24)
     # Intentionally bypassing makeConnection - that triggers some code
     # which uses features not provided by our dumb Connection fake.
     self.client.transport = self.client.client.transport
示例#30
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))
示例#31
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(b"alice", b"")
        self.assertUnauthorizedLogin(checker.requestAvatarId(cred))

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

        cred = UsernamePassword(b"carol", b"*")
        self.assertUnauthorizedLogin(checker.requestAvatarId(cred))
示例#32
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))
示例#33
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 = "******"
        self.assertLoggedIn(checker.requestAvatarId(cred), 'bob')
        self.assertEquals(mockos.seteuidCalls, [0, 2345])
        self.assertEquals(mockos.setegidCalls, [0, 1234])
示例#34
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(util, "os", mockos)

        mockos.euid = 2345
        mockos.egid = 1234

        cred = UsernamePassword(b"alice", b"password")
        self.assertLoggedIn(checker.requestAvatarId(cred), b"alice")
        self.assertEqual(mockos.seteuidCalls, [])
        self.assertEqual(mockos.setegidCalls, [])
        cred.username = b"bob"
        self.assertLoggedIn(checker.requestAvatarId(cred), b"bob")
        self.assertEqual(mockos.seteuidCalls, [0, 2345])
        self.assertEqual(mockos.setegidCalls, [0, 1234])
示例#35
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)
示例#36
0
文件: test_checkers.py 项目: alex/ess
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')))
示例#37
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')))
示例#38
0
 def setUp(self):
     """
     Create a L{UserDatabase} with no user data in it.
     """
     self.database = UserDatabase()
     self._counter = SYSTEM_UID_MAX + 1
示例#39
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')))
 def setUp(self):
     super(WatchDogRunTests, self).setUp()
     self.fake_pwd = UserDatabase()
示例#41
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)
示例#42
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')))
示例#43
0
 def setUp(self):
     """
     Create a L{UserDatabase} with no user data in it.
     """
     self.database = UserDatabase()
     self._counter = SYSTEM_UID_MAX + 1