1
0
Fork 0
mirror of https://github.com/Kozea/Radicale.git synced 2025-06-26 16:45:52 +00:00

Remove extra auth, rights and storage modules

This commit is contained in:
Guillaume Ayoub 2016-04-07 19:02:52 +02:00
parent 1c4acc44a8
commit 1001bcb676
17 changed files with 134 additions and 1119 deletions

View file

@ -1,97 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2012 Daniel Aleksandersen
# Copyright © 2013 Nikita Koshikov
# Copyright © 2013-2016 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
IMAP authentication.
Secure authentication based on the ``imaplib`` module.
Validating users against a modern IMAP4rev1 server that awaits STARTTLS on
port 143. Legacy SSL (often on legacy port 993) is deprecated and thus
unsupported. STARTTLS is enforced except if host is ``localhost`` as
passwords are sent in PLAIN.
"""
import imaplib
from .. import config, log
IMAP_SERVER = config.get("auth", "imap_hostname")
IMAP_SERVER_PORT = config.getint("auth", "imap_port")
IMAP_USE_SSL = config.getboolean("auth", "imap_ssl")
IMAP_WARNED_UNENCRYPTED = False
def is_authenticated(user, password):
"""Check if ``user``/``password`` couple is valid."""
global IMAP_WARNED_UNENCRYPTED
if not user or not password:
return False
log.LOGGER.debug(
"Connecting to IMAP server %s:%s." % (IMAP_SERVER, IMAP_SERVER_PORT,))
connection_is_secure = False
if IMAP_USE_SSL:
connection = imaplib.IMAP4_SSL(host=IMAP_SERVER, port=IMAP_SERVER_PORT)
connection_is_secure = True
else:
connection = imaplib.IMAP4(host=IMAP_SERVER, port=IMAP_SERVER_PORT)
server_is_local = (IMAP_SERVER == "localhost")
if not connection_is_secure:
try:
connection.starttls()
log.LOGGER.debug("IMAP server connection changed to TLS.")
connection_is_secure = True
except AttributeError:
if not server_is_local:
log.LOGGER.error(
"Python 3.2 or newer is required for IMAP + TLS.")
except (imaplib.IMAP4.error, imaplib.IMAP4.abort) as exception:
log.LOGGER.warning(
"IMAP server at %s failed to accept TLS connection "
"because of: %s" % (IMAP_SERVER, exception))
if server_is_local and not connection_is_secure and not IMAP_WARNED_UNENCRYPTED:
IMAP_WARNED_UNENCRYPTED = True
log.LOGGER.warning(
"IMAP server is local. "
"Will allow transmitting unencrypted credentials.")
if connection_is_secure or server_is_local:
try:
connection.login(user, password)
connection.logout()
log.LOGGER.debug(
"Authenticated IMAP user %s "
"via %s." % (user, IMAP_SERVER))
return True
except (imaplib.IMAP4.error, imaplib.IMAP4.abort) as exception:
log.LOGGER.error(
"IMAP server could not authenticate user %s "
"because of: %s" % (user, exception))
else:
log.LOGGER.critical(
"IMAP server did not support TLS and is not ``localhost``. "
"Refusing to transmit passwords under these conditions. "
"Authentication attempt aborted.")
return False # authentication failed

View file

@ -1,78 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2011 Corentin Le Bail
# Copyright © 2011-2016 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
LDAP authentication.
Authentication based on the ``python-ldap`` module
(http://www.python-ldap.org/).
"""
import ldap
from .. import config, log
BASE = config.get("auth", "ldap_base")
ATTRIBUTE = config.get("auth", "ldap_attribute")
FILTER = config.get("auth", "ldap_filter")
CONNEXION = ldap.initialize(config.get("auth", "ldap_url"))
BINDDN = config.get("auth", "ldap_binddn")
PASSWORD = config.get("auth", "ldap_password")
SCOPE = getattr(ldap, "SCOPE_%s" % config.get("auth", "ldap_scope").upper())
def is_authenticated(user, password):
"""Check if ``user``/``password`` couple is valid."""
global CONNEXION
try:
CONNEXION.whoami_s()
except:
log.LOGGER.debug("Reconnecting the LDAP server")
CONNEXION = ldap.initialize(config.get("auth", "ldap_url"))
if BINDDN and PASSWORD:
log.LOGGER.debug("Initial LDAP bind as %s" % BINDDN)
CONNEXION.simple_bind_s(BINDDN, PASSWORD)
distinguished_name = "%s=%s" % (ATTRIBUTE, ldap.dn.escape_dn_chars(user))
log.LOGGER.debug(
"LDAP bind for %s in base %s" % (distinguished_name, BASE))
if FILTER:
filter_string = "(&(%s)%s)" % (distinguished_name, FILTER)
else:
filter_string = distinguished_name
log.LOGGER.debug("Used LDAP filter: %s" % filter_string)
users = CONNEXION.search_s(BASE, SCOPE, filter_string)
if users:
log.LOGGER.debug("User %s found" % user)
try:
CONNEXION.simple_bind_s(users[0][0], password or "")
except ldap.LDAPError:
log.LOGGER.debug("Invalid credentials")
else:
log.LOGGER.debug("LDAP bind OK")
return True
else:
log.LOGGER.debug("User %s not found" % user)
log.LOGGER.debug("LDAP bind failed")
return False

View file

@ -1,93 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2011 Henry-Nicolas Tourneur
# Copyright © 2016 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
PAM authentication.
Authentication based on the ``pam-python`` module.
"""
import grp
import pwd
import pam
from .. import config, log
GROUP_MEMBERSHIP = config.get("auth", "pam_group_membership")
# Compatibility for old versions of python-pam.
if hasattr(pam, "pam"):
def pam_authenticate(*args, **kwargs):
return pam.pam().authenticate(*args, **kwargs)
else:
def pam_authenticate(*args, **kwargs):
return pam.authenticate(*args, **kwargs)
def is_authenticated(user, password):
"""Check if ``user``/``password`` couple is valid."""
if user is None or password is None:
return False
# Check whether the user exists in the PAM system
try:
pwd.getpwnam(user).pw_uid
except KeyError:
log.LOGGER.debug("User %s not found" % user)
return False
else:
log.LOGGER.debug("User %s found" % user)
# Check whether the group exists
try:
# Obtain supplementary groups
members = grp.getgrnam(GROUP_MEMBERSHIP).gr_mem
except KeyError:
log.LOGGER.debug(
"The PAM membership required group (%s) doesn't exist" %
GROUP_MEMBERSHIP)
return False
# Check whether the user exists
try:
# Get user primary group
primary_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name
except KeyError:
log.LOGGER.debug("The PAM user (%s) doesn't exist" % user)
return False
# Check whether the user belongs to the required group
# (primary or supplementary)
if primary_group == GROUP_MEMBERSHIP or user in members:
log.LOGGER.debug(
"The PAM user belongs to the required group (%s)" %
GROUP_MEMBERSHIP)
# Check the password
if pam_authenticate(user, password, service='radicale'):
return True
else:
log.LOGGER.debug("Wrong PAM password")
else:
log.LOGGER.debug(
"The PAM user doesn't belong to the required group (%s)" %
GROUP_MEMBERSHIP)
return False

View file

@ -1,54 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2016 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Authentication management.
"""
import sys
from .. import config, log
def load():
"""Load list of available authentication managers."""
auth_type = config.get("auth", "type")
log.LOGGER.debug("Authentication type is %s" % auth_type)
if auth_type == "None":
return None
elif auth_type == 'custom':
auth_module = config.get("auth", "custom_handler")
__import__(auth_module)
module = sys.modules[auth_module]
else:
root_module = __import__(
"auth.%s" % auth_type, globals=globals(), level=2)
module = getattr(root_module, auth_type)
# Override auth.is_authenticated
sys.modules[__name__].is_authenticated = module.is_authenticated
return module
def is_authenticated(user, password):
"""Check if the user is authenticated.
This method is overriden if an auth module is loaded.
"""
return True # Default is always True: no authentication

View file

@ -1,61 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2011 Henry-Nicolas Tourneur
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Courier-Authdaemon authentication.
"""
import sys
import socket
from .. import config, log
COURIER_SOCKET = config.get("auth", "courier_socket")
def is_authenticated(user, password):
"""Check if ``user``/``password`` couple is valid."""
if not user or not password:
return False
line = "%s\nlogin\n%s\n%s" % (sys.argv[0], user, password)
line = "AUTH %i\n%s" % (len(line), line)
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(COURIER_SOCKET)
log.LOGGER.debug("Sending to Courier socket the request: %s" % line)
sock.send(line)
data = sock.recv(1024)
sock.close()
except socket.error as exception:
log.LOGGER.debug(
"Unable to communicate with Courier socket: %s" % exception)
return False
log.LOGGER.debug("Got Courier socket response: %r" % data)
# Address, HOME, GID, and either UID or USERNAME are mandatory in resposne
# see http://www.courier-mta.org/authlib/README_authlib.html#authpipeproto
for line in data.split():
if "GID" in line:
return True
# default is reject
# this alleviates the problem of a possibly empty reply from authlib
# see http://www.courier-mta.org/authlib/README_authlib.html#authpipeproto
return False

View file

@ -1,166 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
# Copyright © 2008-2016 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Implement htpasswd authentication.
Apache's htpasswd command (httpd.apache.org/docs/programs/htpasswd.html) manages
a file for storing user credentials. It can encrypt passwords using different
methods, e.g. BCRYPT, MD5-APR1 (a version of MD5 modified for Apache), SHA1, or
by using the system's CRYPT routine. The CRYPT and SHA1 encryption methods
implemented by htpasswd are considered as insecure. MD5-APR1 provides medium
security as of 2015. Only BCRYPT can be considered secure by current standards.
MD5-APR1-encrypted credentials can be written by all versions of htpasswd (its
the default, in fact), whereas BCRYPT requires htpasswd 2.4.x or newer.
The `is_authenticated(user, password)` function provided by this module
verifies the user-given credentials by parsing the htpasswd credential file
pointed to by the ``htpasswd_filename`` configuration value while assuming
the password encryption method specified via the ``htpasswd_encryption``
configuration value.
The following htpasswd password encrpytion methods are supported by Radicale
out-of-the-box:
- plain-text (created by htpasswd -p...) -- INSECURE
- CRYPT (created by htpasswd -d...) -- INSECURE
- SHA1 (created by htpasswd -s...) -- INSECURE
When passlib (https://pypi.python.org/pypi/passlib) is importable, the
following significantly more secure schemes are parsable by Radicale:
- MD5-APR1 (htpasswd -m...) -- htpasswd's default method
- BCRYPT (htpasswd -B...) -- Requires htpasswd 2.4.x
"""
import base64
import hashlib
import os
from .. import config
FILENAME = os.path.expanduser(config.get("auth", "htpasswd_filename"))
ENCRYPTION = config.get("auth", "htpasswd_encryption")
def _plain(hash_value, password):
"""Check if ``hash_value`` and ``password`` match, using plain method."""
return hash_value == password
def _crypt(hash_value, password):
"""Check if ``hash_value`` and ``password`` match, using crypt method."""
return crypt.crypt(password, hash_value) == hash_value
def _sha1(hash_value, password):
"""Check if ``hash_value`` and ``password`` match, using sha1 method."""
hash_value = hash_value.replace("{SHA}", "").encode("ascii")
password = password.encode(config.get("encoding", "stock"))
sha1 = hashlib.sha1() # pylint: disable=E1101
sha1.update(password)
return sha1.digest() == base64.b64decode(hash_value)
def _ssha(hash_salt_value, password):
"""Check if ``hash_salt_value`` and ``password`` match, using salted sha1
method. This method is not directly supported by htpasswd, but it can be
written with e.g. openssl, and nginx can parse it."""
hash_salt_value = hash_salt_value.replace(
"{SSHA}", "").encode("ascii").decode('base64')
password = password.encode(config.get("encoding", "stock"))
hash_value = hash_salt_value[:20]
salt_value = hash_salt_value[20:]
sha1 = hashlib.sha1() # pylint: disable=E1101
sha1.update(password)
sha1.update(salt_value)
return sha1.digest() == hash_value
def _bcrypt(hash_value, password):
return _passlib_bcrypt.verify(password, hash_value)
def _md5apr1(hash_value, password):
return _passlib_md5apr1.verify(password, hash_value)
# Prepare mapping between encryption names and verification functions.
# Pre-fill with methods that do not have external dependencies.
_verifuncs = {
"ssha": _ssha,
"sha1": _sha1,
"plain": _plain}
# Conditionally attempt to import external dependencies.
if ENCRYPTION == "md5":
try:
from passlib.hash import apr_md5_crypt as _passlib_md5apr1
except ImportError:
raise RuntimeError(("The htpasswd_encryption method 'md5' requires "
"availability of the passlib module."))
_verifuncs["md5"] = _md5apr1
elif ENCRYPTION == "bcrypt":
try:
from passlib.hash import bcrypt as _passlib_bcrypt
except ImportError:
raise RuntimeError(("The htpasswd_encryption method 'bcrypt' requires "
"availability of the passlib module with bcrypt support."))
# A call to `encrypt` raises passlib.exc.MissingBackendError with a good
# error message if bcrypt backend is not available. Trigger this here.
_passlib_bcrypt.encrypt("test-bcrypt-backend")
_verifuncs["bcrypt"] = _bcrypt
elif ENCRYPTION == "crypt":
try:
import crypt
except ImportError:
raise RuntimeError(("The htpasswd_encryption method 'crypt' requires "
"crypt() system support."))
_verifuncs["crypt"] = _crypt
# Validate initial configuration.
if ENCRYPTION not in _verifuncs:
raise RuntimeError(("The htpasswd encryption method '%s' is not "
"supported." % ENCRYPTION))
def is_authenticated(user, password):
"""Validate credentials.
Iterate through htpasswd credential file until user matches, extract hash
(encrypted password) and check hash against user-given password, using the
method specified in the Radicale config.
"""
with open(FILENAME) as f:
for line in f:
strippedline = line.strip()
if strippedline:
login, hash_value = strippedline.split(":")
if login == user:
# Allow encryption method to be overridden at runtime.
return _verifuncs[ENCRYPTION](hash_value, password)
return False

View file

@ -1,41 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2012 Ehsanul Hoque
# Copyright © 2013 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
HTTP authentication.
Authentication based on the ``requests`` module.
Post a request to an authentication server with the username/password.
Anything other than a 200/201 response is considered auth failure.
"""
import requests
from .. import config, log
AUTH_URL = config.get("auth", "http_url")
USER_PARAM = config.get("auth", "http_user_parameter")
PASSWORD_PARAM = config.get("auth", "http_password_parameter")
def is_authenticated(user, password):
"""Check if ``user``/``password`` couple is valid."""
log.LOGGER.debug("HTTP-based auth on %s." % AUTH_URL)
payload = {USER_PARAM: user, PASSWORD_PARAM: password}
return requests.post(AUTH_URL, data=payload).status_code in (200, 201)

View file

@ -1,29 +0,0 @@
# This file is part of Radicale Server - Calendar Server
# Copyright © 2012 Ehsanul Hoque
# Copyright © 2013 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Trusting the HTTP server auth mechanism.
"""
from .. import log
def is_authenticated(user, password):
"""Check if ``user`` is defined and assuming it's valid."""
log.LOGGER.debug("Got user %r from HTTP server." % user)
return user is not None