Exemplo n.º 1
0
    def GET(self, profile_type, domain):
        form = web.input()
        domain = web.safestr(domain).lower()

        _wrap = LDAPWrap()
        conn = _wrap.conn

        qr = ldap_lib_domain.get_profile(domain=domain, conn=conn)

        if not qr[0]:
            raise web.seeother('/domains?msg=' + web.urlquote(qr[1]))

        domain_profile = qr[1]['ldif']

        r = ldap_lib_domain.list_accounts(attributes=['domainName'], conn=conn)
        if r[0] is True:
            all_domains = r[1]
        else:
            return r

        domain_account_settings = ldaputils.get_account_setting_from_profile(
            domain_profile)

        (min_passwd_length,
         max_passwd_length) = ldap_lib_general.get_domain_password_lengths(
             domain=domain,
             account_settings=domain_account_settings,
             fallback_to_global_settings=False)

        # Get settings from db.
        _settings = iredutils.get_settings_from_db(
            params=['min_passwd_length', 'max_passwd_length'])
        global_min_passwd_length = _settings['min_passwd_length']
        global_max_passwd_length = _settings['max_passwd_length']

        return web.render(
            'ldap/domain/profile.html',
            cur_domain=domain,
            allDomains=all_domains,
            domain_account_settings=domain_account_settings,
            profile=domain_profile,
            profile_type=profile_type,
            global_min_passwd_length=global_min_passwd_length,
            global_max_passwd_length=global_max_passwd_length,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            timezones=TIMEZONES,
            default_mta_transport=settings.default_mta_transport,
            languagemaps=iredutils.get_language_maps(),
            msg=form.get('msg', None),
        )
Exemplo n.º 2
0
    def GET(self):
        form = web.input()

        db_settings = iredutils.get_settings_from_db()
        min_passwd_length = db_settings['min_passwd_length']
        max_passwd_length = db_settings['max_passwd_length']

        password_policies = iredutils.get_password_policies(
            db_settings=db_settings)

        return web.render('ldap/admin/create.html',
                          languagemaps=iredutils.get_language_maps(),
                          default_language=settings.default_language,
                          min_passwd_length=min_passwd_length,
                          max_passwd_length=max_passwd_length,
                          password_policies=password_policies,
                          msg=form.get('msg'))
Exemplo n.º 3
0
    def GET(self, profile_type, domain):
        form = web.input()
        domain = web.safestr(domain.split('/', 1)[0])
        profile_type = web.safestr(profile_type)

        #check if admin asking for details of correct domain
        admins_of_domain = sql_lib_domain.get_domain_admin_addresses(
            domain=domain)[1]
        if session.get('username') not in admins_of_domain and not session.get(
                'is_global_admin'):
            raise web.seeother(
                '/domains?msg=PERMISSION_DENIED_TRYING_TO_ACCESS_OUT_OF_BOUND_DOMAIN'
            )

        _wrap = SQLWrap()
        conn = _wrap.conn

        result = sql_lib_domain.profile(conn=conn, domain=domain)

        if result[0] is not True:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))

        domain_profile = result[1]

        # Get settings from db.
        _settings = iredutils.get_settings_from_db(
            params=['min_passwd_length', 'max_passwd_length'])
        global_min_passwd_length = _settings['min_passwd_length']
        global_max_passwd_length = _settings['max_passwd_length']

        return web.render(
            'sql/domain/profile.html',
            cur_domain=domain,
            profile_type=profile_type,
            profile=domain_profile,
            default_mta_transport=settings.default_mta_transport,
            domain_settings=sqlutils.account_settings_string_to_dict(
                domain_profile['settings']),
            global_min_passwd_length=global_min_passwd_length,
            global_max_passwd_length=global_max_passwd_length,
            timezones=TIMEZONES,
            # Language
            languagemaps=iredutils.get_language_maps(),
            msg=form.get('msg'),
        )
Exemplo n.º 4
0
def get_domain_password_lengths(domain,
                                account_settings=None,
                                fallback_to_global_settings=False,
                                db_settings=None,
                                conn=None):
    das = {}

    if account_settings:
        das = account_settings
    else:
        if not conn:
            _wrap = LDAPWrap()
            conn = _wrap.conn

        dn = ldaputils.rdn_value_to_domain_dn(domain)
        _filter = '(&(objectClass=mailDomain)(|(domainName={})(domainAliasName={})))'.format(domain, domain)

        _qr = conn.search_s(dn,
                            ldap.SCOPE_BASE,
                            _filter,
                            ['domainName', 'accountSetting'])
        if _qr:
            das = ldaputils.get_account_settings_from_qr(_qr).get(domain, {})

    min_pw_len = das.get('minPasswordLength', 0)
    max_pw_len = das.get('maxPasswordLength', 0)

    if fallback_to_global_settings:
        if not db_settings:
            db_settings = iredutils.get_settings_from_db(params=['min_passwd_length', 'max_passwd_length'])

        if min_pw_len < db_settings['min_passwd_length']:
            min_pw_len = db_settings['min_passwd_length']

        if max_pw_len < db_settings['max_passwd_length']:
            max_pw_len = db_settings['max_passwd_length']

    return (min_pw_len, max_pw_len)
Exemplo n.º 5
0
    def GET(self, profile_type, domain):
        form = web.input()
        domain = web.safestr(domain.split('/', 1)[0])
        profile_type = web.safestr(profile_type)

        _wrap = SQLWrap()
        conn = _wrap.conn

        result = sql_lib_domain.profile(conn=conn, domain=domain)

        if result[0] is not True:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))

        domain_profile = result[1]

        # Get settings from db.
        _settings = iredutils.get_settings_from_db(
            params=['min_passwd_length', 'max_passwd_length'])
        global_min_passwd_length = _settings['min_passwd_length']
        global_max_passwd_length = _settings['max_passwd_length']

        return web.render(
            'sql/domain/profile.html',
            cur_domain=domain,
            profile_type=profile_type,
            profile=domain_profile,
            default_mta_transport=settings.default_mta_transport,
            domain_settings=sqlutils.account_settings_string_to_dict(
                domain_profile['settings']),
            global_min_passwd_length=global_min_passwd_length,
            global_max_passwd_length=global_max_passwd_length,
            timezones=TIMEZONES,
            # Language
            languagemaps=iredutils.get_language_maps(),
            msg=form.get('msg'),
        )
Exemplo n.º 6
0
from libs import iredutils
from tools import ira_tool_lib

web.config.debug = ira_tool_lib.debug
logger = ira_tool_lib.logger

if not (settings.amavisd_enable_logging or settings.amavisd_enable_quarantine):
    sys.exit("Amavisd is not enabled. SKIP.")

backend = settings.backend
logger.info('Backend: %s' % backend)
logger.info('SQL server: %s:%d' %
            (settings.amavisd_db_host, int(settings.amavisd_db_port)))

db_settings = iredutils.get_settings_from_db(params=[
    'amavisd_remove_quarantined_in_days', 'amavisd_remove_maillog_in_days'
])
keep_quar_days = db_settings['amavisd_remove_quarantined_in_days']
keep_inout_days = db_settings['amavisd_remove_maillog_in_days']
query_size_limit = settings.AMAVISD_CLEANUP_QUERY_SIZE_LIMIT

conn_amavisd = ira_tool_lib.get_db_conn('amavisd')

if settings.backend in ['mysql', 'ldap']:
    # Querying (SELECT) without locking. Require MySQL 5.0+ and InnoDB.
    #
    # Since we're dealing with sql records created days ago, no new records
    # will be inserted with that date, it's safe to use dirty read.
    logger.info('Enable dirty read for querying without locking SQL tables.')
    try:
        conn_amavisd.query('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED')
Exemplo n.º 7
0
def add(domain, form, conn=None):
    # Get domain name, username, cn.
    form_domain = form_utils.get_domain_name(form)
    if not (domain == form_domain):
        return (False, 'INVALID_DOMAIN_NAME')

    username = web.safestr(form.get('username')).strip().lower()
    mail = username + '@' + domain
    mail = iredutils.strip_mail_ext_address(mail)

    if not iredutils.is_auth_email(mail):
        return (False, 'INVALID_MAIL')

    if not conn:
        _wrap = LDAPWrap()
        conn = _wrap.conn

    _qr = ldap_lib_general.check_account_existence(mail=mail,
                                                   account_type='mail',
                                                   conn=conn)
    if _qr[0] is not False:
        return (False, 'ALREADY_EXISTS')

    # Get @domainAccountSetting.
    qr = ldap_lib_domain.get_profile(domain=domain, conn=conn)

    if not qr[0]:
        return qr

    domain_profile = qr[1]['ldif']
    domain_status = domain_profile.get('accountStatus', ['disabled'])[0]
    domainAccountSetting = ldaputils.get_account_setting_from_profile(
        domain_profile)

    # Check account number limit.
    _num_users = domainAccountSetting.get('numberOfUsers')
    if _num_users == '-1':
        return (False, 'NOT_ALLOWED')

    _pw_hash = form.get('password_hash', '')
    if _pw_hash:
        if not iredpwd.is_supported_password_scheme(_pw_hash):
            return (False, 'INVALID_PASSWORD_SCHEME')

        passwd_plain = ''
        passwd_hash = _pw_hash
    else:
        (min_pw_len,
         max_pw_len) = ldap_lib_general.get_domain_password_lengths(
             domain=domain,
             account_settings=domainAccountSetting,
             fallback_to_global_settings=False,
             conn=conn,
         )

        qr = form_utils.get_password(form=form,
                                     input_name='newpw',
                                     confirm_pw_input_name='confirmpw',
                                     min_passwd_length=min_pw_len,
                                     max_passwd_length=max_pw_len)

        if qr[0]:
            passwd_plain = qr[1]['pw_plain']
            passwd_hash = qr[1]['pw_hash']
        else:
            return qr

    cn = form_utils.get_name(form=form, input_name="cn")

    # Get preferred language.
    preferred_language = form_utils.get_language(form=form)
    if preferred_language not in iredutils.get_language_maps():
        preferred_language = None

    # Get user quota. Unit is MB.
    quota = form_utils.get_single_value(form=form,
                                        input_name='mailQuota',
                                        default_value=0,
                                        is_integer=True)

    quota = abs(quota)

    if quota == 0:
        # Get per-domain default user quota
        default_user_quota = ldap_lib_domain.get_default_user_quota(
            domain=domain, domain_account_setting=domainAccountSetting)

        quota = default_user_quota

    defaultStorageBaseDirectory = domainAccountSetting.get(
        'defaultStorageBaseDirectory', None)

    db_settings = iredutils.get_settings_from_db()
    # Get mailbox format and folder.
    _mailbox_format = form.get('mailboxFormat', '').lower()
    _mailbox_folder = form.get('mailboxFolder', '')
    if not iredutils.is_valid_mailbox_format(_mailbox_format):
        _mailbox_format = db_settings['mailbox_format']

    if not iredutils.is_valid_mailbox_folder(_mailbox_folder):
        _mailbox_folder = db_settings['mailbox_folder']

    # Get full maildir path
    _mailbox_maildir = form.get('maildir')

    # Get default mailing lists which set in domain accountSetting.
    ldif = iredldif.ldif_mailuser(
        domain=domain,
        username=username,
        cn=cn,
        passwd=passwd_hash,
        quota=quota,
        storage_base_directory=defaultStorageBaseDirectory,
        mailbox_format=_mailbox_format,
        mailbox_folder=_mailbox_folder,
        mailbox_maildir=_mailbox_maildir,
        language=preferred_language,
        domain_status=domain_status,
    )

    dn_user = ldaputils.rdn_value_to_user_dn(mail)

    # Store plain password in additional attribute
    if passwd_plain and settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR:
        ldif += [(settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR,
                  [passwd_plain])]

    try:
        conn.add_s(dn_user, ldif)

        # Update count of accounts
        ldap_lib_general.update_num_domain_current_users(domain=domain,
                                                         increase=True,
                                                         conn=conn)

        log_activity(msg="Create user: %s." % (mail),
                     domain=domain,
                     event='create')

        return (True, )
    except ldap.ALREADY_EXISTS:
        return (False, 'ALREADY_EXISTS')
    except Exception as e:
        return (False, repr(e))
Exemplo n.º 8
0
def update(domain, profile_type, form, conn=None):
    profile_type = str(profile_type)
    domain = str(domain).lower()
    sql_vars = {'domain': domain}

    if not conn:
        _wrap = SQLWrap()
        conn = _wrap.conn

    db_settings = iredutils.get_settings_from_db()

    # Get current domain profile
    qr = simple_profile(conn=conn, domain=domain)
    if qr[0]:
        domain_profile = qr[1]
        domain_settings = sqlutils.account_settings_string_to_dict(
            domain_profile.get('settings', ''))
        del qr
    else:
        return qr

    # Check disabled domain profiles
    disabled_domain_profiles = []
    if not session.get('is_global_admin'):
        disabled_domain_profiles = domain_settings.get(
            'disabled_domain_profiles', [])
        if profile_type in disabled_domain_profiles:
            return (False, 'PERMISSION_DENIED')

    # Pre-defined update key:value.
    updates = {'modified': iredutils.get_gmttime()}

    if profile_type == 'general':
        # Get name
        cn = form.get('cn', '')
        updates['description'] = cn

        # Get default quota for new user.
        default_user_quota = form_utils.get_single_value(
            form=form,
            input_name='defaultQuota',
            default_value=0,
            is_integer=True)
        if default_user_quota > 0:
            domain_settings['default_user_quota'] = default_user_quota
        else:
            if 'default_user_quota' in domain_settings:
                domain_settings.pop('default_user_quota')

    elif profile_type == 'advanced':
        # Update min/max password length in domain setting
        if session.get('is_global_admin') or ('password_policies'
                                              not in disabled_domain_profiles):
            for (_input_name,
                 _key_name) in [('minPasswordLength', 'min_passwd_length'),
                                ('maxPasswordLength', 'max_passwd_length')]:
                try:
                    _length = int(form.get(_input_name, 0))
                except:
                    _length = 0

                if _length > 0:
                    if not session.get('is_global_admin'):
                        # Make sure domain setting doesn't exceed global setting.
                        if _input_name == 'minPasswordLength':
                            # Cannot be shorter than global setting.
                            if _length < db_settings['min_passwd_length']:
                                _length = db_settings['min_passwd_length']
                        elif _input_name == 'maxPasswordLength':
                            # Cannot be longer than global setting.
                            if (db_settings['max_passwd_length'] > 0) and \
                               (_length > db_settings['max_passwd_length'] or _length <= db_settings['min_passwd_length']):
                                _length = db_settings['max_passwd_length']

                    domain_settings[_key_name] = _length
                else:
                    if _key_name in domain_settings:
                        domain_settings.pop(_key_name)

        # Update default language for new user
        default_language = form_utils.get_language(form)
        if default_language in iredutils.get_language_maps():
            domain_settings['default_language'] = default_language

        domain_settings['timezone'] = form_utils.get_timezone(form)

    updates['settings'] = sqlutils.account_settings_dict_to_string(
        domain_settings)
    try:
        conn.update('domain', vars=sql_vars, where='domain=$domain', **updates)

        log_activity(msg="Update domain profile: {} ({}).".format(
            domain, profile_type),
                     domain=domain,
                     event='update')

        return (True, )
    except Exception as e:
        return (False, repr(e))
Exemplo n.º 9
0
def add_user_from_form(domain, form, conn=None):
    # Get domain name, username, cn.
    mail_domain = form_utils.get_domain_name(form)
    mail_username = form.get('username')
    if mail_username:
        mail_username = web.safestr(mail_username).strip().lower()
    else:
        return (False, 'INVALID_ACCOUNT')

    mail = mail_username + '@' + mail_domain

    if mail_domain != domain:
        return (False, 'PERMISSION_DENIED')

    if not iredutils.is_auth_email(mail):
        return (False, 'INVALID_MAIL')

    if not conn:
        _wrap = SQLWrap()
        conn = _wrap.conn

    # Check account existing.
    if sql_lib_general.is_email_exists(mail=mail, conn=conn):
        return (False, 'ALREADY_EXISTS')

    # Get domain profile.
    qr_profile = sql_lib_domain.profile(conn=conn, domain=domain)

    if qr_profile[0] is True:
        domain_profile = qr_profile[1]
        domain_settings = sqlutils.account_settings_string_to_dict(
            domain_profile['settings'])
    else:
        return qr_profile

    # Check account limit.
    num_exist_accounts = sql_lib_admin.num_managed_users(conn=conn,
                                                         domains=[domain])

    if domain_profile.mailboxes == -1:
        return (False, 'NOT_ALLOWED')
    elif domain_profile.mailboxes > 0:
        if domain_profile.mailboxes <= num_exist_accounts:
            return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT')

    # Get quota from <form>
    quota = str(form.get('mailQuota', 0)).strip()
    try:
        quota = int(quota)
    except:
        quota = 0

    #
    # Get password from <form>.
    #
    pw_hash = form.get('password_hash', '')
    newpw = web.safestr(form.get('newpw', ''))
    confirmpw = web.safestr(form.get('confirmpw', ''))

    if pw_hash:
        if not iredpwd.is_supported_password_scheme(pw_hash):
            return (False, 'INVALID_PASSWORD_SCHEME')

        passwd = pw_hash
    else:
        # Get password length limit from domain profile or global setting.
        min_passwd_length = domain_settings.get('min_passwd_length', 0)
        max_passwd_length = domain_settings.get('max_passwd_length', 0)

        qr_pw = iredpwd.verify_new_password(
            newpw,
            confirmpw,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length)

        if qr_pw[0] is True:
            pwscheme = None
            if 'store_password_in_plain_text' in form and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                pwscheme = 'PLAIN'
            passwd = iredpwd.generate_password_hash(qr_pw[1],
                                                    pwscheme=pwscheme)
        else:
            return qr_pw

    # Get display name from <form>
    cn = form_utils.get_single_value(form, input_name='cn', default_value='')

    # Get preferred language.
    preferred_language = form_utils.get_language(form)
    if preferred_language not in iredutils.get_language_maps():
        preferred_language = ''

    # Get storage base directory.
    _storage_base_directory = settings.storage_base_directory
    splited_sbd = _storage_base_directory.rstrip('/').split('/')
    storage_node = splited_sbd.pop()
    storage_base_directory = '/'.join(splited_sbd)
    maildir = iredutils.generate_maildir_path(mail)

    # Read full maildir path from web form - from RESTful API.
    mailbox_maildir = form.get('maildir', '').lower().rstrip('/')
    if mailbox_maildir and os.path.isabs(mailbox_maildir):
        # Split storageBaseDirectory and storageNode
        _splited = mailbox_maildir.rstrip('/').split('/')
        storage_base_directory = '/' + _splited[0]
        storage_node = _splited[1]
        maildir = '/'.join(_splited[2:])

    record = {
        'domain': domain,
        'username': mail,
        'password': passwd,
        'name': cn,
        'quota': quota,
        'storagebasedirectory': storage_base_directory,
        'storagenode': storage_node,
        'maildir': maildir,
        'language': preferred_language,
        'passwordlastchange': iredutils.get_gmttime(),
        'created': iredutils.get_gmttime(),
        'active': 1
    }

    # Get settings from SQL db.
    db_settings = iredutils.get_settings_from_db()

    # Get mailbox format and folder.
    _mailbox_format = form.get('mailboxFormat',
                               db_settings['mailbox_format']).lower()
    _mailbox_folder = form.get('mailboxFolder', db_settings['mailbox_folder'])
    if iredutils.is_valid_mailbox_format(_mailbox_format):
        record['mailboxformat'] = _mailbox_format

    if iredutils.is_valid_mailbox_folder(_mailbox_folder):
        record['mailboxfolder'] = _mailbox_folder

    # Always store plain password in another attribute.
    if settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR:
        record[settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR] = newpw

    # Set disabled mail services.
    disabled_mail_services = domain_settings.get('disabled_mail_services', [])
    for srv in disabled_mail_services:
        record['enable' + srv] = 0

    # globally disabled mail services
    for srv in settings.ADDITIONAL_DISABLED_USER_SERVICES:
        record['enable' + srv] = 0

    # globally enabled mail services
    for srv in settings.ADDITIONAL_ENABLED_USER_SERVICES:
        record['enable' + srv] = 1

    try:
        # Store new user in SQL db.
        conn.insert('mailbox', **record)

        # Create an entry in `vmail.forwardings` with `address=forwarding`
        conn.insert('forwardings',
                    address=mail,
                    forwarding=mail,
                    domain=domain,
                    dest_domain=domain,
                    is_forwarding=1,
                    active=1)

        log_activity(msg="Create user: %s." % (mail),
                     domain=domain,
                     event='create')
        return (True, )
    except Exception as e:
        return (False, repr(e))