# encoding: utf-8
import PIL
+import PIL.ImageOps
+import datetime
import io
import ldap
+import ldap.modlist
import logging
+import phonenumbers
+import sshpubkeys
import urllib.parse
import urllib.request
+import zxcvbn
+from . import util
from .decorators import *
from .misc import Object
query, attrlist=attrlist, sizelimit=limit)
except:
# Close current connection
- self.ldap.close()
del self.ldap
raise
# Find accounts by name
if not accounts:
- for account in self._search("(&(objectClass=posixAccount)(cn=*%s*))" % query):
+ for account in self._search("(&(objectClass=posixAccount)(|(cn=*%s*)(uid=*%s*)))" % (query, query)):
if not account in accounts:
accounts.append(account)
Object.__init__(self, backend)
self.dn = dn
- self.__attrs = attrs or {}
+ self.attributes = attrs or {}
def __str__(self):
return self.name
def ldap(self):
return self.accounts.ldap
- @property
- def attributes(self):
- return self.__attrs
+ def _exists(self, key):
+ try:
+ self.attributes[key]
+ except KeyError:
+ return False
- def _get_first_attribute(self, attr, default=None):
- if attr not in self.attributes:
- return default
+ return True
- res = self.attributes.get(attr, [])
- if res:
- return res[0]
+ def _get(self, key):
+ for value in self.attributes.get(key, []):
+ yield value
- def get(self, key):
- try:
- attribute = self.attributes[key]
- except KeyError:
- raise AttributeError(key)
+ def _get_bytes(self, key, default=None):
+ for value in self._get(key):
+ return value
+
+ return default
+
+ def _get_strings(self, key):
+ for value in self._get(key):
+ yield value.decode()
+
+ def _get_string(self, key, default=None):
+ for value in self._get_strings(key):
+ return value
+
+ return default
+
+ def _get_phone_numbers(self, key):
+ for value in self._get_strings(key):
+ yield phonenumbers.parse(value, None)
+
+ def _modify(self, modlist):
+ logging.debug("Modifying %s: %s" % (self.dn, modlist))
+
+ # Run modify operation
+ self.ldap.modify_s(self.dn, modlist)
+
+ def _set(self, key, values):
+ current = self._get(key)
+
+ # Don't do anything if nothing has changed
+ if list(current) == values:
+ return
+
+ # Remove all old values and add all new ones
+ modlist = []
+
+ if self._exists(key):
+ modlist.append((ldap.MOD_DELETE, key, None))
+
+ # Add new values
+ if values:
+ modlist.append((ldap.MOD_ADD, key, values))
+
+ # Run modify operation
+ self._modify(modlist)
+
+ # Update cache
+ self.attributes.update({ key : values })
+
+ def _set_bytes(self, key, values):
+ return self._set(key, values)
+
+ def _set_strings(self, key, values):
+ return self._set(key, [e.encode() for e in values if e])
+
+ def _set_string(self, key, value):
+ return self._set_strings(key, [value,])
+
+ def _add(self, key, values):
+ modlist = [
+ (ldap.MOD_ADD, key, values),
+ ]
+
+ self._modify(modlist)
+
+ def _add_strings(self, key, values):
+ return self._add(key, [e.encode() for e in values])
+
+ def _add_string(self, key, value):
+ return self._add_strings(key, [value,])
+
+ def _delete(self, key, values):
+ modlist = [
+ (ldap.MOD_DELETE, key, values),
+ ]
+
+ self._modify(modlist)
- if len(attribute) == 1:
- return attribute[0]
+ def _delete_strings(self, key, values):
+ return self._delete(key, [e.encode() for e in values])
- return attribute
+ def _delete_string(self, key, value):
+ return self._delete_strings(key, [value,])
+
+ def passwd(self, password):
+ """
+ Sets a new password
+ """
+ # The new password must have a score of 3 or better
+ quality = self.check_password_quality(password)
+ if quality["score"] < 3:
+ raise ValueError("Password too weak")
+
+ self.ldap.passwd_s(self.dn, None, password)
def check_password(self, password):
"""
Raises exceptions from the server on any other errors.
"""
+ if not password:
+ return
logging.debug("Checking credentials for %s" % self.dn)
+
+ # Create a new LDAP connection
+ ldap_uri = self.backend.settings.get("ldap_uri")
+ conn = ldap.initialize(ldap_uri)
+
try:
- self.ldap.simple_bind_s(self.dn, password.encode("utf-8"))
+ conn.simple_bind_s(self.dn, password.encode("utf-8"))
except ldap.INVALID_CREDENTIALS:
- logging.debug("Account credentials are invalid.")
+ logging.debug("Account credentials are invalid for %s" % self)
return False
- logging.debug("Successfully authenticated.")
+ logging.info("Successfully authenticated %s" % self)
+
return True
+ def check_password_quality(self, password):
+ """
+ Passwords are passed through zxcvbn to make sure
+ that they are strong enough.
+ """
+ return zxcvbn.zxcvbn(password, user_inputs=(
+ self.first_name, self.last_name,
+ ))
+
def is_admin(self):
return "wheel" in self.groups
return "sipUser" in self.classes or "sipRoutingObject" in self.classes \
or self.telephone_numbers or self.address
+ def can_be_managed_by(self, account):
+ """
+ Returns True if account is allowed to manage this account
+ """
+ # Admins can manage all accounts
+ if account.is_admin():
+ return True
+
+ # Users can manage themselves
+ return self == account
+
@property
def classes(self):
- return (x.decode() for x in self.attributes.get("objectClass", []))
+ return self._get_strings("objectClass")
@property
def uid(self):
- return self._get_first_attribute("uid").decode()
+ return self._get_string("uid")
@property
def name(self):
- return self._get_first_attribute("cn").decode()
+ return self._get_string("cn")
- @property
- def first_name(self):
- return self._get_first_attribute("givenName").decode()
+ # First Name
+
+ def get_first_name(self):
+ return self._get_string("givenName")
+
+ def set_first_name(self, first_name):
+ self._set_string("givenName", first_name)
+
+ # Update Common Name
+ self._set_string("cn", "%s %s" % (first_name, self.last_name))
+
+ first_name = property(get_first_name, set_first_name)
+
+ # Last Name
+
+ def get_last_name(self):
+ return self._get_string("sn")
+
+ def set_last_name(self, last_name):
+ self._set_string("sn", last_name)
+
+ # Update Common Name
+ self._set_string("cn", "%s %s" % (self.first_name, last_name))
+
+ last_name = property(get_last_name, set_last_name)
@lazy_property
def groups(self):
return groups
- @property
- def address(self):
- address = self._get_first_attribute("homePostalAddress", "".encode()).decode()
- address = address.replace(", ", "\n")
+ # Address
+
+ def get_address(self):
+ address = self._get_string("homePostalAddress")
+
+ if address:
+ return (line.strip() for line in address.split(","))
+
+ return []
- return address
+ def set_address(self, address):
+ data = ", ".join(address.splitlines())
+
+ self._set_bytes("homePostalAddress", data.encode())
+
+ address = property(get_address, set_address)
@property
def email(self):
# If everything else fails, we will go with the UID
return "%s@ipfire.org" % self.uid
+ # Mail Routing Address
+
+ def get_mail_routing_address(self):
+ return self._get_string("mailRoutingAddress", None)
+
+ def set_mail_routing_address(self, address):
+ self._set_string("mailRoutingAddress", address or None)
+
+ mail_routing_address = property(get_mail_routing_address, set_mail_routing_address)
+
@property
def sip_id(self):
if "sipUser" in self.classes:
- return self._get_first_attribute("sipAuthenticationUser").decode()
+ return self._get_string("sipAuthenticationUser")
if "sipRoutingObject" in self.classes:
- return self._get_first_attribute("sipLocalAddress").decode()
+ return self._get_string("sipLocalAddress")
@property
def sip_password(self):
- return self._get_first_attribute("sipPassword").decode()
+ return self._get_string("sipPassword")
+
+ @staticmethod
+ def _generate_sip_password():
+ return util.random_string(8)
@property
def sip_url(self):
return "%s@ipfire.org" % self.sip_id
def uses_sip_forwarding(self):
- if self.sip_routing_url:
+ if self.sip_routing_address:
return True
return False
- @property
- def sip_routing_url(self):
+ # SIP Routing
+
+ def get_sip_routing_address(self):
if "sipRoutingObject" in self.classes:
- return self._get_first_attribute("sipRoutingAddress").decode()
+ return self._get_string("sipRoutingAddress")
+
+ def set_sip_routing_address(self, address):
+ if not address:
+ address = None
+
+ # Don't do anything if nothing has changed
+ if self.get_sip_routing_address() == address:
+ return
+
+ if address:
+ modlist = [
+ # This is no longer a SIP user any more
+ (ldap.MOD_DELETE, "objectClass", b"sipUser"),
+ (ldap.MOD_DELETE, "sipAuthenticationUser", None),
+ (ldap.MOD_DELETE, "sipPassword", None),
+
+ (ldap.MOD_ADD, "objectClass", b"sipRoutingObject"),
+ (ldap.MOD_ADD, "sipLocalAddress", self.sip_id.encode()),
+ (ldap.MOD_ADD, "sipRoutingAddress", address.encode()),
+ ]
+ else:
+ modlist = [
+ (ldap.MOD_DELETE, "objectClass", b"sipRoutingObject"),
+ (ldap.MOD_DELETE, "sipLocalAddress", None),
+ (ldap.MOD_DELETE, "sipRoutingAddress", None),
+
+ (ldap.MOD_ADD, "objectClass", b"sipUser"),
+ (ldap.MOD_ADD, "sipAuthenticationUser", self.sip_id.encode()),
+ (ldap.MOD_ADD, "sipPassword", self._generate_sip_password().encode()),
+ ]
+
+ # Run modification
+ self._modify(modlist)
+
+ # XXX Cache is invalid here
+
+ sip_routing_address = property(get_sip_routing_address, set_sip_routing_address)
@lazy_property
def sip_registrations(self):
return sip_registrations
+ @lazy_property
+ def sip_channels(self):
+ return self.backend.talk.freeswitch.get_sip_channels(self)
+
def get_cdr(self, date=None, limit=None):
return self.backend.talk.freeswitch.get_cdr_by_account(self, date=date, limit=limit)
- @property
- def telephone_numbers(self):
- return self._telephone_numbers + self.mobile_telephone_numbers \
- + self.home_telephone_numbers
+ # Phone Numbers
- @property
- def _telephone_numbers(self):
- return self.attributes.get("telephoneNumber") or []
+ @lazy_property
+ def phone_number(self):
+ """
+ Returns the IPFire phone number
+ """
+ if self.sip_id:
+ return phonenumbers.parse("+4923636035%s" % self.sip_id)
- @property
- def home_telephone_numbers(self):
- return self.attributes.get("homePhone") or []
+ @lazy_property
+ def fax_number(self):
+ if self.sip_id:
+ return phonenumbers.parse("+49236360359%s" % self.sip_id)
+
+ def get_phone_numbers(self):
+ ret = []
+
+ for field in ("telephoneNumber", "homePhone", "mobile"):
+ for number in self._get_phone_numbers(field):
+ ret.append(number)
+
+ return ret
+
+ def set_phone_numbers(self, phone_numbers):
+ # Sort phone numbers by landline and mobile
+ _landline_numbers = []
+ _mobile_numbers = []
+
+ for number in phone_numbers:
+ try:
+ number = phonenumbers.parse(number, None)
+ except phonenumbers.phonenumberutil.NumberParseException:
+ continue
+
+ # Convert to string (in E.164 format)
+ s = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
+
+ # Separate mobile numbers
+ if phonenumbers.number_type(number) == phonenumbers.PhoneNumberType.MOBILE:
+ _mobile_numbers.append(s)
+ else:
+ _landline_numbers.append(s)
+
+ # Save
+ self._set_strings("telephoneNumber", _landline_numbers)
+ self._set_strings("mobile", _mobile_numbers)
+
+ phone_numbers = property(get_phone_numbers, set_phone_numbers)
@property
- def mobile_telephone_numbers(self):
- return self.attributes.get("mobile") or []
+ def _all_telephone_numbers(self):
+ ret = [ self.sip_id, ]
+
+ if self.phone_number:
+ s = phonenumbers.format_number(self.phone_number, phonenumbers.PhoneNumberFormat.E164)
+ ret.append(s)
+
+ for number in self.phone_numbers:
+ s = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
+ ret.append(s)
+
+ return ret
def avatar_url(self, size=None):
if self.backend.debug:
return url
def get_avatar(self, size=None):
- avatar = self._get_first_attribute("jpegPhoto")
+ avatar = self._get_bytes("jpegPhoto")
if not avatar:
return
if image.mode == "RGBA":
image = image.convert("RGB")
- # Resize the image to the desired resolution
- image.thumbnail((size, size), PIL.Image.ANTIALIAS)
+ # Resize the image to the desired resolution (and make it square)
+ thumbnail = PIL.ImageOps.fit(image, (size, size), PIL.Image.ANTIALIAS)
with io.BytesIO() as f:
# If writing out the image does not work with optimization,
# we try to write it out without any optimization.
try:
- image.save(f, "JPEG", optimize=True, quality=98)
+ thumbnail.save(f, "JPEG", optimize=True, quality=98)
except:
- image.save(f, "JPEG", quality=98)
+ thumbnail.save(f, "JPEG", quality=98)
return f.getvalue()
+ def upload_avatar(self, avatar):
+ self._set("jpegPhoto", avatar)
+
+ # SSH Keys
+
+ @lazy_property
+ def ssh_keys(self):
+ ret = []
+
+ for key in self._get_strings("sshPublicKey"):
+ s = sshpubkeys.SSHKey()
+
+ try:
+ s.parse(key)
+ except (sshpubkeys.InvalidKeyError, NotImplementedError) as e:
+ logging.warning("Could not parse SSH key %s: %s" % (key, e))
+ continue
+
+ ret.append(s)
+
+ return ret
+
+ def get_ssh_key_by_hash_sha256(self, hash_sha256):
+ for key in self.ssh_keys:
+ if not key.hash_sha256() == hash_sha256:
+ continue
+
+ return key
+
+ def add_ssh_key(self, key):
+ k = sshpubkeys.SSHKey()
+
+ # Try to parse the key
+ k.parse(key)
+
+ # Check for types and sufficient sizes
+ if k.key_type == b"ssh-rsa":
+ if k.bits < 4096:
+ raise sshpubkeys.TooShortKeyError("RSA keys cannot be smaller than 4096 bits")
+
+ elif k.key_type == b"ssh-dss":
+ raise sshpubkeys.InvalidKeyError("DSA keys are not supported")
+
+ # Ignore any duplicates
+ if key in (k.keydata for k in self.ssh_keys):
+ logging.debug("SSH Key has already been added for %s: %s" % (self, key))
+ return
+
+ # Save key to LDAP
+ self._add_string("sshPublicKey", key)
+
+ # Append to cache
+ self.ssh_keys.append(k)
+
+ def delete_ssh_key(self, key):
+ if not key in (k.keydata for k in self.ssh_keys):
+ return
+
+ # Delete key from LDAP
+ self._delete_string("sshPublicKey", key)
+
if __name__ == "__main__":
a = Accounts()