PAM.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2011 Corentin Le Bail
  5. # Copyright © 2011 Guillaume Ayoub
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. PAM ACL.
  21. Authentication based on the ``python-ldap`` module
  22. (http://www.python-ldap.org/).
  23. """
  24. import grp
  25. import pam
  26. import pwd
  27. from radicale import acl, config, log
  28. GROUP_MEMBERSHIP = config.get("acl", "group_membership")
  29. def has_right(owner, user, password):
  30. """Check if ``user``/``password`` couple is valid."""
  31. if not user or (owner not in acl.PRIVATE_USERS and user != owner):
  32. # No user given, or owner is not private and is not user, forbidden
  33. return False
  34. try: # 1 - Does the user exist in the PAM system?
  35. pwd.getpwnam(user).pw_uid
  36. log.LOGGER.debug("User %s found" % user)
  37. except KeyError: # No such user in the PAM system
  38. log.LOGGER.debug("User %s not found" % user)
  39. return False
  40. try: # 2 - Does the user belong to the required group?
  41. for member in grp.getgrnam(GROUP_MEMBERSHIP):
  42. if member == user:
  43. raise Exception()
  44. log.LOGGER.debug("The user doesn't belong to the required group (%s)" % GROUP_MEMBERSHIP)
  45. return False
  46. except KeyError:
  47. log.LOGGER.debug("The membership required group (%s) doesn't exist" % GROUP_MEMBERSHIP)
  48. return False
  49. except Exception:
  50. log.LOGGER.debug("The user belong to the required group (%s)" % GROUP_MEMBERSHIP)
  51. if pam.authenticate(user, password): # 3 - Does the password match ?
  52. return True
  53. return False # Authentication failled