test_digestauth.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.cred._digest} and the associated bits in
  5. L{twisted.cred.credentials}.
  6. """
  7. from __future__ import division, absolute_import
  8. import base64
  9. from binascii import hexlify
  10. from hashlib import md5, sha1
  11. from zope.interface.verify import verifyObject
  12. from twisted.trial.unittest import TestCase
  13. from twisted.internet.address import IPv4Address
  14. from twisted.cred.error import LoginFailed
  15. from twisted.cred.credentials import calcHA1, calcHA2, IUsernameDigestHash
  16. from twisted.cred.credentials import calcResponse, DigestCredentialFactory
  17. from twisted.python.compat import networkString
  18. def b64encode(s):
  19. return base64.b64encode(s).strip()
  20. class FakeDigestCredentialFactory(DigestCredentialFactory):
  21. """
  22. A Fake Digest Credential Factory that generates a predictable
  23. nonce and opaque
  24. """
  25. def __init__(self, *args, **kwargs):
  26. super(FakeDigestCredentialFactory, self).__init__(*args, **kwargs)
  27. self.privateKey = b"0"
  28. def _generateNonce(self):
  29. """
  30. Generate a static nonce
  31. """
  32. return b'178288758716122392881254770685'
  33. def _getTime(self):
  34. """
  35. Return a stable time
  36. """
  37. return 0
  38. class DigestAuthTests(TestCase):
  39. """
  40. L{TestCase} mixin class which defines a number of tests for
  41. L{DigestCredentialFactory}. Because this mixin defines C{setUp}, it
  42. must be inherited before L{TestCase}.
  43. """
  44. def setUp(self):
  45. """
  46. Create a DigestCredentialFactory for testing
  47. """
  48. self.username = b"foobar"
  49. self.password = b"bazquux"
  50. self.realm = b"test realm"
  51. self.algorithm = b"md5"
  52. self.cnonce = b"29fc54aa1641c6fa0e151419361c8f23"
  53. self.qop = b"auth"
  54. self.uri = b"/write/"
  55. self.clientAddress = IPv4Address('TCP', '10.2.3.4', 43125)
  56. self.method = b'GET'
  57. self.credentialFactory = DigestCredentialFactory(
  58. self.algorithm, self.realm)
  59. def test_MD5HashA1(self, _algorithm=b'md5', _hash=md5):
  60. """
  61. L{calcHA1} accepts the C{'md5'} algorithm and returns an MD5 hash of
  62. its parameters, excluding the nonce and cnonce.
  63. """
  64. nonce = b'abc123xyz'
  65. hashA1 = calcHA1(_algorithm, self.username, self.realm, self.password,
  66. nonce, self.cnonce)
  67. a1 = b":".join((self.username, self.realm, self.password))
  68. expected = hexlify(_hash(a1).digest())
  69. self.assertEqual(hashA1, expected)
  70. def test_MD5SessionHashA1(self):
  71. """
  72. L{calcHA1} accepts the C{'md5-sess'} algorithm and returns an MD5 hash
  73. of its parameters, including the nonce and cnonce.
  74. """
  75. nonce = b'xyz321abc'
  76. hashA1 = calcHA1(b'md5-sess', self.username, self.realm, self.password,
  77. nonce, self.cnonce)
  78. a1 = self.username + b':' + self.realm + b':' + self.password
  79. ha1 = hexlify(md5(a1).digest())
  80. a1 = ha1 + b':' + nonce + b':' + self.cnonce
  81. expected = hexlify(md5(a1).digest())
  82. self.assertEqual(hashA1, expected)
  83. def test_SHAHashA1(self):
  84. """
  85. L{calcHA1} accepts the C{'sha'} algorithm and returns a SHA hash of its
  86. parameters, excluding the nonce and cnonce.
  87. """
  88. self.test_MD5HashA1(b'sha', sha1)
  89. def test_MD5HashA2Auth(self, _algorithm=b'md5', _hash=md5):
  90. """
  91. L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of
  92. its arguments, excluding the entity hash for QOP other than
  93. C{'auth-int'}.
  94. """
  95. method = b'GET'
  96. hashA2 = calcHA2(_algorithm, method, self.uri, b'auth', None)
  97. a2 = method + b':' + self.uri
  98. expected = hexlify(_hash(a2).digest())
  99. self.assertEqual(hashA2, expected)
  100. def test_MD5HashA2AuthInt(self, _algorithm=b'md5', _hash=md5):
  101. """
  102. L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of
  103. its arguments, including the entity hash for QOP of C{'auth-int'}.
  104. """
  105. method = b'GET'
  106. hentity = b'foobarbaz'
  107. hashA2 = calcHA2(_algorithm, method, self.uri, b'auth-int', hentity)
  108. a2 = method + b':' + self.uri + b':' + hentity
  109. expected = hexlify(_hash(a2).digest())
  110. self.assertEqual(hashA2, expected)
  111. def test_MD5SessHashA2Auth(self):
  112. """
  113. L{calcHA2} accepts the C{'md5-sess'} algorithm and QOP of C{'auth'} and
  114. returns the same value as it does for the C{'md5'} algorithm.
  115. """
  116. self.test_MD5HashA2Auth(b'md5-sess')
  117. def test_MD5SessHashA2AuthInt(self):
  118. """
  119. L{calcHA2} accepts the C{'md5-sess'} algorithm and QOP of C{'auth-int'}
  120. and returns the same value as it does for the C{'md5'} algorithm.
  121. """
  122. self.test_MD5HashA2AuthInt(b'md5-sess')
  123. def test_SHAHashA2Auth(self):
  124. """
  125. L{calcHA2} accepts the C{'sha'} algorithm and returns a SHA hash of
  126. its arguments, excluding the entity hash for QOP other than
  127. C{'auth-int'}.
  128. """
  129. self.test_MD5HashA2Auth(b'sha', sha1)
  130. def test_SHAHashA2AuthInt(self):
  131. """
  132. L{calcHA2} accepts the C{'sha'} algorithm and returns a SHA hash of
  133. its arguments, including the entity hash for QOP of C{'auth-int'}.
  134. """
  135. self.test_MD5HashA2AuthInt(b'sha', sha1)
  136. def test_MD5HashResponse(self, _algorithm=b'md5', _hash=md5):
  137. """
  138. L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash
  139. of its parameters, excluding the nonce count, client nonce, and QoP
  140. value if the nonce count and client nonce are L{None}
  141. """
  142. hashA1 = b'abc123'
  143. hashA2 = b'789xyz'
  144. nonce = b'lmnopq'
  145. response = hashA1 + b':' + nonce + b':' + hashA2
  146. expected = hexlify(_hash(response).digest())
  147. digest = calcResponse(hashA1, hashA2, _algorithm, nonce, None, None,
  148. None)
  149. self.assertEqual(expected, digest)
  150. def test_MD5SessionHashResponse(self):
  151. """
  152. L{calcResponse} accepts the C{'md5-sess'} algorithm and returns an MD5
  153. hash of its parameters, excluding the nonce count, client nonce, and
  154. QoP value if the nonce count and client nonce are L{None}
  155. """
  156. self.test_MD5HashResponse(b'md5-sess')
  157. def test_SHAHashResponse(self):
  158. """
  159. L{calcResponse} accepts the C{'sha'} algorithm and returns a SHA hash
  160. of its parameters, excluding the nonce count, client nonce, and QoP
  161. value if the nonce count and client nonce are L{None}
  162. """
  163. self.test_MD5HashResponse(b'sha', sha1)
  164. def test_MD5HashResponseExtra(self, _algorithm=b'md5', _hash=md5):
  165. """
  166. L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash
  167. of its parameters, including the nonce count, client nonce, and QoP
  168. value if they are specified.
  169. """
  170. hashA1 = b'abc123'
  171. hashA2 = b'789xyz'
  172. nonce = b'lmnopq'
  173. nonceCount = b'00000004'
  174. clientNonce = b'abcxyz123'
  175. qop = b'auth'
  176. response = hashA1 + b':' + nonce + b':' + nonceCount + b':' +\
  177. clientNonce + b':' + qop + b':' + hashA2
  178. expected = hexlify(_hash(response).digest())
  179. digest = calcResponse(
  180. hashA1, hashA2, _algorithm, nonce, nonceCount, clientNonce, qop)
  181. self.assertEqual(expected, digest)
  182. def test_MD5SessionHashResponseExtra(self):
  183. """
  184. L{calcResponse} accepts the C{'md5-sess'} algorithm and returns an MD5
  185. hash of its parameters, including the nonce count, client nonce, and
  186. QoP value if they are specified.
  187. """
  188. self.test_MD5HashResponseExtra(b'md5-sess')
  189. def test_SHAHashResponseExtra(self):
  190. """
  191. L{calcResponse} accepts the C{'sha'} algorithm and returns a SHA hash
  192. of its parameters, including the nonce count, client nonce, and QoP
  193. value if they are specified.
  194. """
  195. self.test_MD5HashResponseExtra(b'sha', sha1)
  196. def formatResponse(self, quotes=True, **kw):
  197. """
  198. Format all given keyword arguments and their values suitably for use as
  199. the value of an HTTP header.
  200. @types quotes: C{bool}
  201. @param quotes: A flag indicating whether to quote the values of each
  202. field in the response.
  203. @param **kw: Keywords and C{bytes} values which will be treated as field
  204. name/value pairs to include in the result.
  205. @rtype: C{bytes}
  206. @return: The given fields formatted for use as an HTTP header value.
  207. """
  208. if 'username' not in kw:
  209. kw['username'] = self.username
  210. if 'realm' not in kw:
  211. kw['realm'] = self.realm
  212. if 'algorithm' not in kw:
  213. kw['algorithm'] = self.algorithm
  214. if 'qop' not in kw:
  215. kw['qop'] = self.qop
  216. if 'cnonce' not in kw:
  217. kw['cnonce'] = self.cnonce
  218. if 'uri' not in kw:
  219. kw['uri'] = self.uri
  220. if quotes:
  221. quote = b'"'
  222. else:
  223. quote = b''
  224. return b', '.join([
  225. b"".join((networkString(k), b"=", quote, v, quote))
  226. for (k, v)
  227. in kw.items()
  228. if v is not None])
  229. def getDigestResponse(self, challenge, ncount):
  230. """
  231. Calculate the response for the given challenge
  232. """
  233. nonce = challenge.get('nonce')
  234. algo = challenge.get('algorithm').lower()
  235. qop = challenge.get('qop')
  236. ha1 = calcHA1(
  237. algo, self.username, self.realm, self.password, nonce, self.cnonce)
  238. ha2 = calcHA2(algo, b"GET", self.uri, qop, None)
  239. expected = calcResponse(
  240. ha1, ha2, algo, nonce, ncount, self.cnonce, qop)
  241. return expected
  242. def test_response(self, quotes=True):
  243. """
  244. L{DigestCredentialFactory.decode} accepts a digest challenge response
  245. and parses it into an L{IUsernameHashedPassword} provider.
  246. """
  247. challenge = self.credentialFactory.getChallenge(
  248. self.clientAddress.host)
  249. nc = b"00000001"
  250. clientResponse = self.formatResponse(
  251. quotes=quotes,
  252. nonce=challenge['nonce'],
  253. response=self.getDigestResponse(challenge, nc),
  254. nc=nc,
  255. opaque=challenge['opaque'])
  256. creds = self.credentialFactory.decode(
  257. clientResponse, self.method, self.clientAddress.host)
  258. self.assertTrue(creds.checkPassword(self.password))
  259. self.assertFalse(creds.checkPassword(self.password + b'wrong'))
  260. def test_responseWithoutQuotes(self):
  261. """
  262. L{DigestCredentialFactory.decode} accepts a digest challenge response
  263. which does not quote the values of its fields and parses it into an
  264. L{IUsernameHashedPassword} provider in the same way it would a
  265. response which included quoted field values.
  266. """
  267. self.test_response(False)
  268. def test_responseWithCommaURI(self):
  269. """
  270. L{DigestCredentialFactory.decode} accepts a digest challenge response
  271. which quotes the values of its fields and includes a C{b","} in the URI
  272. field.
  273. """
  274. self.uri = b"/some,path/"
  275. self.test_response(True)
  276. def test_caseInsensitiveAlgorithm(self):
  277. """
  278. The case of the algorithm value in the response is ignored when
  279. checking the credentials.
  280. """
  281. self.algorithm = b'MD5'
  282. self.test_response()
  283. def test_md5DefaultAlgorithm(self):
  284. """
  285. The algorithm defaults to MD5 if it is not supplied in the response.
  286. """
  287. self.algorithm = None
  288. self.test_response()
  289. def test_responseWithoutClientIP(self):
  290. """
  291. L{DigestCredentialFactory.decode} accepts a digest challenge response
  292. even if the client address it is passed is L{None}.
  293. """
  294. challenge = self.credentialFactory.getChallenge(None)
  295. nc = b"00000001"
  296. clientResponse = self.formatResponse(
  297. nonce=challenge['nonce'],
  298. response=self.getDigestResponse(challenge, nc),
  299. nc=nc,
  300. opaque=challenge['opaque'])
  301. creds = self.credentialFactory.decode(clientResponse, self.method,
  302. None)
  303. self.assertTrue(creds.checkPassword(self.password))
  304. self.assertFalse(creds.checkPassword(self.password + b'wrong'))
  305. def test_multiResponse(self):
  306. """
  307. L{DigestCredentialFactory.decode} handles multiple responses to a
  308. single challenge.
  309. """
  310. challenge = self.credentialFactory.getChallenge(
  311. self.clientAddress.host)
  312. nc = b"00000001"
  313. clientResponse = self.formatResponse(
  314. nonce=challenge['nonce'],
  315. response=self.getDigestResponse(challenge, nc),
  316. nc=nc,
  317. opaque=challenge['opaque'])
  318. creds = self.credentialFactory.decode(clientResponse, self.method,
  319. self.clientAddress.host)
  320. self.assertTrue(creds.checkPassword(self.password))
  321. self.assertFalse(creds.checkPassword(self.password + b'wrong'))
  322. nc = b"00000002"
  323. clientResponse = self.formatResponse(
  324. nonce=challenge['nonce'],
  325. response=self.getDigestResponse(challenge, nc),
  326. nc=nc,
  327. opaque=challenge['opaque'])
  328. creds = self.credentialFactory.decode(clientResponse, self.method,
  329. self.clientAddress.host)
  330. self.assertTrue(creds.checkPassword(self.password))
  331. self.assertFalse(creds.checkPassword(self.password + b'wrong'))
  332. def test_failsWithDifferentMethod(self):
  333. """
  334. L{DigestCredentialFactory.decode} returns an L{IUsernameHashedPassword}
  335. provider which rejects a correct password for the given user if the
  336. challenge response request is made using a different HTTP method than
  337. was used to request the initial challenge.
  338. """
  339. challenge = self.credentialFactory.getChallenge(
  340. self.clientAddress.host)
  341. nc = b"00000001"
  342. clientResponse = self.formatResponse(
  343. nonce=challenge['nonce'],
  344. response=self.getDigestResponse(challenge, nc),
  345. nc=nc,
  346. opaque=challenge['opaque'])
  347. creds = self.credentialFactory.decode(clientResponse, b'POST',
  348. self.clientAddress.host)
  349. self.assertFalse(creds.checkPassword(self.password))
  350. self.assertFalse(creds.checkPassword(self.password + b'wrong'))
  351. def test_noUsername(self):
  352. """
  353. L{DigestCredentialFactory.decode} raises L{LoginFailed} if the response
  354. has no username field or if the username field is empty.
  355. """
  356. # Check for no username
  357. e = self.assertRaises(
  358. LoginFailed,
  359. self.credentialFactory.decode,
  360. self.formatResponse(username=None),
  361. self.method, self.clientAddress.host)
  362. self.assertEqual(str(e), "Invalid response, no username given.")
  363. # Check for an empty username
  364. e = self.assertRaises(
  365. LoginFailed,
  366. self.credentialFactory.decode,
  367. self.formatResponse(username=b""),
  368. self.method, self.clientAddress.host)
  369. self.assertEqual(str(e), "Invalid response, no username given.")
  370. def test_noNonce(self):
  371. """
  372. L{DigestCredentialFactory.decode} raises L{LoginFailed} if the response
  373. has no nonce.
  374. """
  375. e = self.assertRaises(
  376. LoginFailed,
  377. self.credentialFactory.decode,
  378. self.formatResponse(opaque=b"abc123"),
  379. self.method, self.clientAddress.host)
  380. self.assertEqual(str(e), "Invalid response, no nonce given.")
  381. def test_noOpaque(self):
  382. """
  383. L{DigestCredentialFactory.decode} raises L{LoginFailed} if the response
  384. has no opaque.
  385. """
  386. e = self.assertRaises(
  387. LoginFailed,
  388. self.credentialFactory.decode,
  389. self.formatResponse(),
  390. self.method, self.clientAddress.host)
  391. self.assertEqual(str(e), "Invalid response, no opaque given.")
  392. def test_checkHash(self):
  393. """
  394. L{DigestCredentialFactory.decode} returns an L{IUsernameDigestHash}
  395. provider which can verify a hash of the form 'username:realm:password'.
  396. """
  397. challenge = self.credentialFactory.getChallenge(
  398. self.clientAddress.host)
  399. nc = b"00000001"
  400. clientResponse = self.formatResponse(
  401. nonce=challenge['nonce'],
  402. response=self.getDigestResponse(challenge, nc),
  403. nc=nc,
  404. opaque=challenge['opaque'])
  405. creds = self.credentialFactory.decode(clientResponse, self.method,
  406. self.clientAddress.host)
  407. self.assertTrue(verifyObject(IUsernameDigestHash, creds))
  408. cleartext = self.username + b":" + self.realm + b":" + self.password
  409. hash = md5(cleartext)
  410. self.assertTrue(creds.checkHash(hexlify(hash.digest())))
  411. hash.update(b'wrong')
  412. self.assertFalse(creds.checkHash(hexlify(hash.digest())))
  413. def test_invalidOpaque(self):
  414. """
  415. L{DigestCredentialFactory.decode} raises L{LoginFailed} when the opaque
  416. value does not contain all the required parts.
  417. """
  418. credentialFactory = FakeDigestCredentialFactory(self.algorithm,
  419. self.realm)
  420. challenge = credentialFactory.getChallenge(self.clientAddress.host)
  421. exc = self.assertRaises(
  422. LoginFailed,
  423. credentialFactory._verifyOpaque,
  424. b'badOpaque',
  425. challenge['nonce'],
  426. self.clientAddress.host)
  427. self.assertEqual(str(exc), 'Invalid response, invalid opaque value')
  428. badOpaque = b'foo-' + b64encode(b'nonce,clientip')
  429. exc = self.assertRaises(
  430. LoginFailed,
  431. credentialFactory._verifyOpaque,
  432. badOpaque,
  433. challenge['nonce'],
  434. self.clientAddress.host)
  435. self.assertEqual(str(exc), 'Invalid response, invalid opaque value')
  436. exc = self.assertRaises(
  437. LoginFailed,
  438. credentialFactory._verifyOpaque,
  439. b'',
  440. challenge['nonce'],
  441. self.clientAddress.host)
  442. self.assertEqual(str(exc), 'Invalid response, invalid opaque value')
  443. badOpaque = b'foo-' + b64encode(
  444. b",".join((challenge['nonce'],
  445. networkString(self.clientAddress.host),
  446. b"foobar")))
  447. exc = self.assertRaises(
  448. LoginFailed,
  449. credentialFactory._verifyOpaque,
  450. badOpaque,
  451. challenge['nonce'],
  452. self.clientAddress.host)
  453. self.assertEqual(
  454. str(exc), 'Invalid response, invalid opaque/time values')
  455. def test_incompatibleNonce(self):
  456. """
  457. L{DigestCredentialFactory.decode} raises L{LoginFailed} when the given
  458. nonce from the response does not match the nonce encoded in the opaque.
  459. """
  460. credentialFactory = FakeDigestCredentialFactory(self.algorithm,
  461. self.realm)
  462. challenge = credentialFactory.getChallenge(self.clientAddress.host)
  463. badNonceOpaque = credentialFactory._generateOpaque(
  464. b'1234567890',
  465. self.clientAddress.host)
  466. exc = self.assertRaises(
  467. LoginFailed,
  468. credentialFactory._verifyOpaque,
  469. badNonceOpaque,
  470. challenge['nonce'],
  471. self.clientAddress.host)
  472. self.assertEqual(
  473. str(exc),
  474. 'Invalid response, incompatible opaque/nonce values')
  475. exc = self.assertRaises(
  476. LoginFailed,
  477. credentialFactory._verifyOpaque,
  478. badNonceOpaque,
  479. b'',
  480. self.clientAddress.host)
  481. self.assertEqual(
  482. str(exc),
  483. 'Invalid response, incompatible opaque/nonce values')
  484. def test_incompatibleClientIP(self):
  485. """
  486. L{DigestCredentialFactory.decode} raises L{LoginFailed} when the
  487. request comes from a client IP other than what is encoded in the
  488. opaque.
  489. """
  490. credentialFactory = FakeDigestCredentialFactory(self.algorithm,
  491. self.realm)
  492. challenge = credentialFactory.getChallenge(self.clientAddress.host)
  493. badAddress = '10.0.0.1'
  494. # Sanity check
  495. self.assertNotEqual(self.clientAddress.host, badAddress)
  496. badNonceOpaque = credentialFactory._generateOpaque(
  497. challenge['nonce'], badAddress)
  498. self.assertRaises(
  499. LoginFailed,
  500. credentialFactory._verifyOpaque,
  501. badNonceOpaque,
  502. challenge['nonce'],
  503. self.clientAddress.host)
  504. def test_oldNonce(self):
  505. """
  506. L{DigestCredentialFactory.decode} raises L{LoginFailed} when the given
  507. opaque is older than C{DigestCredentialFactory.CHALLENGE_LIFETIME_SECS}
  508. """
  509. credentialFactory = FakeDigestCredentialFactory(self.algorithm,
  510. self.realm)
  511. challenge = credentialFactory.getChallenge(self.clientAddress.host)
  512. key = b",".join((challenge['nonce'],
  513. networkString(self.clientAddress.host),
  514. b'-137876876'))
  515. digest = hexlify(md5(key + credentialFactory.privateKey).digest())
  516. ekey = b64encode(key)
  517. oldNonceOpaque = b"-".join((digest, ekey.strip(b'\n')))
  518. self.assertRaises(
  519. LoginFailed,
  520. credentialFactory._verifyOpaque,
  521. oldNonceOpaque,
  522. challenge['nonce'],
  523. self.clientAddress.host)
  524. def test_mismatchedOpaqueChecksum(self):
  525. """
  526. L{DigestCredentialFactory.decode} raises L{LoginFailed} when the opaque
  527. checksum fails verification.
  528. """
  529. credentialFactory = FakeDigestCredentialFactory(self.algorithm,
  530. self.realm)
  531. challenge = credentialFactory.getChallenge(self.clientAddress.host)
  532. key = b",".join((challenge['nonce'],
  533. networkString(self.clientAddress.host),
  534. b'0'))
  535. digest = hexlify(md5(key + b'this is not the right pkey').digest())
  536. badChecksum = b"-".join((digest, b64encode(key)))
  537. self.assertRaises(
  538. LoginFailed,
  539. credentialFactory._verifyOpaque,
  540. badChecksum,
  541. challenge['nonce'],
  542. self.clientAddress.host)
  543. def test_incompatibleCalcHA1Options(self):
  544. """
  545. L{calcHA1} raises L{TypeError} when any of the pszUsername, pszRealm,
  546. or pszPassword arguments are specified with the preHA1 keyword
  547. argument.
  548. """
  549. arguments = (
  550. (b"user", b"realm", b"password", b"preHA1"),
  551. (None, b"realm", None, b"preHA1"),
  552. (None, None, b"password", b"preHA1"),
  553. )
  554. for pszUsername, pszRealm, pszPassword, preHA1 in arguments:
  555. self.assertRaises(
  556. TypeError,
  557. calcHA1,
  558. b"md5",
  559. pszUsername,
  560. pszRealm,
  561. pszPassword,
  562. b"nonce",
  563. b"cnonce",
  564. preHA1=preHA1)
  565. def test_noNewlineOpaque(self):
  566. """
  567. L{DigestCredentialFactory._generateOpaque} returns a value without
  568. newlines, regardless of the length of the nonce.
  569. """
  570. opaque = self.credentialFactory._generateOpaque(
  571. b"long nonce " * 10, None)
  572. self.assertNotIn(b'\n', opaque)