Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

checkers.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. # -*- test-case-name: twisted.conch.test.test_checkers -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Provide L{ICredentialsChecker} implementations to be used in Conch protocols.
  6. """
  7. import binascii
  8. import errno
  9. import sys
  10. from base64 import decodebytes
  11. from typing import IO, Callable, Iterable, Iterator, Mapping, Optional, Tuple, cast
  12. from zope.interface import Interface, implementer, providedBy
  13. from incremental import Version
  14. from typing_extensions import Literal, Protocol
  15. from twisted.conch import error
  16. from twisted.conch.ssh import keys
  17. from twisted.cred.checkers import ICredentialsChecker
  18. from twisted.cred.credentials import ISSHPrivateKey, IUsernamePassword
  19. from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
  20. from twisted.internet import defer
  21. from twisted.logger import Logger
  22. from twisted.plugins.cred_unix import verifyCryptedPassword
  23. from twisted.python import failure, reflect
  24. from twisted.python.deprecate import deprecatedModuleAttribute
  25. from twisted.python.filepath import FilePath
  26. from twisted.python.util import runAsEffectiveUser
  27. _log = Logger()
  28. class UserRecord(Tuple[str, str, int, int, str, str, str]):
  29. """
  30. A record in a UNIX-style password database. See L{pwd} for field details.
  31. This corresponds to the undocumented type L{pwd.struct_passwd}, but lacks named
  32. field accessors.
  33. """
  34. @property
  35. def pw_dir(self) -> str:
  36. ...
  37. class UserDB(Protocol):
  38. """
  39. A database of users by name, like the stdlib L{pwd} module.
  40. See L{twisted.python.fakepwd} for an in-memory implementation.
  41. """
  42. def getpwnam(self, username: str) -> UserRecord:
  43. """
  44. Lookup a user record by name.
  45. @raises KeyError: when no such user exists
  46. """
  47. pwd: Optional[UserDB]
  48. try:
  49. import pwd as _pwd
  50. except ImportError:
  51. pwd = None
  52. else:
  53. pwd = cast(UserDB, _pwd)
  54. try:
  55. import spwd as _spwd
  56. except ImportError:
  57. spwd = None
  58. else:
  59. spwd = _spwd
  60. class CryptedPasswordRecord(Protocol):
  61. """
  62. A sequence where the item at index 1 may be a crypted password.
  63. Both L{pwd.struct_passwd} and L{spwd.struct_spwd} conform to this protocol.
  64. """
  65. def __getitem__(self, index: Literal[1]) -> str:
  66. """
  67. Get the crypted password.
  68. """
  69. def _lookupUser(userdb: UserDB, username: bytes) -> UserRecord:
  70. """
  71. Lookup a user by name in a L{pwd}-style database.
  72. @param userdb: The user database.
  73. @param username: Identifying name in bytes. This will be decoded according
  74. to the filesystem encoding, as the L{pwd} module does internally.
  75. @raises KeyError: when the user doesn't exist
  76. """
  77. return userdb.getpwnam(username.decode(sys.getfilesystemencoding()))
  78. def _pwdGetByName(username: str) -> Optional[CryptedPasswordRecord]:
  79. """
  80. Look up a user in the /etc/passwd database using the pwd module. If the
  81. pwd module is not available, return None.
  82. @param username: the username of the user to return the passwd database
  83. information for.
  84. @returns: A L{pwd.struct_passwd}, where field 1 may contain a crypted
  85. password, or L{None} when the L{pwd} database is unavailable.
  86. @raises KeyError: when no such user exists
  87. """
  88. if pwd is None:
  89. return None
  90. return cast(CryptedPasswordRecord, pwd.getpwnam(username))
  91. def _shadowGetByName(username: str) -> Optional[CryptedPasswordRecord]:
  92. """
  93. Look up a user in the /etc/shadow database using the spwd module. If it is
  94. not available, return L{None}.
  95. @param username: the username of the user to return the shadow database
  96. information for.
  97. @type username: L{str}
  98. @returns: A L{spwd.struct_spwd}, where field 1 may contain a crypted
  99. password, or L{None} when the L{spwd} database is unavailable.
  100. @raises KeyError: when no such user exists
  101. """
  102. if spwd is not None:
  103. f = spwd.getspnam
  104. else:
  105. return None
  106. return cast(CryptedPasswordRecord, runAsEffectiveUser(0, 0, f, username))
  107. @implementer(ICredentialsChecker)
  108. class UNIXPasswordDatabase:
  109. """
  110. A checker which validates users out of the UNIX password databases, or
  111. databases of a compatible format.
  112. @ivar _getByNameFunctions: a C{list} of functions which are called in order
  113. to validate a user. The default value is such that the C{/etc/passwd}
  114. database will be tried first, followed by the C{/etc/shadow} database.
  115. """
  116. credentialInterfaces = (IUsernamePassword,)
  117. def __init__(self, getByNameFunctions=None):
  118. if getByNameFunctions is None:
  119. getByNameFunctions = [_pwdGetByName, _shadowGetByName]
  120. self._getByNameFunctions = getByNameFunctions
  121. def requestAvatarId(self, credentials):
  122. # We get bytes, but the Py3 pwd module uses str. So attempt to decode
  123. # it using the same method that CPython does for the file on disk.
  124. username = credentials.username.decode(sys.getfilesystemencoding())
  125. password = credentials.password.decode(sys.getfilesystemencoding())
  126. for func in self._getByNameFunctions:
  127. try:
  128. pwnam = func(username)
  129. except KeyError:
  130. return defer.fail(UnauthorizedLogin("invalid username"))
  131. else:
  132. if pwnam is not None:
  133. crypted = pwnam[1]
  134. if crypted == "":
  135. continue
  136. if verifyCryptedPassword(crypted, password):
  137. return defer.succeed(credentials.username)
  138. # fallback
  139. return defer.fail(UnauthorizedLogin("unable to verify password"))
  140. @implementer(ICredentialsChecker)
  141. class SSHPublicKeyDatabase:
  142. """
  143. Checker that authenticates SSH public keys, based on public keys listed in
  144. authorized_keys and authorized_keys2 files in user .ssh/ directories.
  145. """
  146. credentialInterfaces = (ISSHPrivateKey,)
  147. _userdb: UserDB = cast(UserDB, pwd)
  148. def requestAvatarId(self, credentials):
  149. d = defer.maybeDeferred(self.checkKey, credentials)
  150. d.addCallback(self._cbRequestAvatarId, credentials)
  151. d.addErrback(self._ebRequestAvatarId)
  152. return d
  153. def _cbRequestAvatarId(self, validKey, credentials):
  154. """
  155. Check whether the credentials themselves are valid, now that we know
  156. if the key matches the user.
  157. @param validKey: A boolean indicating whether or not the public key
  158. matches a key in the user's authorized_keys file.
  159. @param credentials: The credentials offered by the user.
  160. @type credentials: L{ISSHPrivateKey} provider
  161. @raise UnauthorizedLogin: (as a failure) if the key does not match the
  162. user in C{credentials}. Also raised if the user provides an invalid
  163. signature.
  164. @raise ValidPublicKey: (as a failure) if the key matches the user but
  165. the credentials do not include a signature. See
  166. L{error.ValidPublicKey} for more information.
  167. @return: The user's username, if authentication was successful.
  168. """
  169. if not validKey:
  170. return failure.Failure(UnauthorizedLogin("invalid key"))
  171. if not credentials.signature:
  172. return failure.Failure(error.ValidPublicKey())
  173. else:
  174. try:
  175. pubKey = keys.Key.fromString(credentials.blob)
  176. if pubKey.verify(credentials.signature, credentials.sigData):
  177. return credentials.username
  178. except Exception: # any error should be treated as a failed login
  179. _log.failure("Error while verifying key")
  180. return failure.Failure(UnauthorizedLogin("error while verifying key"))
  181. return failure.Failure(UnauthorizedLogin("unable to verify key"))
  182. def getAuthorizedKeysFiles(self, credentials):
  183. """
  184. Return a list of L{FilePath} instances for I{authorized_keys} files
  185. which might contain information about authorized keys for the given
  186. credentials.
  187. On OpenSSH servers, the default location of the file containing the
  188. list of authorized public keys is
  189. U{$HOME/.ssh/authorized_keys<http://www.openbsd.org/cgi-bin/man.cgi?query=sshd_config>}.
  190. I{$HOME/.ssh/authorized_keys2} is also returned, though it has been
  191. U{deprecated by OpenSSH since
  192. 2001<http://marc.info/?m=100508718416162>}.
  193. @return: A list of L{FilePath} instances to files with the authorized keys.
  194. """
  195. pwent = _lookupUser(self._userdb, credentials.username)
  196. root = FilePath(pwent.pw_dir).child(".ssh")
  197. files = ["authorized_keys", "authorized_keys2"]
  198. return [root.child(f) for f in files]
  199. def checkKey(self, credentials):
  200. """
  201. Retrieve files containing authorized keys and check against user
  202. credentials.
  203. """
  204. ouid, ogid = _lookupUser(self._userdb, credentials.username)[2:4]
  205. for filepath in self.getAuthorizedKeysFiles(credentials):
  206. if not filepath.exists():
  207. continue
  208. try:
  209. lines = filepath.open()
  210. except OSError as e:
  211. if e.errno == errno.EACCES:
  212. lines = runAsEffectiveUser(ouid, ogid, filepath.open)
  213. else:
  214. raise
  215. with lines:
  216. for l in lines:
  217. l2 = l.split()
  218. if len(l2) < 2:
  219. continue
  220. try:
  221. if decodebytes(l2[1]) == credentials.blob:
  222. return True
  223. except binascii.Error:
  224. continue
  225. return False
  226. def _ebRequestAvatarId(self, f):
  227. if not f.check(UnauthorizedLogin):
  228. _log.error(
  229. "Unauthorized login due to internal error: {error}", error=f.value
  230. )
  231. return failure.Failure(UnauthorizedLogin("unable to get avatar id"))
  232. return f
  233. @implementer(ICredentialsChecker)
  234. class SSHProtocolChecker:
  235. """
  236. SSHProtocolChecker is a checker that requires multiple authentications
  237. to succeed. To add a checker, call my registerChecker method with
  238. the checker and the interface.
  239. After each successful authenticate, I call my areDone method with the
  240. avatar id. To get a list of the successful credentials for an avatar id,
  241. use C{SSHProcotolChecker.successfulCredentials[avatarId]}. If L{areDone}
  242. returns True, the authentication has succeeded.
  243. """
  244. def __init__(self):
  245. self.checkers = {}
  246. self.successfulCredentials = {}
  247. @property
  248. def credentialInterfaces(self):
  249. return list(self.checkers.keys())
  250. def registerChecker(self, checker, *credentialInterfaces):
  251. if not credentialInterfaces:
  252. credentialInterfaces = checker.credentialInterfaces
  253. for credentialInterface in credentialInterfaces:
  254. self.checkers[credentialInterface] = checker
  255. def requestAvatarId(self, credentials):
  256. """
  257. Part of the L{ICredentialsChecker} interface. Called by a portal with
  258. some credentials to check if they'll authenticate a user. We check the
  259. interfaces that the credentials provide against our list of acceptable
  260. checkers. If one of them matches, we ask that checker to verify the
  261. credentials. If they're valid, we call our L{_cbGoodAuthentication}
  262. method to continue.
  263. @param credentials: the credentials the L{Portal} wants us to verify
  264. """
  265. ifac = providedBy(credentials)
  266. for i in ifac:
  267. c = self.checkers.get(i)
  268. if c is not None:
  269. d = defer.maybeDeferred(c.requestAvatarId, credentials)
  270. return d.addCallback(self._cbGoodAuthentication, credentials)
  271. return defer.fail(
  272. UnhandledCredentials(
  273. "No checker for %s" % ", ".join(map(reflect.qual, ifac))
  274. )
  275. )
  276. def _cbGoodAuthentication(self, avatarId, credentials):
  277. """
  278. Called if a checker has verified the credentials. We call our
  279. L{areDone} method to see if the whole of the successful authentications
  280. are enough. If they are, we return the avatar ID returned by the first
  281. checker.
  282. """
  283. if avatarId not in self.successfulCredentials:
  284. self.successfulCredentials[avatarId] = []
  285. self.successfulCredentials[avatarId].append(credentials)
  286. if self.areDone(avatarId):
  287. del self.successfulCredentials[avatarId]
  288. return avatarId
  289. else:
  290. raise error.NotEnoughAuthentication()
  291. def areDone(self, avatarId):
  292. """
  293. Override to determine if the authentication is finished for a given
  294. avatarId.
  295. @param avatarId: the avatar returned by the first checker. For
  296. this checker to function correctly, all the checkers must
  297. return the same avatar ID.
  298. """
  299. return True
  300. deprecatedModuleAttribute(
  301. Version("Twisted", 15, 0, 0),
  302. (
  303. "Please use twisted.conch.checkers.SSHPublicKeyChecker, "
  304. "initialized with an instance of "
  305. "twisted.conch.checkers.UNIXAuthorizedKeysFiles instead."
  306. ),
  307. __name__,
  308. "SSHPublicKeyDatabase",
  309. )
  310. class IAuthorizedKeysDB(Interface):
  311. """
  312. An object that provides valid authorized ssh keys mapped to usernames.
  313. @since: 15.0
  314. """
  315. def getAuthorizedKeys(avatarId):
  316. """
  317. Gets an iterable of authorized keys that are valid for the given
  318. C{avatarId}.
  319. @param avatarId: the ID of the avatar
  320. @type avatarId: valid return value of
  321. L{twisted.cred.checkers.ICredentialsChecker.requestAvatarId}
  322. @return: an iterable of L{twisted.conch.ssh.keys.Key}
  323. """
  324. def readAuthorizedKeyFile(
  325. fileobj: IO[bytes], parseKey: Callable[[bytes], keys.Key] = keys.Key.fromString
  326. ) -> Iterator[keys.Key]:
  327. """
  328. Reads keys from an authorized keys file. Any non-comment line that cannot
  329. be parsed as a key will be ignored, although that particular line will
  330. be logged.
  331. @param fileobj: something from which to read lines which can be parsed
  332. as keys
  333. @param parseKey: a callable that takes bytes and returns a
  334. L{twisted.conch.ssh.keys.Key}, mainly to be used for testing. The
  335. default is L{twisted.conch.ssh.keys.Key.fromString}.
  336. @return: an iterable of L{twisted.conch.ssh.keys.Key}
  337. @since: 15.0
  338. """
  339. for line in fileobj:
  340. line = line.strip()
  341. if line and not line.startswith(b"#"): # for comments
  342. try:
  343. yield parseKey(line)
  344. except keys.BadKeyError as e:
  345. _log.error(
  346. "Unable to parse line {line!r} as a key: {error!s}",
  347. line=line,
  348. error=e,
  349. )
  350. def _keysFromFilepaths(
  351. filepaths: Iterable[FilePath], parseKey: Callable[[bytes], keys.Key]
  352. ) -> Iterable[keys.Key]:
  353. """
  354. Helper function that turns an iterable of filepaths into a generator of
  355. keys. If any file cannot be read, a message is logged but it is
  356. otherwise ignored.
  357. @param filepaths: iterable of L{twisted.python.filepath.FilePath}.
  358. @type filepaths: iterable
  359. @param parseKey: a callable that takes a string and returns a
  360. L{twisted.conch.ssh.keys.Key}
  361. @type parseKey: L{callable}
  362. @return: generator of L{twisted.conch.ssh.keys.Key}
  363. @since: 15.0
  364. """
  365. for fp in filepaths:
  366. if fp.exists():
  367. try:
  368. with fp.open() as f:
  369. yield from readAuthorizedKeyFile(f, parseKey)
  370. except OSError as e:
  371. _log.error("Unable to read {path!r}: {error!s}", path=fp.path, error=e)
  372. @implementer(IAuthorizedKeysDB)
  373. class InMemorySSHKeyDB:
  374. """
  375. Object that provides SSH public keys based on a dictionary of usernames
  376. mapped to L{twisted.conch.ssh.keys.Key}s.
  377. @since: 15.0
  378. """
  379. def __init__(self, mapping: Mapping[bytes, Iterable[keys.Key]]) -> None:
  380. """
  381. Initializes a new L{InMemorySSHKeyDB}.
  382. @param mapping: mapping of usernames to iterables of
  383. L{twisted.conch.ssh.keys.Key}s
  384. """
  385. self._mapping = mapping
  386. def getAuthorizedKeys(self, username: bytes) -> Iterable[keys.Key]:
  387. """
  388. Look up the authorized keys for a user.
  389. @param username: Name of the user
  390. """
  391. return self._mapping.get(username, [])
  392. @implementer(IAuthorizedKeysDB)
  393. class UNIXAuthorizedKeysFiles:
  394. """
  395. Object that provides SSH public keys based on public keys listed in
  396. authorized_keys and authorized_keys2 files in UNIX user .ssh/ directories.
  397. If any of the files cannot be read, a message is logged but that file is
  398. otherwise ignored.
  399. @since: 15.0
  400. """
  401. _userdb: UserDB
  402. def __init__(
  403. self,
  404. userdb: Optional[UserDB] = None,
  405. parseKey: Callable[[bytes], keys.Key] = keys.Key.fromString,
  406. ):
  407. """
  408. Initializes a new L{UNIXAuthorizedKeysFiles}.
  409. @param userdb: access to the Unix user account and password database
  410. (default is the Python module L{pwd}, if available)
  411. @param parseKey: a callable that takes a string and returns a
  412. L{twisted.conch.ssh.keys.Key}, mainly to be used for testing. The
  413. default is L{twisted.conch.ssh.keys.Key.fromString}.
  414. """
  415. if userdb is not None:
  416. self._userdb = userdb
  417. elif pwd is not None:
  418. self._userdb = pwd
  419. else:
  420. raise ValueError("No pwd module found, and no userdb argument passed.")
  421. self._parseKey = parseKey
  422. def getAuthorizedKeys(self, username: bytes) -> Iterable[keys.Key]:
  423. try:
  424. passwd = _lookupUser(self._userdb, username)
  425. except KeyError:
  426. return ()
  427. root = FilePath(passwd.pw_dir).child(".ssh")
  428. files = ["authorized_keys", "authorized_keys2"]
  429. return _keysFromFilepaths((root.child(f) for f in files), self._parseKey)
  430. @implementer(ICredentialsChecker)
  431. class SSHPublicKeyChecker:
  432. """
  433. Checker that authenticates SSH public keys, based on public keys listed in
  434. authorized_keys and authorized_keys2 files in user .ssh/ directories.
  435. Initializing this checker with a L{UNIXAuthorizedKeysFiles} should be
  436. used instead of L{twisted.conch.checkers.SSHPublicKeyDatabase}.
  437. @since: 15.0
  438. """
  439. credentialInterfaces = (ISSHPrivateKey,)
  440. def __init__(self, keydb: IAuthorizedKeysDB) -> None:
  441. """
  442. Initializes a L{SSHPublicKeyChecker}.
  443. @param keydb: a provider of L{IAuthorizedKeysDB}
  444. """
  445. self._keydb = keydb
  446. def requestAvatarId(self, credentials):
  447. d = defer.execute(self._sanityCheckKey, credentials)
  448. d.addCallback(self._checkKey, credentials)
  449. d.addCallback(self._verifyKey, credentials)
  450. return d
  451. def _sanityCheckKey(self, credentials):
  452. """
  453. Checks whether the provided credentials are a valid SSH key with a
  454. signature (does not actually verify the signature).
  455. @param credentials: the credentials offered by the user
  456. @type credentials: L{ISSHPrivateKey} provider
  457. @raise ValidPublicKey: the credentials do not include a signature. See
  458. L{error.ValidPublicKey} for more information.
  459. @raise BadKeyError: The key included with the credentials is not
  460. recognized as a key.
  461. @return: the key in the credentials
  462. @rtype: L{twisted.conch.ssh.keys.Key}
  463. """
  464. if not credentials.signature:
  465. raise error.ValidPublicKey()
  466. return keys.Key.fromString(credentials.blob)
  467. def _checkKey(self, pubKey, credentials):
  468. """
  469. Checks the public key against all authorized keys (if any) for the
  470. user.
  471. @param pubKey: the key in the credentials (just to prevent it from
  472. having to be calculated again)
  473. @type pubKey:
  474. @param credentials: the credentials offered by the user
  475. @type credentials: L{ISSHPrivateKey} provider
  476. @raise UnauthorizedLogin: If the key is not authorized, or if there
  477. was any error obtaining a list of authorized keys for the user.
  478. @return: C{pubKey} if the key is authorized
  479. @rtype: L{twisted.conch.ssh.keys.Key}
  480. """
  481. if any(
  482. key == pubKey for key in self._keydb.getAuthorizedKeys(credentials.username)
  483. ):
  484. return pubKey
  485. raise UnauthorizedLogin("Key not authorized")
  486. def _verifyKey(self, pubKey, credentials):
  487. """
  488. Checks whether the credentials themselves are valid, now that we know
  489. if the key matches the user.
  490. @param pubKey: the key in the credentials (just to prevent it from
  491. having to be calculated again)
  492. @type pubKey: L{twisted.conch.ssh.keys.Key}
  493. @param credentials: the credentials offered by the user
  494. @type credentials: L{ISSHPrivateKey} provider
  495. @raise UnauthorizedLogin: If the key signature is invalid or there
  496. was any error verifying the signature.
  497. @return: The user's username, if authentication was successful
  498. @rtype: L{bytes}
  499. """
  500. try:
  501. if pubKey.verify(credentials.signature, credentials.sigData):
  502. return credentials.username
  503. except Exception as e: # Any error should be treated as a failed login
  504. raise UnauthorizedLogin("Error while verifying key") from e
  505. raise UnauthorizedLogin("Key signature invalid.")