PAM.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 ``pam-python`` module.
  21. """
  22. import grp
  23. import pam
  24. import pwd
  25. from radicale import acl, config, log
  26. GROUP_MEMBERSHIP = config.get("acl", "pam_group_membership")
  27. def is_authenticated(user, password):
  28. """Check if ``user``/``password`` couple is valid."""
  29. # Check whether the user exists in the PAM system
  30. try:
  31. pwd.getpwnam(user).pw_uid
  32. except KeyError:
  33. log.LOGGER.debug("User %s not found" % user)
  34. return False
  35. else:
  36. log.LOGGER.debug("User %s found" % user)
  37. # Check whether the group exists
  38. try:
  39. members = grp.getgrnam(GROUP_MEMBERSHIP)
  40. except KeyError:
  41. log.LOGGER.debug(
  42. "The PAM membership required group (%s) doesn't exist" %
  43. GROUP_MEMBERSHIP)
  44. return False
  45. # Check whether the user belongs to the required group
  46. for member in members:
  47. if member == user:
  48. log.LOGGER.debug(
  49. "The PAM user belongs to the required group (%s)" %
  50. GROUP_MEMBERSHIP)
  51. # Check the password
  52. if pam.authenticate(user, password):
  53. return True
  54. else:
  55. log.LOGGER.debug("Wrong PAM password")
  56. break
  57. else:
  58. log.LOGGER.debug(
  59. "The PAM user doesn't belong to the required group (%s)" %
  60. GROUP_MEMBERSHIP)
  61. return False