authorizers.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. #!/usr/bin/env python
  2. # $Id: authorizers.py 1171 2013-02-19 10:13:09Z g.rodola $
  3. # ======================================================================
  4. # Copyright (C) 2007-2013 Giampaolo Rodola' <g.rodola@gmail.com>
  5. #
  6. # All Rights Reserved
  7. #
  8. # Permission is hereby granted, free of charge, to any person
  9. # obtaining a copy of this software and associated documentation
  10. # files (the "Software"), to deal in the Software without
  11. # restriction, including without limitation the rights to use,
  12. # copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. # copies of the Software, and to permit persons to whom the
  14. # Software is furnished to do so, subject to the following
  15. # conditions:
  16. #
  17. # The above copyright notice and this permission notice shall be
  18. # included in all copies or substantial portions of the Software.
  19. #
  20. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  22. # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  24. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  25. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  26. # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  27. # OTHER DEALINGS IN THE SOFTWARE.
  28. #
  29. # ======================================================================
  30. """An "authorizer" is a class handling authentications and permissions
  31. of the FTP server. It is used by pyftpdlib.handlers.FTPHandler
  32. class for:
  33. - verifying user password
  34. - getting user home directory
  35. - checking user permissions when a filesystem read/write event occurs
  36. - changing user when accessing the filesystem
  37. DummyAuthorizer is the main class which handles virtual users.
  38. UnixAuthorizer and WindowsAuthorizer are platform specific and
  39. interact with UNIX and Windows password database.
  40. """
  41. import os
  42. import warnings
  43. import errno
  44. import sys
  45. from pyftpdlib._compat import PY3, unicode, getcwdu
  46. __all__ = ['DummyAuthorizer',
  47. #'BaseUnixAuthorizer', 'UnixAuthorizer',
  48. #'BaseWindowsAuthorizer', 'WindowsAuthorizer',
  49. ]
  50. # ===================================================================
  51. # --- exceptions
  52. # ===================================================================
  53. class AuthorizerError(Exception):
  54. """Base class for authorizer exceptions."""
  55. class AuthenticationFailed(Exception):
  56. """Exception raised when authentication fails for any reason."""
  57. # ===================================================================
  58. # --- base class
  59. # ===================================================================
  60. class DummyAuthorizer(object):
  61. """Basic "dummy" authorizer class, suitable for subclassing to
  62. create your own custom authorizers.
  63. An "authorizer" is a class handling authentications and permissions
  64. of the FTP server. It is used inside FTPHandler class for verifying
  65. user's password, getting users home directory, checking user
  66. permissions when a file read/write event occurs and changing user
  67. before accessing the filesystem.
  68. DummyAuthorizer is the base authorizer, providing a platform
  69. independent interface for managing "virtual" FTP users. System
  70. dependent authorizers can by written by subclassing this base
  71. class and overriding appropriate methods as necessary.
  72. """
  73. read_perms = "elr"
  74. write_perms = "adfmwM"
  75. def __init__(self):
  76. self.user_table = {}
  77. def add_user(self, username, password, homedir, perm='elr',
  78. msg_login="Login successful.", msg_quit="Goodbye."):
  79. """Add a user to the virtual users table.
  80. AuthorizerError exceptions raised on error conditions such as
  81. invalid permissions, missing home directory or duplicate usernames.
  82. Optional perm argument is a string referencing the user's
  83. permissions explained below:
  84. Read permissions:
  85. - "e" = change directory (CWD command)
  86. - "l" = list files (LIST, NLST, STAT, MLSD, MLST, SIZE, MDTM commands)
  87. - "r" = retrieve file from the server (RETR command)
  88. Write permissions:
  89. - "a" = append data to an existing file (APPE command)
  90. - "d" = delete file or directory (DELE, RMD commands)
  91. - "f" = rename file or directory (RNFR, RNTO commands)
  92. - "m" = create directory (MKD command)
  93. - "w" = store a file to the server (STOR, STOU commands)
  94. - "M" = change file mode (SITE CHMOD command)
  95. Optional msg_login and msg_quit arguments can be specified to
  96. provide customized response strings when user log-in and quit.
  97. """
  98. if self.has_user(username):
  99. raise ValueError('user %r already exists' % username)
  100. if not isinstance(homedir, unicode):
  101. homedir = homedir.decode('utf8')
  102. if not os.path.isdir(homedir):
  103. raise ValueError('no such directory: %r' % homedir)
  104. homedir = os.path.realpath(homedir)
  105. self._check_permissions(username, perm)
  106. dic = {'pwd': str(password),
  107. 'home': homedir,
  108. 'perm': perm,
  109. 'operms': {},
  110. 'msg_login': str(msg_login),
  111. 'msg_quit': str(msg_quit)
  112. }
  113. self.user_table[username] = dic
  114. def add_anonymous(self, homedir, **kwargs):
  115. """Add an anonymous user to the virtual users table.
  116. AuthorizerError exception raised on error conditions such as
  117. invalid permissions, missing home directory, or duplicate
  118. anonymous users.
  119. The keyword arguments in kwargs are the same expected by
  120. add_user method: "perm", "msg_login" and "msg_quit".
  121. The optional "perm" keyword argument is a string defaulting to
  122. "elr" referencing "read-only" anonymous user's permissions.
  123. Using write permission values ("adfmwM") results in a
  124. RuntimeWarning.
  125. """
  126. DummyAuthorizer.add_user(self, 'anonymous', '', homedir, **kwargs)
  127. def remove_user(self, username):
  128. """Remove a user from the virtual users table."""
  129. del self.user_table[username]
  130. def override_perm(self, username, directory, perm, recursive=False):
  131. """Override permissions for a given directory."""
  132. self._check_permissions(username, perm)
  133. if not os.path.isdir(directory):
  134. raise ValueError('no such directory: %r' % directory)
  135. directory = os.path.normcase(os.path.realpath(directory))
  136. home = os.path.normcase(self.get_home_dir(username))
  137. if directory == home:
  138. raise ValueError("can't override home directory permissions")
  139. if not self._issubpath(directory, home):
  140. raise ValueError("path escapes user home directory")
  141. self.user_table[username]['operms'][directory] = perm, recursive
  142. def validate_authentication(self, username, password, handler):
  143. """Raises AuthenticationFailed if supplied username and
  144. password don't match the stored credentials, else return
  145. None.
  146. """
  147. msg = "Authentication failed."
  148. if not self.has_user(username):
  149. if username == 'anonymous':
  150. msg = "Anonymous access not allowed."
  151. raise AuthenticationFailed(msg)
  152. if username != 'anonymous':
  153. if self.user_table[username]['pwd'] != password:
  154. raise AuthenticationFailed(msg)
  155. def get_home_dir(self, username):
  156. """Return the user's home directory.
  157. Since this is called during authentication (PASS),
  158. AuthenticationFailed can be freely raised by subclasses in case
  159. the provided username no longer exists.
  160. """
  161. return self.user_table[username]['home']
  162. def impersonate_user(self, username, password):
  163. """Impersonate another user (noop).
  164. It is always called before accessing the filesystem.
  165. By default it does nothing. The subclass overriding this
  166. method is expected to provide a mechanism to change the
  167. current user.
  168. """
  169. def terminate_impersonation(self, username):
  170. """Terminate impersonation (noop).
  171. It is always called after having accessed the filesystem.
  172. By default it does nothing. The subclass overriding this
  173. method is expected to provide a mechanism to switch back
  174. to the original user.
  175. """
  176. def has_user(self, username):
  177. """Whether the username exists in the virtual users table."""
  178. return username in self.user_table
  179. def has_perm(self, username, perm, path=None):
  180. """Whether the user has permission over path (an absolute
  181. pathname of a file or a directory).
  182. Expected perm argument is one of the following letters:
  183. "elradfmwM".
  184. """
  185. if path is None:
  186. return perm in self.user_table[username]['perm']
  187. path = os.path.normcase(path)
  188. for dir in self.user_table[username]['operms'].keys():
  189. operm, recursive = self.user_table[username]['operms'][dir]
  190. if self._issubpath(path, dir):
  191. if recursive:
  192. return perm in operm
  193. if (path == dir) or (os.path.dirname(path) == dir \
  194. and not os.path.isdir(path)):
  195. return perm in operm
  196. return perm in self.user_table[username]['perm']
  197. def get_perms(self, username):
  198. """Return current user permissions."""
  199. return self.user_table[username]['perm']
  200. def get_msg_login(self, username):
  201. """Return the user's login message."""
  202. return self.user_table[username]['msg_login']
  203. def get_msg_quit(self, username):
  204. """Return the user's quitting message."""
  205. return self.user_table[username]['msg_quit']
  206. def _check_permissions(self, username, perm):
  207. warned = 0
  208. for p in perm:
  209. if p not in self.read_perms + self.write_perms:
  210. raise ValueError('no such permission %r' % p)
  211. if (username == 'anonymous') and (p in self.write_perms) and not warned:
  212. warnings.warn("write permissions assigned to anonymous user.",
  213. RuntimeWarning)
  214. warned = 1
  215. def _issubpath(self, a, b):
  216. """Return True if a is a sub-path of b or if the paths are equal."""
  217. p1 = a.rstrip(os.sep).split(os.sep)
  218. p2 = b.rstrip(os.sep).split(os.sep)
  219. return p1[:len(p2)] == p2
  220. def replace_anonymous(callable):
  221. """A decorator to replace anonymous user string passed to authorizer
  222. methods as first argument with the actual user used to handle
  223. anonymous sessions.
  224. """
  225. def wrapper(self, username, *args, **kwargs):
  226. if username == 'anonymous':
  227. username = self.anonymous_user or username
  228. return callable(self, username, *args, **kwargs)
  229. return wrapper
  230. # ===================================================================
  231. # --- platform specific authorizers
  232. # ===================================================================
  233. class _Base(object):
  234. """Methods common to both Unix and Windows authorizers.
  235. Not supposed to be used directly.
  236. """
  237. msg_no_such_user = "Authentication failed."
  238. msg_wrong_password = "Authentication failed."
  239. msg_anon_not_allowed = "Anonymous access not allowed."
  240. msg_invalid_shell = "User %s doesn't have a valid shell."
  241. msg_rejected_user = "User %s is not allowed to login."
  242. def __init__(self):
  243. """Check for errors in the constructor."""
  244. if self.rejected_users and self.allowed_users:
  245. raise AuthorizerError("rejected_users and allowed_users options are "
  246. "mutually exclusive")
  247. users = self._get_system_users()
  248. for user in (self.allowed_users or self.rejected_users):
  249. if user == 'anonymous':
  250. raise AuthorizerError('invalid username "anonymous"')
  251. if user not in users:
  252. raise AuthorizerError('unknown user %s' % user)
  253. if self.anonymous_user is not None:
  254. if not self.has_user(self.anonymous_user):
  255. raise AuthorizerError('no such user %s' % self.anonymous_user)
  256. home = self.get_home_dir(self.anonymous_user)
  257. if not os.path.isdir(home):
  258. raise AuthorizerError('no valid home set for user %s'
  259. % self.anonymous_user)
  260. def override_user(self, username, password=None, homedir=None, perm=None,
  261. msg_login=None, msg_quit=None):
  262. """Overrides the options specified in the class constructor
  263. for a specific user.
  264. """
  265. if not password and not homedir and not perm and not msg_login \
  266. and not msg_quit:
  267. raise AuthorizerError("at least one keyword argument must be specified")
  268. if self.allowed_users and username not in self.allowed_users:
  269. raise AuthorizerError('%s is not an allowed user' % username)
  270. if self.rejected_users and username in self.rejected_users:
  271. raise AuthorizerError('%s is not an allowed user' % username)
  272. if username == "anonymous" and password:
  273. raise AuthorizerError("can't assign password to anonymous user")
  274. if not self.has_user(username):
  275. raise AuthorizerError('no such user %s' % username)
  276. if homedir is not None and not isinstance(homedir, unicode):
  277. homedir = homedir.decode('utf8')
  278. if username in self._dummy_authorizer.user_table:
  279. # re-set parameters
  280. del self._dummy_authorizer.user_table[username]
  281. self._dummy_authorizer.add_user(username, password or "",
  282. homedir or getcwdu(),
  283. perm or "",
  284. msg_login or "",
  285. msg_quit or "")
  286. if homedir is None:
  287. self._dummy_authorizer.user_table[username]['home'] = ""
  288. def get_msg_login(self, username):
  289. return self._get_key(username, 'msg_login') or self.msg_login
  290. def get_msg_quit(self, username):
  291. return self._get_key(username, 'msg_quit') or self.msg_quit
  292. def get_perms(self, username):
  293. overridden_perms = self._get_key(username, 'perm')
  294. if overridden_perms:
  295. return overridden_perms
  296. if username == 'anonymous':
  297. return 'elr'
  298. return self.global_perm
  299. def has_perm(self, username, perm, path=None):
  300. return perm in self.get_perms(username)
  301. def _get_key(self, username, key):
  302. if self._dummy_authorizer.has_user(username):
  303. return self._dummy_authorizer.user_table[username][key]
  304. def _is_rejected_user(self, username):
  305. """Return True if the user has been black listed via
  306. allowed_users or rejected_users options.
  307. """
  308. if self.allowed_users and username not in self.allowed_users:
  309. return True
  310. if self.rejected_users and username in self.rejected_users:
  311. return True
  312. return False
  313. # ===================================================================
  314. # --- UNIX
  315. # ===================================================================
  316. # Note: requires python >= 2.5
  317. try:
  318. import pwd, spwd, crypt
  319. except ImportError:
  320. pass
  321. else:
  322. __all__.extend(['BaseUnixAuthorizer', 'UnixAuthorizer'])
  323. # the uid/gid the server runs under
  324. PROCESS_UID = os.getuid()
  325. PROCESS_GID = os.getgid()
  326. class BaseUnixAuthorizer(object):
  327. """An authorizer compatible with Unix user account and password
  328. database.
  329. This class should not be used directly unless for subclassing.
  330. Use higher-level UnixAuthorizer class instead.
  331. """
  332. def __init__(self, anonymous_user=None):
  333. if os.geteuid() != 0 or not spwd.getspall():
  334. raise AuthorizerError("super user privileges are required")
  335. self.anonymous_user = anonymous_user
  336. if self.anonymous_user is not None:
  337. try:
  338. pwd.getpwnam(self.anonymous_user).pw_dir
  339. except KeyError:
  340. raise AuthorizerError('no such user %s' % anonymous_user)
  341. # --- overridden / private API
  342. def validate_authentication(self, username, password, handler):
  343. """Authenticates against shadow password db; raises
  344. AuthenticationFailed in case of failed authentication.
  345. """
  346. if username == "anonymous":
  347. if self.anonymous_user is None:
  348. raise AuthenticationFailed(self.msg_anon_not_allowed)
  349. else:
  350. try:
  351. pw1 = spwd.getspnam(username).sp_pwd
  352. pw2 = crypt.crypt(password, pw1)
  353. except KeyError: # no such username
  354. raise AuthenticationFailed(self.msg_no_such_user)
  355. else:
  356. if pw1 != pw2:
  357. raise AuthenticationFailed(self.msg_wrong_password)
  358. @replace_anonymous
  359. def impersonate_user(self, username, password):
  360. """Change process effective user/group ids to reflect
  361. logged in user.
  362. """
  363. try:
  364. pwdstruct = pwd.getpwnam(username)
  365. except KeyError:
  366. raise AuthorizerError(self.msg_no_such_user)
  367. else:
  368. os.setegid(pwdstruct.pw_gid)
  369. os.seteuid(pwdstruct.pw_uid)
  370. def terminate_impersonation(self, username):
  371. """Revert process effective user/group IDs."""
  372. os.setegid(PROCESS_GID)
  373. os.seteuid(PROCESS_UID)
  374. @replace_anonymous
  375. def has_user(self, username):
  376. """Return True if user exists on the Unix system.
  377. If the user has been black listed via allowed_users or
  378. rejected_users options always return False.
  379. """
  380. return username in self._get_system_users()
  381. @replace_anonymous
  382. def get_home_dir(self, username):
  383. """Return user home directory."""
  384. try:
  385. home = pwd.getpwnam(username).pw_dir
  386. except KeyError:
  387. raise AuthorizerError(self.msg_no_such_user)
  388. else:
  389. if not PY3:
  390. home = home.decode('utf8')
  391. return home
  392. @staticmethod
  393. def _get_system_users():
  394. """Return all users defined on the UNIX system."""
  395. # there should be no need to convert usernames to unicode
  396. # as UNIX does not allow chars outside of ASCII set
  397. return [entry.pw_name for entry in pwd.getpwall()]
  398. def get_msg_login(self, username):
  399. return "Login successful."
  400. def get_msg_quit(self, username):
  401. return "Goodbye."
  402. def get_perms(self, username):
  403. return "elradfmw"
  404. def has_perm(self, username, perm, path=None):
  405. return perm in self.get_perms(username)
  406. class UnixAuthorizer(_Base, BaseUnixAuthorizer):
  407. """A wrapper on top of BaseUnixAuthorizer providing options
  408. to specify what users should be allowed to login, per-user
  409. options, etc.
  410. Example usages:
  411. >>> from pyftpdlib.contrib.authorizers import UnixAuthorizer
  412. >>> # accept all except root
  413. >>> auth = UnixAuthorizer(rejected_users=["root"])
  414. >>>
  415. >>> # accept some users only
  416. >>> auth = UnixAuthorizer(allowed_users=["matt", "jay"])
  417. >>>
  418. >>> # accept everybody and don't care if they have not a valid shell
  419. >>> auth = UnixAuthorizer(require_valid_shell=False)
  420. >>>
  421. >>> # set specific options for a user
  422. >>> auth.override_user("matt", password="foo", perm="elr")
  423. """
  424. # --- public API
  425. def __init__(self, global_perm="elradfmw",
  426. allowed_users=None,
  427. rejected_users=None,
  428. require_valid_shell=True,
  429. anonymous_user=None,
  430. msg_login="Login successful.",
  431. msg_quit="Goodbye."):
  432. """Parameters:
  433. - (string) global_perm:
  434. a series of letters referencing the users permissions;
  435. defaults to "elradfmw" which means full read and write
  436. access for everybody (except anonymous).
  437. - (list) allowed_users:
  438. a list of users which are accepted for authenticating
  439. against the FTP server; defaults to [] (no restrictions).
  440. - (list) rejected_users:
  441. a list of users which are not accepted for authenticating
  442. against the FTP server; defaults to [] (no restrictions).
  443. - (bool) require_valid_shell:
  444. Deny access for those users which do not have a valid shell
  445. binary listed in /etc/shells.
  446. If /etc/shells cannot be found this is a no-op.
  447. Anonymous user is not subject to this option, and is free
  448. to not have a valid shell defined.
  449. Defaults to True (a valid shell is required for login).
  450. - (string) anonymous_user:
  451. specify it if you intend to provide anonymous access.
  452. The value expected is a string representing the system user
  453. to use for managing anonymous sessions; defaults to None
  454. (anonymous access disabled).
  455. - (string) msg_login:
  456. the string sent when client logs in.
  457. - (string) msg_quit:
  458. the string sent when client quits.
  459. """
  460. BaseUnixAuthorizer.__init__(self, anonymous_user)
  461. if allowed_users is None:
  462. allowed_users = []
  463. if rejected_users is None:
  464. rejected_users = []
  465. self.global_perm = global_perm
  466. self.allowed_users = allowed_users
  467. self.rejected_users = rejected_users
  468. self.anonymous_user = anonymous_user
  469. self.require_valid_shell = require_valid_shell
  470. self.msg_login = msg_login
  471. self.msg_quit = msg_quit
  472. self._dummy_authorizer = DummyAuthorizer()
  473. self._dummy_authorizer._check_permissions('', global_perm)
  474. _Base.__init__(self)
  475. if require_valid_shell:
  476. for username in self.allowed_users:
  477. if not self._has_valid_shell(username):
  478. raise AuthorizerError("user %s has not a valid shell"
  479. % username)
  480. def override_user(self, username, password=None, homedir=None, perm=None,
  481. msg_login=None, msg_quit=None):
  482. """Overrides the options specified in the class constructor
  483. for a specific user.
  484. """
  485. if self.require_valid_shell and username != 'anonymous':
  486. if not self._has_valid_shell(username):
  487. raise AuthorizerError(self.msg_invalid_shell % username)
  488. _Base.override_user(self, username, password, homedir, perm,
  489. msg_login, msg_quit)
  490. # --- overridden / private API
  491. def validate_authentication(self, username, password, handler):
  492. if username == "anonymous":
  493. if self.anonymous_user is None:
  494. raise AuthenticationFailed(self.msg_anon_not_allowed)
  495. return
  496. if self._is_rejected_user(username):
  497. raise AuthenticationFailed(self.msg_rejected_user % username)
  498. overridden_password = self._get_key(username, 'pwd')
  499. if overridden_password:
  500. if overridden_password != password:
  501. raise AuthenticationFailed(self.msg_wrong_password)
  502. else:
  503. BaseUnixAuthorizer.validate_authentication(self, username,
  504. password, handler)
  505. if self.require_valid_shell and username != 'anonymous':
  506. if not self._has_valid_shell(username):
  507. raise AuthenticationFailed(self.msg_invalid_shell % username)
  508. @replace_anonymous
  509. def has_user(self, username):
  510. if self._is_rejected_user(username):
  511. return False
  512. return username in self._get_system_users()
  513. @replace_anonymous
  514. def get_home_dir(self, username):
  515. overridden_home = self._get_key(username, 'home')
  516. if overridden_home:
  517. return overridden_home
  518. return BaseUnixAuthorizer.get_home_dir(self, username)
  519. @staticmethod
  520. def _has_valid_shell(username):
  521. """Return True if the user has a valid shell binary listed
  522. in /etc/shells. If /etc/shells can't be found return True.
  523. """
  524. file = None
  525. try:
  526. try:
  527. file = open('/etc/shells', 'r')
  528. except IOError:
  529. err = sys.exc_info()[1]
  530. if err.errno == errno.ENOENT:
  531. return True
  532. raise
  533. else:
  534. try:
  535. shell = pwd.getpwnam(username).pw_shell
  536. except KeyError: # invalid user
  537. return False
  538. for line in file:
  539. if line.startswith('#'):
  540. continue
  541. line = line.strip()
  542. if line == shell:
  543. return True
  544. return False
  545. finally:
  546. if file is not None:
  547. file.close()
  548. # ===================================================================
  549. # --- Windows
  550. # ===================================================================
  551. try:
  552. import _winreg as winreg
  553. except ImportError:
  554. try:
  555. import winreg # PY3
  556. except ImportError:
  557. pass
  558. # Note: requires pywin32 extension
  559. try:
  560. import win32security, win32net, pywintypes, win32con, win32api
  561. except ImportError:
  562. pass
  563. else:
  564. __all__.extend(['BaseWindowsAuthorizer', 'WindowsAuthorizer'])
  565. class BaseWindowsAuthorizer(object):
  566. """An authorizer compatible with Windows user account and
  567. password database.
  568. This class should not be used directly unless for subclassing.
  569. Use higher-level WinowsAuthorizer class instead.
  570. """
  571. def __init__(self, anonymous_user=None, anonymous_password=None):
  572. # actually try to impersonate the user
  573. self.anonymous_user = anonymous_user
  574. self.anonymous_password = anonymous_password
  575. if self.anonymous_user is not None:
  576. self.impersonate_user(self.anonymous_user,
  577. self.anonymous_password)
  578. self.terminate_impersonation(None)
  579. def validate_authentication(self, username, password, handler):
  580. if username == "anonymous":
  581. if self.anonymous_user is None:
  582. raise AuthenticationFailed(self.msg_anon_not_allowed)
  583. return
  584. try:
  585. win32security.LogonUser(username, None, password,
  586. win32con.LOGON32_LOGON_INTERACTIVE,
  587. win32con.LOGON32_PROVIDER_DEFAULT)
  588. except pywintypes.error:
  589. raise AuthenticationFailed(self.msg_wrong_password)
  590. @replace_anonymous
  591. def impersonate_user(self, username, password):
  592. """Impersonate the security context of another user."""
  593. handler = win32security.LogonUser(username, None, password,
  594. win32con.LOGON32_LOGON_INTERACTIVE,
  595. win32con.LOGON32_PROVIDER_DEFAULT)
  596. win32security.ImpersonateLoggedOnUser(handler)
  597. handler.Close()
  598. def terminate_impersonation(self, username):
  599. """Terminate the impersonation of another user."""
  600. win32security.RevertToSelf()
  601. @replace_anonymous
  602. def has_user(self, username):
  603. return username in self._get_system_users()
  604. @replace_anonymous
  605. def get_home_dir(self, username):
  606. """Return the user's profile directory, the closest thing
  607. to a user home directory we have on Windows.
  608. """
  609. try:
  610. sid = win32security.ConvertSidToStringSid(
  611. win32security.LookupAccountName(None, username)[0])
  612. except pywintypes.error:
  613. err = sys.exc_info()[1]
  614. raise AuthorizerError(err)
  615. path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + \
  616. "\\" + sid
  617. try:
  618. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
  619. except WindowsError:
  620. raise AuthorizerError("No profile directory defined for user %s"
  621. % username)
  622. value = winreg.QueryValueEx(key, "ProfileImagePath")[0]
  623. home = win32api.ExpandEnvironmentStrings(value)
  624. if not PY3 and not isinstance(home, unicode):
  625. home = home.decode('utf8')
  626. return home
  627. @classmethod
  628. def _get_system_users(cls):
  629. """Return all users defined on the Windows system."""
  630. # XXX - Does Windows allow usernames with chars outside of
  631. # ASCII set? In that case we need to convert this to unicode.
  632. return [entry['name'] for entry in win32net.NetUserEnum(None, 0)[0]]
  633. def get_msg_login(self, username):
  634. return "Login successful."
  635. def get_msg_quit(self, username):
  636. return "Goodbye."
  637. def get_perms(self, username):
  638. return "elradfmw"
  639. def has_perm(self, username, perm, path=None):
  640. return perm in self.get_perms(username)
  641. class WindowsAuthorizer(_Base, BaseWindowsAuthorizer):
  642. """A wrapper on top of BaseWindowsAuthorizer providing options
  643. to specify what users should be allowed to login, per-user
  644. options, etc.
  645. Example usages:
  646. >>> from pyftpdlib.contrib.authorizers import WindowsAuthorizer
  647. >>> # accept all except Administrator
  648. >>> auth = UnixAuthorizer(rejected_users=["Administrator"])
  649. >>>
  650. >>> # accept some users only
  651. >>> auth = UnixAuthorizer(allowed_users=["matt", "jay"])
  652. >>>
  653. >>> # set specific options for a user
  654. >>> auth.override_user("matt", password="foo", perm="elr")
  655. """
  656. # --- public API
  657. def __init__(self, global_perm="elradfmw",
  658. allowed_users=None,
  659. rejected_users=None,
  660. anonymous_user=None,
  661. anonymous_password=None,
  662. msg_login="Login successful.",
  663. msg_quit="Goodbye."):
  664. """Parameters:
  665. - (string) global_perm:
  666. a series of letters referencing the users permissions;
  667. defaults to "elradfmw" which means full read and write
  668. access for everybody (except anonymous).
  669. - (list) allowed_users:
  670. a list of users which are accepted for authenticating
  671. against the FTP server; defaults to [] (no restrictions).
  672. - (list) rejected_users:
  673. a list of users which are not accepted for authenticating
  674. against the FTP server; defaults to [] (no restrictions).
  675. - (string) anonymous_user:
  676. specify it if you intend to provide anonymous access.
  677. The value expected is a string representing the system user
  678. to use for managing anonymous sessions.
  679. As for IIS, it is recommended to use Guest account.
  680. The common practice is to first enable the Guest user, which
  681. is disabled by default and then assign an empty password.
  682. Defaults to None (anonymous access disabled).
  683. - (string) anonymous_password:
  684. the password of the user who has been chosen to manage the
  685. anonymous sessions. Defaults to None (empty password).
  686. - (string) msg_login:
  687. the string sent when client logs in.
  688. - (string) msg_quit:
  689. the string sent when client quits.
  690. """
  691. if allowed_users is None:
  692. allowed_users = []
  693. if rejected_users is None:
  694. rejected_users = []
  695. self.global_perm = global_perm
  696. self.allowed_users = allowed_users
  697. self.rejected_users = rejected_users
  698. self.anonymous_user = anonymous_user
  699. self.anonymous_password = anonymous_password
  700. self.msg_login = msg_login
  701. self.msg_quit = msg_quit
  702. self._dummy_authorizer = DummyAuthorizer()
  703. self._dummy_authorizer._check_permissions('', global_perm)
  704. _Base.__init__(self)
  705. # actually try to impersonate the user
  706. if self.anonymous_user is not None:
  707. self.impersonate_user(self.anonymous_user,
  708. self.anonymous_password)
  709. self.terminate_impersonation(None)
  710. def override_user(self, username, password=None, homedir=None, perm=None,
  711. msg_login=None, msg_quit=None):
  712. """Overrides the options specified in the class constructor
  713. for a specific user.
  714. """
  715. _Base.override_user(self, username, password, homedir, perm,
  716. msg_login, msg_quit)
  717. # --- overridden / private API
  718. def validate_authentication(self, username, password, handler):
  719. """Authenticates against Windows user database; return
  720. True on success.
  721. """
  722. if username == "anonymous":
  723. if self.anonymous_user is None:
  724. raise AuthenticationFailed(self.msg_anon_not_allowed)
  725. return
  726. if self.allowed_users and username not in self.allowed_users:
  727. raise AuthenticationFailed(self.msg_rejected_user % username)
  728. if self.rejected_users and username in self.rejected_users:
  729. raise AuthenticationFailed(self.msg_rejected_user % username)
  730. overridden_password = self._get_key(username, 'pwd')
  731. if overridden_password:
  732. if overridden_password != password:
  733. raise AuthenticationFailed(self.msg_wrong_password)
  734. else:
  735. BaseWindowsAuthorizer.validate_authentication(self, username,
  736. password, handler)
  737. def impersonate_user(self, username, password):
  738. """Impersonate the security context of another user."""
  739. if username == "anonymous":
  740. username = self.anonymous_user or ""
  741. password = self.anonymous_password or ""
  742. BaseWindowsAuthorizer.impersonate_user(self, username, password)
  743. @replace_anonymous
  744. def has_user(self, username):
  745. if self._is_rejected_user(username):
  746. return False
  747. return username in self._get_system_users()
  748. @replace_anonymous
  749. def get_home_dir(self, username):
  750. overridden_home = self._get_key(username, 'home')
  751. if overridden_home:
  752. home = overridden_home
  753. else:
  754. home = BaseWindowsAuthorizer.get_home_dir(self, username)
  755. if not PY3 and not isinstance(home, unicode):
  756. home = home.decode('utf8')
  757. return home