示例#1
0
    def testIndexCreation(self):
        cache = files.FilesPasswdMapHandler(self.config)
        entries = [
            passwd.PasswdMapEntry(dict(name='foo', uid=10, gid=10)),
            passwd.PasswdMapEntry(dict(name='bar', uid=11, gid=11)),
            passwd.PasswdMapEntry(dict(name='quux', uid=12, gid=11)),
        ]
        pmap = passwd.PasswdMap(entries)
        cache.Write(pmap)
        cache.WriteIndex()

        index_filename = cache.GetCacheFilename() + '.ixname'
        self.assertTrue(os.path.exists(index_filename),
                        'Index not created %s' % index_filename)
        with open(index_filename) as f:
            self.assertEqual('bar\x0015\x00\x00\n', f.readline())
            self.assertEqual('foo\x000\x00\x00\x00\n', f.readline())
            self.assertEqual('quux\x0030\x00\n', f.readline())

        index_filename = cache.GetCacheFilename() + '.ixuid'
        self.assertTrue(os.path.exists(index_filename),
                        'Index not created %s' % index_filename)
        with open(index_filename) as f:
            self.assertEqual('10\x000\x00\x00\n', f.readline())
            self.assertEqual('11\x0015\x00\n', f.readline())
            self.assertEqual('12\x0030\x00\n', f.readline())
示例#2
0
    def testEq(self):
        """Verify we are doing a deep compare in __eq__."""

        # Setup some things to compare
        entry_good = passwd.PasswdMapEntry({
            'name': 'foo',
            'uid': 10,
            'gid': 10
        })
        entry_same_as_good = passwd.PasswdMapEntry({
            'name': 'foo',
            'uid': 10,
            'gid': 10
        })
        entry_like_good = passwd.PasswdMapEntry()
        entry_like_good.name = 'foo'  # same Key(), but rest of attributes differ
        entry_bad = passwd.PasswdMapEntry()
        entry_bad.name = 'bar'

        self.assertEquals(entry_good,
                          entry_good,
                          msg='entry_good not equal to itself')
        self.assertEquals(entry_good,
                          entry_same_as_good,
                          msg='__eq__ not doing deep compare')
        self.assertNotEqual(entry_good,
                            entry_like_good,
                            msg='__eq__ not doing deep compare')
        self.assertNotEqual(entry_good, entry_bad, msg='unexpected equality')
示例#3
0
    def testIncrementalUpdate(self):
        """An incremental update reads a partial map and merges it."""

        # Unlike in a full update, we create a cache map and a source map, and
        # let it merge them.  If it goes to write the merged map, we're good.
        # Also check that timestamps were updated, as in testFullUpdate above.

        def compare_function(map_object):
            return len(map_object) == 2

        original_modify_stamp = 1
        new_modify_stamp = 2
        updater = map_updater.MapUpdater(config.MAP_PASSWORD,
                                         self.workdir, {},
                                         can_do_incremental=True)
        updater.WriteModifyTimestamp(original_modify_stamp)

        cache_map_entry = passwd.PasswdMapEntry({
            'name': 'bar',
            'uid': 20,
            'gid': 20
        })
        cache_map = passwd.PasswdMap([cache_map_entry])
        cache_map.SetModifyTimestamp(original_modify_stamp)

        cache_mock = self.mox.CreateMock(caches.Cache)
        cache_mock.GetMap().AndReturn(cache_map)
        cache_mock.WriteMap(map_data=mox.Func(compare_function)).AndReturn(0)

        source_map_entry = passwd.PasswdMapEntry({
            'name': 'foo',
            'uid': 10,
            'gid': 10
        })
        source_map = passwd.PasswdMap([source_map_entry])
        source_map.SetModifyTimestamp(new_modify_stamp)

        source_mock = self.mox.CreateMock(source.Source)
        source_mock.GetMap(config.MAP_PASSWORD,
                           location=None,
                           since=original_modify_stamp).AndReturn(source_map)

        self.mox.ReplayAll()

        self.assertEqual(
            0,
            updater.UpdateCacheFromSource(cache_mock,
                                          source_mock,
                                          incremental=True,
                                          force_write=False,
                                          location=None))
        self.assertEqual(updater.GetModifyTimestamp(), new_modify_stamp)
        self.assertNotEqual(updater.GetUpdateTimestamp(), None)
示例#4
0
    def setUp(self):
        super(TestVerifyCommand, self).setUp()

        class DummyConfig(object):
            pass

        class DummySource(source.Source):
            name = 'dummy'

            def Verify(self):
                return 0

        # Instead of a DummyCache, we will override cache_factory.Create so
        # we can return a pmock cache object.
        self.original_caches_create = cache_factory.Create
        self.original_sources_create = source_factory.Create

        # Add dummy source to the set if implementations of sources.
        source_factory.RegisterImplementation(DummySource)

        # Create a config with a section for a passwd map.
        self.conf = DummyConfig()
        self.conf.options = {config.MAP_PASSWORD: config.MapOptions()}
        self.conf.options[config.MAP_PASSWORD].cache = {'name': 'dummy'}
        self.conf.options[config.MAP_PASSWORD].source = {'name': 'dummy'}

        self.original_verify_configuration = config.VerifyConfiguration
        self.original_getmap = nss.GetMap
        self.original_getpwall = pwd.getpwall
        self.original_getgrall = grp.getgrall

        # Setup maps used by VerifyMap testing.
        big_map = passwd.PasswdMap()
        map_entry1 = passwd.PasswdMapEntry()
        map_entry1.name = 'foo'
        map_entry1.uid = 10
        map_entry1.gid = 10
        big_map.Add(map_entry1)
        map_entry2 = passwd.PasswdMapEntry()
        map_entry2.name = 'bar'
        map_entry2.uid = 20
        map_entry2.gid = 20
        big_map.Add(map_entry2)

        small_map = passwd.PasswdMap()
        small_map.Add(map_entry1)

        self.big_map = big_map
        self.small_map = small_map
示例#5
0
    def testContains(self):
        """Verify __contains__ works, and does a deep compare."""
        pentry_good = self._good_entry
        pentry_like_good = passwd.PasswdMapEntry()
        pentry_like_good.name = 'foo'  # same Key(), but rest of attributes differ
        pentry_bad = passwd.PasswdMapEntry()
        pentry_bad.name = 'bar'

        pmap = passwd.PasswdMap([pentry_good])

        self.assertTrue(pentry_good in pmap, msg='expected entry to be in map')
        self.assertFalse(pentry_bad in pmap,
                         msg='did not expect entry to be in map')
        self.assertFalse(pentry_like_good in pmap,
                         msg='__contains__ not doing a deep compare')
示例#6
0
    def testUpdateMapsTrapsPermissionDenied(self):
        self.mox.StubOutWithMock(map_updater.MapUpdater, 'UpdateFromSource')
        map_updater.MapUpdater.UpdateFromSource(mox.IgnoreArg(),
                                                incremental=True,
                                                force_write=False).AndRaise(
                                                    error.PermissionDenied)

        self.mox.StubOutClassWithMocks(lock, 'PidFile')
        lock_mock = lock.PidFile(filename=None)
        lock_mock.Lock(force=False).AndReturn(True)
        lock_mock.Locked().AndReturn(True)
        lock_mock.Unlock()

        self.conf.maps = [config.MAP_PASSWORD]
        self.conf.cache = 'dummy'
        modify_stamp = 1
        map_entry = passwd.PasswdMapEntry({'name': 'foo', 'uid': 10, 'gid': 10})
        passwd_map = passwd.PasswdMap([map_entry])
        passwd_map.SetModifyTimestamp(modify_stamp)

        source_mock = self.mox.CreateMock(source.Source)

        self.mox.StubOutWithMock(source_factory, 'Create')
        source_factory.Create(self.conf.options[
            config.MAP_PASSWORD].source).AndReturn(source_mock)

        cache_mock = self.mox.CreateMock(caches.Cache)

        self.mox.StubOutWithMock(cache_factory, 'Create')

        self.mox.ReplayAll()

        c = command.Update()
        self.assertEqual(
            1, c.UpdateMaps(self.conf, incremental=True, force_write=False))
示例#7
0
    def testUpdateSingleMaps(self):
        self.mox.StubOutClassWithMocks(lock, 'PidFile')
        lock_mock = lock.PidFile(filename=None)
        lock_mock.Lock(force=False).AndReturn(True)
        lock_mock.Locked().AndReturn(True)
        lock_mock.Unlock()

        self.conf.maps = [config.MAP_PASSWORD]
        self.conf.cache = 'dummy'

        modify_stamp = 1
        map_entry = passwd.PasswdMapEntry({'name': 'foo', 'uid': 10, 'gid': 10})
        passwd_map = passwd.PasswdMap([map_entry])
        passwd_map.SetModifyTimestamp(modify_stamp)

        source_mock = self.mox.CreateMock(source.Source)
        source_mock.GetMap(config.MAP_PASSWORD,
                           location=None).AndReturn(passwd_map)

        self.mox.StubOutWithMock(source_factory, 'Create')
        source_factory.Create(self.conf.options[
            config.MAP_PASSWORD].source).AndReturn(source_mock)

        cache_mock = self.mox.CreateMock(caches.Cache)
        cache_mock.WriteMap(map_data=passwd_map).AndReturn(0)

        self.mox.StubOutWithMock(cache_factory, 'Create')
        cache_factory.Create(self.conf.options[config.MAP_PASSWORD].cache,
                             config.MAP_PASSWORD).AndReturn(cache_mock)

        self.mox.ReplayAll()
        c = command.Update()
        self.assertEqual(
            0, c.UpdateMaps(self.conf, incremental=True, force_write=False))
示例#8
0
  def testFullUpdateOnEmptySource(self):
    """A full update as above, but instead, the initial source is empty."""
    original_modify_stamp = time.gmtime(1)
    new_modify_stamp = time.gmtime(2)
    # Construct an updater
    self.updater = files_updater.FileMapUpdater(config.MAP_PASSWORD,
                                                self.workdir,
                                                {'name': 'files',
                                                 'dir': self.workdir2})
    self.updater.WriteModifyTimestamp(original_modify_stamp)

    # Construct a cache
    cache = files.FilesPasswdMapHandler({'dir': self.workdir2})
    map_entry = passwd.PasswdMapEntry({'name': 'foo', 'uid': 10, 'gid': 10})
    password_map = passwd.PasswdMap()
    password_map.SetModifyTimestamp(new_modify_stamp)
    password_map.Add(map_entry)
    cache.Write(password_map)

    source_mock = self.mox.CreateMock(source.FileSource)
    source_mock.GetFile(config.MAP_PASSWORD,
                        mox.IgnoreArg(),
                        current_file=mox.IgnoreArg(),
                        location=None).AndReturn(None)
    self.mox.ReplayAll()
    self.assertRaises(error.EmptyMap,
                      self.updater.UpdateCacheFromSource,
                      cache,
                      source_mock,
                      force_write=False,
                      location=None)
    self.assertNotEqual(new_modify_stamp, self.updater.GetModifyTimestamp())
    self.assertEqual(None, self.updater.GetUpdateTimestamp())
示例#9
0
 def testAttributes(self):
     """Test that we can get and set all expected attributes."""
     entry = passwd.PasswdMapEntry()
     entry.name = 'foo'
     self.assertEquals(entry.name,
                       'foo',
                       msg='Could not set attribute: name')
     entry.passwd = 'x'
     self.assertEquals(entry.passwd,
                       'x',
                       msg='Could not set attribute: passwd')
     entry.uid = 10
     self.assertEquals(entry.uid, 10, msg='Could not set attribute: uid')
     entry.gid = 10
     self.assertEquals(entry.gid, 10, msg='Could not set attribute: gid')
     entry.gecos = 'How Now Brown Cow'
     self.assertEquals(entry.gecos,
                       'How Now Brown Cow',
                       msg='Could not set attribute: gecos')
     entry.dir = '/home/foo'
     self.assertEquals(entry.dir,
                       '/home/foo',
                       msg='Could not set attribute: dir')
     entry.shell = '/bin/bash'
     self.assertEquals(entry.shell,
                       '/bin/bash',
                       msg='Could not set attribute: shell')
示例#10
0
    def testVerifyFailure(self):
        # create a map
        m = passwd.PasswdMap()
        e = passwd.PasswdMapEntry()
        e.name = 'foo'
        e.uid = 1000
        e.gid = 2000
        self.assertTrue(m.Add(e))

        updater = nssdb.NssDbPasswdHandler({
            'dir': self.workdir,
            'makedb': '/usr/bin/makedb'
        })
        written = updater.Write(m)

        self.assertTrue(os.path.exists(updater.temp_cache_filename),
                        'updater.Write() did not create a file')

        # change the cache
        db = btopen(updater.temp_cache_filename)
        del db[db.first()[0]]
        db.sync()
        db.close()

        retval = updater.Verify(written)

        self.assertEqual(False, retval)
        self.assertFalse(
            os.path.exists(os.path.join(updater.temp_cache_filename)))
示例#11
0
    def testNssDbPasswdHandlerWriteData(self):
        entry_string = 'foo:x:1000:1000:foo:/:/bin/sh'

        makedb_stdin = self.mox.CreateMock(sys.stdin)
        makedb_stdin.write('.foo %s\n' % entry_string)
        makedb_stdin.write('=1000 %s\n' % entry_string)
        makedb_stdin.write('00 %s\n' % entry_string)

        passwd_map = passwd.PasswdMap()
        passwd_map_entry = passwd.PasswdMapEntry()
        passwd_map_entry.name = 'foo'
        passwd_map_entry.uid = 1000
        passwd_map_entry.gid = 1000
        passwd_map_entry.gecos = 'foo'
        passwd_map_entry.dir = '/'
        passwd_map_entry.shell = '/bin/sh'
        passwd_map_entry.passwd = 'x'
        self.failUnless(passwd_map.Add(passwd_map_entry))

        writer = nssdb.NssDbPasswdHandler({
            'makedb': '/bin/false',
            'dir': '/tmp'
        })

        self.mox.ReplayAll()

        writer.WriteData(makedb_stdin, passwd_map_entry, 0)
示例#12
0
    def testVerify(self):
        # Can't test if no makedb
        if not os.path.exists('/usr/bin/makedb'):
            raise TestSkipped('no /usr/bin/makedb')
        # create a map
        m = passwd.PasswdMap()
        e = passwd.PasswdMapEntry()
        e.name = 'foo'
        e.uid = 1000
        e.gid = 2000
        self.failUnless(m.Add(e))

        updater = nssdb.NssDbPasswdHandler({
            'dir': self.workdir,
            'makedb': '/usr/bin/makedb'
        })
        written = updater.Write(m)

        self.failUnless(os.path.exists(updater.temp_cache_filename),
                        'updater.Write() did not create a file')

        retval = updater.Verify(written)

        self.failUnlessEqual(True, retval)

        os.unlink(updater.temp_cache_filename)
示例#13
0
  def Transform(self, obj):
    """Transforms a LDAP posixAccount data structure into a PasswdMapEntry."""

    pw = passwd.PasswdMapEntry()

    if 'gecos' in obj:
      pw.gecos = obj['gecos'][0]
    elif 'cn' in obj:
      pw.gecos = obj['cn'][0]
    elif 'fullName' in obj:
      pw.gecos = obj['fullName'][0]
    else:
      raise ValueError('Neither gecos nor cn found')

    pw.name = obj['uid'][0]
    if 'loginShell' in obj:
      pw.shell = obj['loginShell'][0]
    else:
      pw.shell = ''

    pw.uid = int(obj['uidNumber'][0])
    pw.gid = int(obj['gidNumber'][0])
    pw.dir = obj['homeDirectory'][0]

    # hack
    pw.passwd = '*'

    return pw
示例#14
0
    def ConvertValueToMapEntry(self, entry):
        """Convert a pwent-like string into a PasswdMapEntry.

        Args:
         entry: A string containing a pwent entry ala /etc/passwd

        Returns:
          a PasswdMapEntry instance
        """
        if isinstance(entry, bytes):
            entry = entry.decode('ascii')
        elif entry.endswith('\x00'):
            entry = entry[:-1]

        entry = entry.split(':')
        map_entry = passwd.PasswdMapEntry()
        # maps expect strict typing, so convert to int as appropriate.
        map_entry.name = entry[0]
        map_entry.passwd = entry[1]
        map_entry.uid = int(entry[2])
        map_entry.gid = int(entry[3])
        map_entry.gecos = entry[4]
        map_entry.dir = entry[5]
        map_entry.shell = entry[6]

        return map_entry
示例#15
0
  def testFullUpdate(self):
    """A full update reads the source, writes to cache, and updates times."""
    original_modify_stamp = 1
    new_modify_stamp = 2

    updater = map_updater.MapUpdater(
        config.MAP_PASSWORD, self.workdir, {})
    updater.WriteModifyTimestamp(original_modify_stamp)

    map_entry = passwd.PasswdMapEntry({'name': 'foo', 'uid': 10, 'gid': 10})
    password_map = passwd.PasswdMap([map_entry])
    password_map.SetModifyTimestamp(new_modify_stamp)

    cache_mock = self.mox.CreateMock(files.FilesCache)
    cache_mock.WriteMap(map_data=password_map).AndReturn(0)

    source_mock = self.mox.CreateMock(source.Source)
    source_mock.GetMap(config.MAP_PASSWORD,
                       location=None).AndReturn(password_map)

    self.mox.ReplayAll()

    self.assertEqual(0, updater.UpdateCacheFromSource(cache_mock,
                                                      source_mock,
                                                      False,
                                                      False,
                                                      None))
    self.assertEqual(updater.GetModifyTimestamp(), new_modify_stamp)
    self.assertNotEqual(updater.GetUpdateTimestamp(), None)
示例#16
0
 def testWrite(self):
     cache = files.FilesPasswdMapHandler(self.config)
     entry = passwd.PasswdMapEntry({'name': 'foo', 'uid': 10, 'gid': 10})
     pmap = passwd.PasswdMap([entry])
     written = cache.Write(pmap)
     self.assertTrue('foo' in written)
     self.assertFalse(entry in pmap)  # we emptied pmap to avoid mem leaks
     self.assertFalse(cache.temp_cache_file.closed)
示例#17
0
 def setUp(self):
     """Set some default avalible data for testing."""
     self._good_entry = passwd.PasswdMapEntry()
     self._good_entry.name = 'foo'
     self._good_entry.passwd = 'x'
     self._good_entry.uid = 10
     self._good_entry.gid = 10
     self._good_entry.gecos = 'How Now Brown Cow'
     self._good_entry.dir = '/home/foo'
     self._good_entry.shell = '/bin/bash'
示例#18
0
    def testMerge(self):
        """Verify Merge() throws the right exceptions and correctly merges."""

        # Setup some MapEntry objects with distinct Key()s
        pentry1 = self._good_entry
        pentry2 = passwd.PasswdMapEntry()
        pentry2.name = 'john'
        pentry3 = passwd.PasswdMapEntry()
        pentry3.name = 'jane'

        # Setup some Map objects
        pmap_big = passwd.PasswdMap([pentry1, pentry2])
        pmap_small = passwd.PasswdMap([pentry3])

        # Merge small into big
        self.assertTrue(pmap_big.Merge(pmap_small),
                        msg='Merging small into big failed!')
        self.assertTrue(pmap_big.Exists(pentry1),
                        msg='pentry1 not found in Map')
        self.assertTrue(pmap_big.Exists(pentry2),
                        msg='pentry1 not found in Map')
        self.assertTrue(pmap_big.Exists(pentry3),
                        msg='pentry1 not found in Map')

        # A second merge should do nothing
        self.assertFalse(pmap_big.Merge(pmap_small),
                         msg='Re-merging small into big succeeded.')

        # An empty merge should do nothing
        self.assertFalse(pmap_big.Merge(passwd.PasswdMap()),
                         msg='Empty Merge should have done nothing.')

        # Merge a GroupMap should throw TypeError
        gmap = group.GroupMap()
        self.assertRaises(TypeError, pmap_big.Merge, gmap)

        # Merge an older map should throw an UnsupportedMap
        old_map = passwd.PasswdMap(modify_time=1)
        new_map = passwd.PasswdMap(modify_time=2)
        self.assertRaises(error.InvalidMerge, new_map.Merge, old_map)
        old_map = passwd.PasswdMap(update_time=1)
        new_map = passwd.PasswdMap(update_time=2)
        self.assertRaises(error.InvalidMerge, new_map.Merge, old_map)
示例#19
0
 def setUp(self):
     """Set some default avalible data for testing."""
     self.good_entry = passwd.PasswdMapEntry()
     self.good_entry.name = 'foo'
     self.good_entry.passwd = 'x'
     self.good_entry.uid = 10
     self.good_entry.gid = 10
     self.good_entry.gecos = b'How Now Brown Cow'
     self.good_entry.dir = b'/home/foo'
     self.good_entry.shell = b'/bin/bash'
     self.parser = consulsource.ConsulPasswdMapParser()
示例#20
0
    def testFullUpdate(self):
        original_modify_stamp = time.gmtime(1)
        new_modify_stamp = time.gmtime(2)

        # Construct a fake source.
        def GetFile(map_name, dst_file, current_file, location):
            print(("GetFile: %s" % dst_file))
            f = open(dst_file, 'w')
            f.write('root:x:0:0:root:/root:/bin/bash\n')
            f.close()
            os.utime(dst_file, (1, 2))
            os.system("ls -al %s" % dst_file)
            return dst_file

        dst_file = mox.Value()
        source_mock = self.mox.CreateMock(source.FileSource)
        source_mock.GetFile(config.MAP_PASSWORD,
                            mox.Remember(dst_file),
                            current_file=mox.IgnoreArg(),
                            location=mox.IgnoreArg()).WithSideEffects(
                                GetFile).AndReturn(dst_file)

        # Construct the cache.
        cache = files.FilesPasswdMapHandler({'dir': self.workdir2})
        map_entry = passwd.PasswdMapEntry({
            'name': 'foo',
            'uid': 10,
            'gid': 10
        })
        password_map = passwd.PasswdMap()
        password_map.SetModifyTimestamp(new_modify_stamp)
        password_map.Add(map_entry)
        cache.Write(password_map)

        updater = files_updater.FileMapUpdater(config.MAP_PASSWORD,
                                               self.workdir, {
                                                   'name': 'files',
                                                   'dir': self.workdir2
                                               })
        updater.WriteModifyTimestamp(original_modify_stamp)

        self.mox.ReplayAll()

        self.assertEqual(
            0,
            updater.UpdateCacheFromSource(cache,
                                          source_mock,
                                          force_write=False,
                                          location=None))

        self.assertEqual(new_modify_stamp, updater.GetModifyTimestamp())
        self.assertNotEqual(None, updater.GetUpdateTimestamp())
示例#21
0
 def _ReadEntry(self, entry):
     """Return a PasswdMapEntry from a record in the target cache."""
     entry = entry.split(':')
     map_entry = passwd.PasswdMapEntry()
     # maps expect strict typing, so convert to int as appropriate.
     map_entry.name = entry[0]
     map_entry.passwd = entry[1]
     map_entry.uid = int(entry[2])
     map_entry.gid = int(entry[3])
     map_entry.gecos = entry[4]
     map_entry.dir = entry[5]
     map_entry.shell = entry[6]
     return map_entry
示例#22
0
 def testInit(self):
     """Construct empty and seeded PasswdMapEntry."""
     entry = passwd.PasswdMapEntry()
     self.assertEquals(type(entry),
                       passwd.PasswdMapEntry,
                       msg='Could not create empty PasswdMapEntry')
     seed = {
         'name': 'foo',
         'passwd': 'x',
         'uid': 10,
         'gid': 10,
         'gecos': '',
         'dir': '',
         'shell': ''
     }
     entry = passwd.PasswdMapEntry(seed)
     self.assert_(entry.Verify(),
                  msg='Could not verify seeded PasswdMapEntry')
     self.assertEquals(entry.name,
                       'foo',
                       msg='Entry returned wrong value for name')
     self.assertEquals(entry.passwd,
                       'x',
                       msg='Entry returned wrong value for passwd')
     self.assertEquals(entry.uid,
                       10,
                       msg='Entry returned wrong value for uid')
     self.assertEquals(entry.gid,
                       10,
                       msg='Entry returned wrong value for gid')
     self.assertEquals(entry.gecos,
                       '',
                       msg='Entry returned wrong value for gecos')
     self.assertEquals(entry.dir,
                       '',
                       msg='Entry returned wrong value for dir')
     self.assertEquals(entry.shell,
                       '',
                       msg='Entry returned wrong value for shell')
示例#23
0
    def _ReadEntry(self, name, entry):
        """Return a PasswdMapEntry from a record in the target cache."""

        map_entry = passwd.PasswdMapEntry()
        # maps expect strict typing, so convert to int as appropriate.
        map_entry.name = name
        map_entry.passwd = entry.get('passwd', 'x')
        map_entry.uid = int(entry['uid'])
        map_entry.gid = int(entry['gid'])
        map_entry.gecos = entry.get('comment', '')
        map_entry.dir = entry.get('home', '/home/{}'.format(name))
        map_entry.shell = entry.get('shell', '/bin/bash')
        return map_entry
示例#24
0
    def testNssDbPasswdHandlerWrite(self):
        ent = 'foo:x:1000:1000:foo:/:/bin/sh'

        makedb_stdin = self.mox.CreateMock(sys.stdin)
        makedb_stdin.write('.foo %s\n' % ent)
        makedb_stdin.write('=1000 %s\n' % ent)
        makedb_stdin.write('00 %s\n' % ent)
        makedb_stdin.close()

        makedb_stdout = self.mox.CreateMock(sys.stdout)
        makedb_stdout.read().AndReturn('')
        makedb_stdout.close()

        m = passwd.PasswdMap()
        pw = passwd.PasswdMapEntry()
        pw.name = 'foo'
        pw.uid = 1000
        pw.gid = 1000
        pw.gecos = 'foo'
        pw.dir = '/'
        pw.shell = '/bin/sh'
        pw.passwd = 'x'
        pw.Verify()
        self.failUnless(m.Add(pw))

        self.mox.StubOutWithMock(select, 'select')
        select.select([makedb_stdout], (), (), 0).AndReturn(([37], [], []))
        select.select([makedb_stdout], (), (), 0).AndReturn(([], [], []))

        def SpawnMakeDb():
            makedb = MakeDbDummy()
            makedb.stdin = makedb_stdin
            makedb.stdout = makedb_stdout
            return makedb

        writer = nssdb.NssDbPasswdHandler({
            'makedb': '/usr/bin/makedb',
            'dir': self.workdir
        })

        writer._SpawnMakeDb = SpawnMakeDb

        self.mox.ReplayAll()

        writer.Write(m)

        tmppasswd = os.path.join(self.workdir, 'passwd.db')
        self.failIf(os.path.exists(tmppasswd))
        # just clean it up, Write() doesn't Commit()
        writer._Rollback()
示例#25
0
    def testAdd(self):
        """Add throws an error for objects it can't verify."""
        amap = automount.AutomountMap()
        entry = self._good_entry
        self.assertTrue(amap.Add(entry), msg='failed to append new entry.')

        self.assertEqual(1, len(amap), msg='unexpected size for Map.')

        ret_entry = amap.PopItem()
        self.assertEqual(ret_entry, entry, msg='failed to pop correct entry.')

        pentry = passwd.PasswdMapEntry()
        pentry.name = 'foo'
        pentry.uid = 10
        pentry.gid = 10
        self.assertRaises(TypeError, amap.Add, pentry)
示例#26
0
def GetPasswdMap():
    """Returns a PasswdMap built from nss calls."""
    passwd_map = passwd.PasswdMap()

    for nss_entry in pwd.getpwall():
        map_entry = passwd.PasswdMapEntry()
        map_entry.name = nss_entry[0]
        map_entry.passwd = nss_entry[1]
        map_entry.uid = nss_entry[2]
        map_entry.gid = nss_entry[3]
        map_entry.gecos = nss_entry[4]
        map_entry.dir = nss_entry[5]
        map_entry.shell = nss_entry[6]
        passwd_map.Add(map_entry)

    return passwd_map
示例#27
0
    def testAdd(self):
        """Add throws an error for objects it can't verify."""
        nmap = netgroup.NetgroupMap()
        entry = self._good_entry
        self.assert_(nmap.Add(entry), msg='failed to append new entry.')

        self.assertEquals(1, len(nmap), msg='unexpected size for Map.')

        ret_entry = nmap.PopItem()
        self.assertEquals(ret_entry, entry, msg='failed to pop correct entry.')

        pentry = passwd.PasswdMapEntry()
        pentry.name = 'foo'
        pentry.uid = 10
        pentry.gid = 10
        self.assertRaises(TypeError, nmap.Add, pentry)
示例#28
0
    def testAdd(self):
        """Add throws an error for objects it can't verify."""
        smap = shadow.ShadowMap()
        entry = self._good_entry
        self.assertTrue(smap.Add(entry), msg='failed to append new entry.')

        self.assertEqual(1, len(smap), msg='unexpected size for Map.')

        ret_entry = smap.PopItem()
        self.assertEqual(ret_entry, entry, msg='failed to pop existing entry.')

        pentry = passwd.PasswdMapEntry()
        pentry.name = 'foo'
        pentry.uid = 10
        pentry.gid = 10
        self.assertRaises(TypeError, smap.Add, pentry)
示例#29
0
    def testWritePasswdEntry(self):
        """We correctly write a typical entry in /etc/passwd format."""
        cache = files.FilesPasswdMapHandler(self.config)
        file_mock = self.mox.CreateMock(sys.stdout)
        file_mock.write('root:x:0:0:Rootsy:/root:/bin/bash\n')

        map_entry = passwd.PasswdMapEntry()
        map_entry.name = 'root'
        map_entry.passwd = 'x'
        map_entry.uid = 0
        map_entry.gid = 0
        map_entry.gecos = 'Rootsy'
        map_entry.dir = '/root'
        map_entry.shell = '/bin/bash'

        self.mox.ReplayAll()

        cache._WriteData(file_mock, map_entry)
示例#30
0
    def testVerifyFailure(self):
        # Can't test if no makedb
        if not os.path.exists('/usr/bin/makedb'):
            raise TestSkipped('no /usr/bin/makedb')
        # Hide the warning that we expect to get

        class TestFilter(logging.Filter):
            def filter(self, record):
                return not record.msg.startswith(
                    'verify failed: %d keys missing')

        fltr = TestFilter()
        logging.getLogger('NssDbPasswdHandler').addFilter(fltr)
        # create a map
        m = passwd.PasswdMap()
        e = passwd.PasswdMapEntry()
        e.name = 'foo'
        e.uid = 1000
        e.gid = 2000
        self.failUnless(m.Add(e))

        updater = nssdb.NssDbPasswdHandler({
            'dir': self.workdir,
            'makedb': '/usr/bin/makedb'
        })
        written = updater.Write(m)

        self.failUnless(os.path.exists(updater.temp_cache_filename),
                        'updater.Write() did not create a file')

        # change the cache
        db = bsddb.btopen(updater.temp_cache_filename)
        del db[db.first()[0]]
        db.sync()
        db.close()

        retval = updater.Verify(written)

        self.failUnlessEqual(False, retval)
        self.failIf(os.path.exists(os.path.join(updater.temp_cache_filename)))
        # no longer hide this message
        logging.getLogger('NssDbPasswdHandler').removeFilter(fltr)