test_strcred.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.cred.strcred}.
  5. """
  6. from __future__ import absolute_import, division
  7. import os
  8. from twisted import plugin
  9. from twisted.trial import unittest
  10. from twisted.cred import credentials, checkers, error, strcred
  11. from twisted.plugins import cred_file, cred_anonymous
  12. from twisted.python import usage, compat
  13. from twisted.python.filepath import FilePath
  14. from twisted.python.fakepwd import UserDatabase
  15. from twisted.python.reflect import requireModule
  16. if compat._PY3:
  17. from io import StringIO
  18. else:
  19. from io import BytesIO as StringIO
  20. try:
  21. import crypt
  22. except ImportError:
  23. crypt = None
  24. try:
  25. import pwd
  26. except ImportError:
  27. pwd = None
  28. try:
  29. import spwd
  30. except ImportError:
  31. spwd = None
  32. def getInvalidAuthType():
  33. """
  34. Helper method to produce an auth type that doesn't exist.
  35. """
  36. invalidAuthType = 'ThisPluginDoesNotExist'
  37. while (invalidAuthType in
  38. [factory.authType for factory in strcred.findCheckerFactories()]):
  39. invalidAuthType += '_'
  40. return invalidAuthType
  41. class PublicAPITests(unittest.TestCase):
  42. def test_emptyDescription(self):
  43. """
  44. Test that the description string cannot be empty.
  45. """
  46. iat = getInvalidAuthType()
  47. self.assertRaises(strcred.InvalidAuthType, strcred.makeChecker, iat)
  48. self.assertRaises(
  49. strcred.InvalidAuthType, strcred.findCheckerFactory, iat)
  50. def test_invalidAuthType(self):
  51. """
  52. Test that an unrecognized auth type raises an exception.
  53. """
  54. iat = getInvalidAuthType()
  55. self.assertRaises(strcred.InvalidAuthType, strcred.makeChecker, iat)
  56. self.assertRaises(
  57. strcred.InvalidAuthType, strcred.findCheckerFactory, iat)
  58. class StrcredFunctionsTests(unittest.TestCase):
  59. def test_findCheckerFactories(self):
  60. """
  61. Test that findCheckerFactories returns all available plugins.
  62. """
  63. availablePlugins = list(strcred.findCheckerFactories())
  64. for plg in plugin.getPlugins(strcred.ICheckerFactory):
  65. self.assertIn(plg, availablePlugins)
  66. def test_findCheckerFactory(self):
  67. """
  68. Test that findCheckerFactory returns the first plugin
  69. available for a given authentication type.
  70. """
  71. self.assertIdentical(strcred.findCheckerFactory('file'),
  72. cred_file.theFileCheckerFactory)
  73. class MemoryCheckerTests(unittest.TestCase):
  74. def setUp(self):
  75. self.admin = credentials.UsernamePassword('admin', 'asdf')
  76. self.alice = credentials.UsernamePassword('alice', 'foo')
  77. self.badPass = credentials.UsernamePassword('alice', 'foobar')
  78. self.badUser = credentials.UsernamePassword('x', 'yz')
  79. self.checker = strcred.makeChecker('memory:admin:asdf:alice:foo')
  80. def test_isChecker(self):
  81. """
  82. Verifies that strcred.makeChecker('memory') returns an object
  83. that implements the L{ICredentialsChecker} interface.
  84. """
  85. self.assertTrue(checkers.ICredentialsChecker.providedBy(self.checker))
  86. self.assertIn(credentials.IUsernamePassword,
  87. self.checker.credentialInterfaces)
  88. def test_badFormatArgString(self):
  89. """
  90. Test that an argument string which does not contain user:pass
  91. pairs (i.e., an odd number of ':' characters) raises an exception.
  92. """
  93. self.assertRaises(strcred.InvalidAuthArgumentString,
  94. strcred.makeChecker, 'memory:a:b:c')
  95. def test_memoryCheckerSucceeds(self):
  96. """
  97. Test that the checker works with valid credentials.
  98. """
  99. def _gotAvatar(username):
  100. self.assertEqual(username, self.admin.username)
  101. return (self.checker
  102. .requestAvatarId(self.admin)
  103. .addCallback(_gotAvatar))
  104. def test_memoryCheckerFailsUsername(self):
  105. """
  106. Test that the checker fails with an invalid username.
  107. """
  108. return self.assertFailure(self.checker.requestAvatarId(self.badUser),
  109. error.UnauthorizedLogin)
  110. def test_memoryCheckerFailsPassword(self):
  111. """
  112. Test that the checker fails with an invalid password.
  113. """
  114. return self.assertFailure(self.checker.requestAvatarId(self.badPass),
  115. error.UnauthorizedLogin)
  116. class AnonymousCheckerTests(unittest.TestCase):
  117. def test_isChecker(self):
  118. """
  119. Verifies that strcred.makeChecker('anonymous') returns an object
  120. that implements the L{ICredentialsChecker} interface.
  121. """
  122. checker = strcred.makeChecker('anonymous')
  123. self.assertTrue(checkers.ICredentialsChecker.providedBy(checker))
  124. self.assertIn(credentials.IAnonymous, checker.credentialInterfaces)
  125. def testAnonymousAccessSucceeds(self):
  126. """
  127. Test that we can log in anonymously using this checker.
  128. """
  129. checker = strcred.makeChecker('anonymous')
  130. request = checker.requestAvatarId(credentials.Anonymous())
  131. def _gotAvatar(avatar):
  132. self.assertIdentical(checkers.ANONYMOUS, avatar)
  133. return request.addCallback(_gotAvatar)
  134. class UnixCheckerTests(unittest.TestCase):
  135. users = {
  136. 'admin': 'asdf',
  137. 'alice': 'foo',
  138. }
  139. def _spwd(self, username):
  140. return (username, crypt.crypt(self.users[username], 'F/'),
  141. 0, 0, 99999, 7, -1, -1, -1)
  142. def setUp(self):
  143. self.admin = credentials.UsernamePassword('admin', 'asdf')
  144. self.alice = credentials.UsernamePassword('alice', 'foo')
  145. self.badPass = credentials.UsernamePassword('alice', 'foobar')
  146. self.badUser = credentials.UsernamePassword('x', 'yz')
  147. self.checker = strcred.makeChecker('unix')
  148. # Hack around the pwd and spwd modules, since we can't really
  149. # go about reading your /etc/passwd or /etc/shadow files
  150. if pwd:
  151. database = UserDatabase()
  152. for username, password in self.users.items():
  153. database.addUser(
  154. username, crypt.crypt(password, 'F/'),
  155. 1000, 1000, username, '/home/' + username, '/bin/sh')
  156. self.patch(pwd, 'getpwnam', database.getpwnam)
  157. if spwd:
  158. self._spwd_getspnam = spwd.getspnam
  159. spwd.getspnam = self._spwd
  160. def tearDown(self):
  161. if spwd:
  162. spwd.getspnam = self._spwd_getspnam
  163. def test_isChecker(self):
  164. """
  165. Verifies that strcred.makeChecker('unix') returns an object
  166. that implements the L{ICredentialsChecker} interface.
  167. """
  168. self.assertTrue(checkers.ICredentialsChecker.providedBy(self.checker))
  169. self.assertIn(credentials.IUsernamePassword,
  170. self.checker.credentialInterfaces)
  171. def test_unixCheckerSucceeds(self):
  172. """
  173. Test that the checker works with valid credentials.
  174. """
  175. def _gotAvatar(username):
  176. self.assertEqual(username, self.admin.username)
  177. return (self.checker
  178. .requestAvatarId(self.admin)
  179. .addCallback(_gotAvatar))
  180. def test_unixCheckerFailsUsername(self):
  181. """
  182. Test that the checker fails with an invalid username.
  183. """
  184. return self.assertFailure(self.checker.requestAvatarId(self.badUser),
  185. error.UnauthorizedLogin)
  186. def test_unixCheckerFailsPassword(self):
  187. """
  188. Test that the checker fails with an invalid password.
  189. """
  190. return self.assertFailure(self.checker.requestAvatarId(self.badPass),
  191. error.UnauthorizedLogin)
  192. if None in (pwd, spwd, crypt):
  193. availability = []
  194. for module, name in ((pwd, "pwd"), (spwd, "spwd"), (crypt, "crypt")):
  195. if module is None:
  196. availability += [name]
  197. for method in (test_unixCheckerSucceeds,
  198. test_unixCheckerFailsUsername,
  199. test_unixCheckerFailsPassword):
  200. method.skip = ("Required module(s) are unavailable: " +
  201. ", ".join(availability))
  202. class FileDBCheckerTests(unittest.TestCase):
  203. """
  204. Test for the --auth=file:... file checker.
  205. """
  206. def setUp(self):
  207. self.admin = credentials.UsernamePassword(b'admin', b'asdf')
  208. self.alice = credentials.UsernamePassword(b'alice', b'foo')
  209. self.badPass = credentials.UsernamePassword(b'alice', b'foobar')
  210. self.badUser = credentials.UsernamePassword(b'x', b'yz')
  211. self.filename = self.mktemp()
  212. FilePath(self.filename).setContent(b'admin:asdf\nalice:foo\n')
  213. self.checker = strcred.makeChecker('file:' + self.filename)
  214. def _fakeFilename(self):
  215. filename = '/DoesNotExist'
  216. while os.path.exists(filename):
  217. filename += '_'
  218. return filename
  219. def test_isChecker(self):
  220. """
  221. Verifies that strcred.makeChecker('memory') returns an object
  222. that implements the L{ICredentialsChecker} interface.
  223. """
  224. self.assertTrue(checkers.ICredentialsChecker.providedBy(self.checker))
  225. self.assertIn(credentials.IUsernamePassword,
  226. self.checker.credentialInterfaces)
  227. def test_fileCheckerSucceeds(self):
  228. """
  229. Test that the checker works with valid credentials.
  230. """
  231. def _gotAvatar(username):
  232. self.assertEqual(username, self.admin.username)
  233. return (self.checker
  234. .requestAvatarId(self.admin)
  235. .addCallback(_gotAvatar))
  236. def test_fileCheckerFailsUsername(self):
  237. """
  238. Test that the checker fails with an invalid username.
  239. """
  240. return self.assertFailure(self.checker.requestAvatarId(self.badUser),
  241. error.UnauthorizedLogin)
  242. def test_fileCheckerFailsPassword(self):
  243. """
  244. Test that the checker fails with an invalid password.
  245. """
  246. return self.assertFailure(self.checker.requestAvatarId(self.badPass),
  247. error.UnauthorizedLogin)
  248. def test_failsWithEmptyFilename(self):
  249. """
  250. Test that an empty filename raises an error.
  251. """
  252. self.assertRaises(ValueError, strcred.makeChecker, 'file')
  253. self.assertRaises(ValueError, strcred.makeChecker, 'file:')
  254. def test_warnWithBadFilename(self):
  255. """
  256. When the file auth plugin is given a file that doesn't exist, it
  257. should produce a warning.
  258. """
  259. oldOutput = cred_file.theFileCheckerFactory.errorOutput
  260. newOutput = StringIO()
  261. cred_file.theFileCheckerFactory.errorOutput = newOutput
  262. strcred.makeChecker('file:' + self._fakeFilename())
  263. cred_file.theFileCheckerFactory.errorOutput = oldOutput
  264. self.assertIn(cred_file.invalidFileWarning, newOutput.getvalue())
  265. class SSHCheckerTests(unittest.TestCase):
  266. """
  267. Tests for the --auth=sshkey:... checker. The majority of the tests for the
  268. ssh public key database checker are in
  269. L{twisted.conch.test.test_checkers.SSHPublicKeyCheckerTestCase}.
  270. """
  271. skip = None
  272. if requireModule('cryptography') is None:
  273. skip = 'cryptography is not available'
  274. if requireModule('pyasn1') is None:
  275. skip = 'pyasn1 is not available'
  276. def test_isChecker(self):
  277. """
  278. Verifies that strcred.makeChecker('sshkey') returns an object
  279. that implements the L{ICredentialsChecker} interface.
  280. """
  281. sshChecker = strcred.makeChecker('sshkey')
  282. self.assertTrue(checkers.ICredentialsChecker.providedBy(sshChecker))
  283. self.assertIn(
  284. credentials.ISSHPrivateKey, sshChecker.credentialInterfaces)
  285. class DummyOptions(usage.Options, strcred.AuthOptionMixin):
  286. """
  287. Simple options for testing L{strcred.AuthOptionMixin}.
  288. """
  289. class CheckerOptionsTests(unittest.TestCase):
  290. def test_createsList(self):
  291. """
  292. Test that the --auth command line creates a list in the
  293. Options instance and appends values to it.
  294. """
  295. options = DummyOptions()
  296. options.parseOptions(['--auth', 'memory'])
  297. self.assertEqual(len(options['credCheckers']), 1)
  298. options = DummyOptions()
  299. options.parseOptions(['--auth', 'memory', '--auth', 'memory'])
  300. self.assertEqual(len(options['credCheckers']), 2)
  301. def test_invalidAuthError(self):
  302. """
  303. Test that the --auth command line raises an exception when it
  304. gets a parameter it doesn't understand.
  305. """
  306. options = DummyOptions()
  307. # If someone adds a 'ThisPluginDoesNotExist' then this unit
  308. # test should still run.
  309. invalidParameter = getInvalidAuthType()
  310. self.assertRaises(
  311. usage.UsageError,
  312. options.parseOptions, ['--auth', invalidParameter])
  313. self.assertRaises(
  314. usage.UsageError,
  315. options.parseOptions, ['--help-auth-type', invalidParameter])
  316. def test_createsDictionary(self):
  317. """
  318. Test that the --auth command line creates a dictionary
  319. mapping supported interfaces to the list of credentials
  320. checkers that support it.
  321. """
  322. options = DummyOptions()
  323. options.parseOptions(['--auth', 'memory', '--auth', 'anonymous'])
  324. chd = options['credInterfaces']
  325. self.assertEqual(len(chd[credentials.IAnonymous]), 1)
  326. self.assertEqual(len(chd[credentials.IUsernamePassword]), 1)
  327. chdAnonymous = chd[credentials.IAnonymous][0]
  328. chdUserPass = chd[credentials.IUsernamePassword][0]
  329. self.assertTrue(checkers.ICredentialsChecker.providedBy(chdAnonymous))
  330. self.assertTrue(checkers.ICredentialsChecker.providedBy(chdUserPass))
  331. self.assertIn(credentials.IAnonymous,
  332. chdAnonymous.credentialInterfaces)
  333. self.assertIn(credentials.IUsernamePassword,
  334. chdUserPass.credentialInterfaces)
  335. def test_credInterfacesProvidesLists(self):
  336. """
  337. Test that when two --auth arguments are passed along which
  338. support the same interface, a list with both is created.
  339. """
  340. options = DummyOptions()
  341. options.parseOptions(['--auth', 'memory', '--auth', 'unix'])
  342. self.assertEqual(
  343. options['credCheckers'],
  344. options['credInterfaces'][credentials.IUsernamePassword])
  345. def test_listDoesNotDisplayDuplicates(self):
  346. """
  347. Test that the list for --help-auth does not duplicate items.
  348. """
  349. authTypes = []
  350. options = DummyOptions()
  351. for cf in options._checkerFactoriesForOptHelpAuth():
  352. self.assertNotIn(cf.authType, authTypes)
  353. authTypes.append(cf.authType)
  354. def test_displaysListCorrectly(self):
  355. """
  356. Test that the --help-auth argument correctly displays all
  357. available authentication plugins, then exits.
  358. """
  359. newStdout = StringIO()
  360. options = DummyOptions()
  361. options.authOutput = newStdout
  362. self.assertRaises(SystemExit, options.parseOptions, ['--help-auth'])
  363. for checkerFactory in strcred.findCheckerFactories():
  364. self.assertIn(checkerFactory.authType, newStdout.getvalue())
  365. def test_displaysHelpCorrectly(self):
  366. """
  367. Test that the --help-auth-for argument will correctly display
  368. the help file for a particular authentication plugin.
  369. """
  370. newStdout = StringIO()
  371. options = DummyOptions()
  372. options.authOutput = newStdout
  373. self.assertRaises(
  374. SystemExit, options.parseOptions, ['--help-auth-type', 'file'])
  375. for line in cred_file.theFileCheckerFactory.authHelp:
  376. if line.strip():
  377. self.assertIn(line.strip(), newStdout.getvalue())
  378. def test_unexpectedException(self):
  379. """
  380. When the checker specified by --auth raises an unexpected error, it
  381. should be caught and re-raised within a L{usage.UsageError}.
  382. """
  383. options = DummyOptions()
  384. err = self.assertRaises(usage.UsageError, options.parseOptions,
  385. ['--auth', 'file'])
  386. self.assertEqual(str(err),
  387. "Unexpected error: 'file' requires a filename")
  388. class OptionsForUsernamePassword(usage.Options, strcred.AuthOptionMixin):
  389. supportedInterfaces = (credentials.IUsernamePassword,)
  390. class OptionsForUsernameHashedPassword(usage.Options, strcred.AuthOptionMixin):
  391. supportedInterfaces = (credentials.IUsernameHashedPassword,)
  392. class OptionsSupportsAllInterfaces(usage.Options, strcred.AuthOptionMixin):
  393. supportedInterfaces = None
  394. class OptionsSupportsNoInterfaces(usage.Options, strcred.AuthOptionMixin):
  395. supportedInterfaces = []
  396. class LimitingInterfacesTests(unittest.TestCase):
  397. """
  398. Tests functionality that allows an application to limit the
  399. credential interfaces it can support. For the purposes of this
  400. test, we use IUsernameHashedPassword, although this will never
  401. really be used by the command line.
  402. (I have, to date, not thought of a half-decent way for a user to
  403. specify a hash algorithm via the command-line. Nor do I think it's
  404. very useful.)
  405. I should note that, at first, this test is counter-intuitive,
  406. because we're using the checker with a pre-defined hash function
  407. as the 'bad' checker. See the documentation for
  408. L{twisted.cred.checkers.FilePasswordDB.hash} for more details.
  409. """
  410. def setUp(self):
  411. self.filename = self.mktemp()
  412. with open(self.filename, 'wb') as f:
  413. f.write(b'admin:asdf\nalice:foo\n')
  414. self.goodChecker = checkers.FilePasswordDB(self.filename)
  415. self.badChecker = checkers.FilePasswordDB(
  416. self.filename, hash=self._hash)
  417. self.anonChecker = checkers.AllowAnonymousAccess()
  418. def _hash(self, networkUsername, networkPassword, storedPassword):
  419. """
  420. A dumb hash that doesn't really do anything.
  421. """
  422. return networkPassword
  423. def test_supportsInterface(self):
  424. """
  425. Test that the supportsInterface method behaves appropriately.
  426. """
  427. options = OptionsForUsernamePassword()
  428. self.assertTrue(
  429. options.supportsInterface(credentials.IUsernamePassword))
  430. self.assertFalse(
  431. options.supportsInterface(credentials.IAnonymous))
  432. self.assertRaises(
  433. strcred.UnsupportedInterfaces, options.addChecker,
  434. self.anonChecker)
  435. def test_supportsAllInterfaces(self):
  436. """
  437. Test that the supportsInterface method behaves appropriately
  438. when the supportedInterfaces attribute is None.
  439. """
  440. options = OptionsSupportsAllInterfaces()
  441. self.assertTrue(
  442. options.supportsInterface(credentials.IUsernamePassword))
  443. self.assertTrue(
  444. options.supportsInterface(credentials.IAnonymous))
  445. def test_supportsCheckerFactory(self):
  446. """
  447. Test that the supportsCheckerFactory method behaves appropriately.
  448. """
  449. options = OptionsForUsernamePassword()
  450. fileCF = cred_file.theFileCheckerFactory
  451. anonCF = cred_anonymous.theAnonymousCheckerFactory
  452. self.assertTrue(options.supportsCheckerFactory(fileCF))
  453. self.assertFalse(options.supportsCheckerFactory(anonCF))
  454. def test_canAddSupportedChecker(self):
  455. """
  456. Test that when addChecker is called with a checker that
  457. implements at least one of the interfaces our application
  458. supports, it is successful.
  459. """
  460. options = OptionsForUsernamePassword()
  461. options.addChecker(self.goodChecker)
  462. iface = options.supportedInterfaces[0]
  463. # Test that we did get IUsernamePassword
  464. self.assertIdentical(
  465. options['credInterfaces'][iface][0], self.goodChecker)
  466. self.assertIdentical(options['credCheckers'][0], self.goodChecker)
  467. # Test that we didn't get IUsernameHashedPassword
  468. self.assertEqual(len(options['credInterfaces'][iface]), 1)
  469. self.assertEqual(len(options['credCheckers']), 1)
  470. def test_failOnAddingUnsupportedChecker(self):
  471. """
  472. Test that when addChecker is called with a checker that does
  473. not implement any supported interfaces, it fails.
  474. """
  475. options = OptionsForUsernameHashedPassword()
  476. self.assertRaises(strcred.UnsupportedInterfaces,
  477. options.addChecker, self.badChecker)
  478. def test_unsupportedInterfaceError(self):
  479. """
  480. Test that the --auth command line raises an exception when it
  481. gets a checker we don't support.
  482. """
  483. options = OptionsSupportsNoInterfaces()
  484. authType = cred_anonymous.theAnonymousCheckerFactory.authType
  485. self.assertRaises(
  486. usage.UsageError,
  487. options.parseOptions, ['--auth', authType])
  488. def test_helpAuthLimitsOutput(self):
  489. """
  490. Test that --help-auth will only list checkers that purport to
  491. supply at least one of the credential interfaces our
  492. application can use.
  493. """
  494. options = OptionsForUsernamePassword()
  495. for factory in options._checkerFactoriesForOptHelpAuth():
  496. invalid = True
  497. for interface in factory.credentialInterfaces:
  498. if options.supportsInterface(interface):
  499. invalid = False
  500. if invalid:
  501. raise strcred.UnsupportedInterfaces()
  502. def test_helpAuthTypeLimitsOutput(self):
  503. """
  504. Test that --help-auth-type will display a warning if you get
  505. help for an authType that does not supply at least one of the
  506. credential interfaces our application can use.
  507. """
  508. options = OptionsForUsernamePassword()
  509. # Find an interface that we can use for our test
  510. invalidFactory = None
  511. for factory in strcred.findCheckerFactories():
  512. if not options.supportsCheckerFactory(factory):
  513. invalidFactory = factory
  514. break
  515. self.assertNotIdentical(invalidFactory, None)
  516. # Capture output and make sure the warning is there
  517. newStdout = StringIO()
  518. options.authOutput = newStdout
  519. self.assertRaises(SystemExit, options.parseOptions,
  520. ['--help-auth-type', 'anonymous'])
  521. self.assertIn(strcred.notSupportedWarning, newStdout.getvalue())
  522. __all__ = [
  523. "CheckerOptionsTests", "FileDBCheckerTests", "LimitingInterfacesTests",
  524. "SSHCheckerTests", "UnixCheckerTests", "AnonymousCheckerTests",
  525. "MemoryCheckerTests", "StrcredFunctionsTests", "PublicAPITests"
  526. ]