PAM.py 2.1 KB

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