PAM.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 authentication.
  20. Authentication based on the ``pam-python`` module.
  21. """
  22. import grp
  23. import pam
  24. import pwd
  25. from .. import config, log
  26. GROUP_MEMBERSHIP = config.get("auth", "pam_group_membership")
  27. def is_authenticated(user, password):
  28. """Check if ``user``/``password`` couple is valid."""
  29. if user is None or password is None:
  30. return False
  31. # Check whether the user exists in the PAM system
  32. try:
  33. pwd.getpwnam(user).pw_uid
  34. except KeyError:
  35. log.LOGGER.debug("User %s not found" % user)
  36. return False
  37. else:
  38. log.LOGGER.debug("User %s found" % user)
  39. # Check whether the group exists
  40. try:
  41. # Obtain supplementary groups
  42. members = grp.getgrnam(GROUP_MEMBERSHIP).gr_mem
  43. except KeyError:
  44. log.LOGGER.debug(
  45. "The PAM membership required group (%s) doesn't exist" %
  46. GROUP_MEMBERSHIP)
  47. return False
  48. # Check whether the user exists
  49. try:
  50. # Get user primary group
  51. primary_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
  52. except KeyError:
  53. log.LOGGER.debug("The PAM user (%s) doesn't exist" % user)
  54. return False
  55. # Check whether the user belongs to the required group
  56. # (primary or supplementary)
  57. if primary_group == GROUP_MEMBERSHIP or user in members:
  58. log.LOGGER.debug(
  59. "The PAM user belongs to the required group (%s)" %
  60. GROUP_MEMBERSHIP)
  61. # Check the password
  62. if pam.authenticate(user, password):
  63. return True
  64. else:
  65. log.LOGGER.debug("Wrong PAM password")
  66. else:
  67. log.LOGGER.debug(
  68. "The PAM user doesn't belong to the required group (%s)" %
  69. GROUP_MEMBERSHIP)
  70. return False