Example #1
0
def upload_ssl_certificate(d):
    try:
        pki_dir, err = config.get_pki_dir()
        if err:
            raise Exception(err)
        path = '%s/%s' % (pki_dir, d['name'])

        if os.path.exists(path):
            raise Exception('A key of that name already exists')

        os.mkdir(path)
        with open('%s/%s.cert' % (path, d['name']), 'w') as f:
            f.write('-----BEGIN PRIVATE KEY-----\n')
            key_lines = d['private_key'].split()
            if key_lines:
                for line in key_lines:
                    f.write('%s\n' % line)
            f.write('-----END PRIVATE KEY-----\n')
            f.write('-----BEGIN CERTIFICATE-----\n')
            cert_lines = d['certificate'].split()
            if cert_lines:
                for line in cert_lines:
                    f.write('%s\n' % line)
            f.write('-----END CERTIFICATE-----\n')
    except Exception, e:
        return False, 'Error uploading certificate : %s' % str(e)
Example #2
0
def get_ssl_certificates():
    cert_list = []
    try:
        certificates_dir, err = config.get_pki_dir()
        if err:
            raise Exception(err)
        if not certificates_dir:
            raise Exception('No certificates location defined')
        if not os.path.exists(certificates_dir):
            raise Exception('Certificates location does not exist')
        for dirname, dirnames, filenames in os.walk(certificates_dir):
            for subdirname in dirnames:
                cert_path = '%s/%s.cert' % (os.path.join(dirname,
                                                         subdirname), subdirname)
                key_path = '%s/%s.key' % (os.path.join(dirname,
                                                       subdirname), subdirname)
                if not os.path.exists(cert_path):
                    continue
                cert_info, err = parse_ssl_certificate(cert_path)
                if err:
                    continue
                d = {}
                d['name'] = subdirname
                d['certificate'] = cert_info
                cert_list.append(d)
    except Exception, e:
        return None, 'Error loading certificates : %s' % str(e)
Example #3
0
def delete_ssl_certificate(name):
    try:
        pki_dir, err = config.get_pki_dir()
        if err:
            raise Exception(err)
        path = '%s/%s' % (pki_dir, name)
        if not os.path.exists(path):
            raise Exception('Specified certificate name does not exist')
        shutil.rmtree(path)
    except Exception, e:
        return False, 'Error deleting certificate : %s' % str(e)
Example #4
0
def update_ftp_config(config):
    try:
        pki_dir, err = integralstor_config.get_pki_dir()
        if err:
            raise Exception(err)
        with open('/tmp/vsftpd.conf', 'w') as f:
            f.write(
                "# AutoGenerated by IntegralStor. Do not change this file manually \n"
            )
            f.write('anonymous_enable=NO\n')
            f.write('local_enable=YES\n')
            f.write('listen=YES\n')
            f.write('local_umask=022\n')
            f.write('dirmessage_enable=YES\n')
            f.write('connect_from_port_20=YES\n')
            f.write('xferlog_enable=YES\n')
            f.write('xferlog_file=/var/log/xferlog\n')
            f.write('xferlog_std_format=YES\n')
            f.write('ftpd_banner=Welcome to the IntegralStor FTP service.\n')
            f.write('chroot_local_user=YES\n')
            # f.write('user_config_dir=/etc/vsftpd/users\n')
            f.write('local_root=/%s/$USER\n' % config['dataset'])
            f.write('user_sub_token=$USER\n')
            f.write('dirlist_enable=YES\n')
            f.write('download_enable=YES\n')
            f.write('write_enable=YES\n')
            f.write('pam_service_name=vsftpd\n')
            f.write('userlist_enable=YES\n')
            f.write('tcp_wrappers=YES\n')
            if config['ssl_enabled']:
                f.write('ssl_enable=yes\n')
                f.write('rsa_cert_file=%s/%s/%s.cert\n' %
                        (pki_dir, config['cert_name'], config['cert_name']))
                f.write('rsa_private_key_file=%s/%s/%s.cert\n' %
                        (pki_dir, config['cert_name'], config['cert_name']))
                f.write('allow_anon_ssl=NO\n')
                f.write('force_local_data_ssl=YES\n')
                f.write('force_local_logins_ssl=YES\n')
                f.write('ssl_tlsv1=YES\n')
                f.write('ssl_sslv2=NO\n')
                f.write('ssl_sslv3=NO\n')
                f.write('require_ssl_reuse=NO\n')
                f.write('ssl_ciphers=HIGH\n')
            else:
                f.write('ssl_enable=no\n')
        shutil.move('/tmp/vsftpd.conf', '/etc/vsftpd/vsftpd.conf')
        ret, err = services_management.update_service_status(
            'vsftpd', 'restart')
        if err:
            raise Exception(err)
    except Exception, e:
        return False, 'Error updating FTP configuration files : %s' % str(e)
Example #5
0
def generate_self_signed_ssl_certificate(d):
    try:
        pki_dir, err = config.get_pki_dir()
        if err:
            raise Exception(err)
        path = '%s/%s' % (pki_dir, d['name'])

        if os.path.exists(path):
            raise Exception('A key of that name already exists')

        cmd = 'openssl req -new -newkey rsa:'

        if 'key_length' in d:
            key_length = int(d['key_length'])
        else:
            key_length = 1024

        cmd = '%s%d' % (cmd, key_length)

        if 'days' in d:
            cmd = '%s -days %d' % (cmd, int(d['days']))

        subj = ''
        if 'country' in d:
            subj = '%s/C=%s' % (subj, d['country'])
        if 'state' in d:
            subj = '%s/ST=%s' % (subj, d['state'])
        if 'location' in d:
            subj = '%s/L=%s' % (subj, d['location'])
        if 'o' in d:
            subj = '%s/O=%s' % (subj, d['o'])
        if 'ou' in d:
            subj = '%s/OU=%s' % (subj, d['ou'])
        if 'cn' in d:
            subj = '%s/CN=%s' % (subj, d['cn'])
        if 'email' in d:
            subj = '%s/emailAddress=%s' % (subj, d['email'])

        cmd += ' -nodes -x509 -subj %s -keyout %s/%s.cert -out %s/%s.cert' % (
            subj, path, d['name'], path, d['name'])
        # print cmd

        os.mkdir(path)
        lines, err = command.get_command_output(cmd)
        if err:
            if os.path.exists(path):
                shutil.rmtree(path)
            raise Exception(err)

    except Exception, e:
        return False, 'Error generating self signed certificate : %s' % str(e)
def update_https_mode(request):
    return_dict = {}
    try:
        ret, err = django_utils.get_request_parameter_values(
            request, ['change_to'])
        if err:
            raise Exception(err)
        if 'change_to' not in ret:
            raise Exception("Invalid request, please use the menus.")
        change_to = ret['change_to']
        return_dict['change_to'] = change_to

        cert_list, err = pki.get_ssl_certificates()
        if err:
            raise Exception(err)
        if not cert_list:
            raise Exception(
                'No certificates have been created. Please create a certificate/key pair before you change the access method'
            )

        if request.method == "GET":
            if change_to == 'secure':
                form = keys_certs_forms.SetHttpsModeForm(cert_list=cert_list)
                return_dict['form'] = form
                return django.shortcuts.render_to_response(
                    "update_https_mode.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            else:
                return_dict[
                    'conf_message'] = 'Are you sure you want to disable the secure access mode for IntegralView?'
                return django.shortcuts.render_to_response(
                    "update_http_mode_conf.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
        else:
            if change_to == 'secure':
                form = keys_certs_forms.SetHttpsModeForm(request.POST,
                                                         cert_list=cert_list)
                return_dict['form'] = form
                if not form.is_valid():
                    return django.shortcuts.render_to_response(
                        "update_https_mode.html",
                        return_dict,
                        context_instance=django.template.context.
                        RequestContext(request))
                cd = form.cleaned_data
            if change_to == 'secure':
                pki_dir, err = config.get_pki_dir()
                if err:
                    raise Exception(err)
                cert_loc = '%s/%s/%s.cert' % (pki_dir, cd['cert_name'],
                                              cd['cert_name'])
                if not os.path.exists(cert_loc):
                    raise Exception('Error locating certificate')
                ret, err = nginx.generate_nginx_conf(True, cert_loc, cert_loc)
                if err:
                    raise Exception(err)
            else:
                ret, err = nginx.generate_nginx_conf(False)
                if err:
                    raise Exception(err)
            audit_str = "Changed the IntegralView access mode to '%s'" % change_to
            audit.audit("set_https_mode", audit_str, request)

        redirect_url = "https://" if change_to == "secure" else "http://"
        redirect_url = redirect_url + \
            request.META["HTTP_HOST"] + \
            "/system/view_https_mode?ack=set_to_%s" % change_to
        restart, err = tasks_utils.create_task(
            'Chaging IntegralView access mode',
            [{
                'Restarting Web Server': 'service nginx restart'
            }], 2)
        if err:
            raise Exception(err)
        return django.http.HttpResponseRedirect(redirect_url)

    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'Modify Integralview access mode'
        return_dict['tab'] = 'system_info_tab'
        return_dict["error"] = 'Error modifying IntegralView access mode'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def update_https_mode(request):
    return_dict = {}
    try:
        ret, err = django_utils.get_request_parameter_values(request, [
                                                             'change_to'])
        if err:
            raise Exception(err)
        if 'change_to' not in ret:
            raise Exception("Invalid request, please use the menus.")
        change_to = ret['change_to']
        return_dict['change_to'] = change_to

        cert_list, err = pki.get_ssl_certificates()
        if err:
            raise Exception(err)
        if not cert_list:
            raise Exception(
                'No certificates have been created. Please create a certificate/key pair before you change the access method')

        if request.method == "GET":
            if change_to == 'secure':
                form = keys_certs_forms.SetHttpsModeForm(cert_list=cert_list)
                return_dict['form'] = form
                return django.shortcuts.render_to_response("update_https_mode.html", return_dict, context_instance=django.template.context.RequestContext(request))
            else:
                return_dict['conf_message'] = 'Are you sure you want to disable the secure access mode for IntegralView?'
                return django.shortcuts.render_to_response("update_http_mode_conf.html", return_dict, context_instance=django.template.context.RequestContext(request))
        else:
            if change_to == 'secure':
                form = keys_certs_forms.SetHttpsModeForm(
                    request.POST, cert_list=cert_list)
                return_dict['form'] = form
                if not form.is_valid():
                    return django.shortcuts.render_to_response("update_https_mode.html", return_dict, context_instance=django.template.context.RequestContext(request))
                cd = form.cleaned_data
            if change_to == 'secure':
                pki_dir, err = config.get_pki_dir()
                if err:
                    raise Exception(err)
                cert_loc = '%s/%s/%s.cert' % (pki_dir,
                                              cd['cert_name'], cd['cert_name'])
                if not os.path.exists(cert_loc):
                    raise Exception('Error locating certificate')
                ret, err = nginx.generate_nginx_conf(True, cert_loc, cert_loc)
                if err:
                    raise Exception(err)
            else:
                ret, err = nginx.generate_nginx_conf(False)
                if err:
                    raise Exception(err)
            audit_str = "Changed the IntegralView access mode to '%s'" % change_to
            audit.audit("set_https_mode", audit_str, request)

        redirect_url = "https://" if change_to == "secure" else "http://"
        redirect_url = redirect_url + \
            request.META["HTTP_HOST"] + \
            "/system/view_https_mode?ack=set_to_%s" % change_to
        restart, err = tasks_utils.create_task('Chaging IntegralView access mode', [
            {'Restarting Web Server': 'service nginx restart'}], 2)
        if err:
            raise Exception(err)
        return django.http.HttpResponseRedirect(redirect_url)

    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'Modify Integralview access mode'
        return_dict['tab'] = 'system_info_tab'
        return_dict["error"] = 'Error modifying IntegralView access mode'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def main():
    lg = None
    try:
        scripts_log, err = config.get_scripts_log_path()
        if err:
            raise Exception(err)
        lg, err = logger.get_script_logger(
            'Current configuration archive generation',
            scripts_log,
            level=logging.DEBUG)
        config_archives_dir, err = config.get_config_archives_dir_path()
        if err:
            raise Exception(err)

        lck, err = lock.get_lock('generate_current_config_archive')
        if err:
            raise Exception(err)
        if not lck:
            raise Exception('Could not acquire lock.')

        logger.log_or_print('Current config archive generation initiated.',
                            lg,
                            level='info')
        db_path, err = config.get_db_path()
        if err:
            raise Exception(err)
        pki_dir, err = config.get_pki_dir()
        if err:
            raise Exception(err)
        config_file_list = [('/etc/samba/smb.conf', 'smb.conf'),
                            ('/etc/krb5.conf', 'krb5.conf'),
                            (db_path, 'integral_view_config.db'),
                            ('/etc/exports', 'exports'),
                            ('/etc/vsftpd/vsftpd.conf', 'vsftpd.conf'),
                            ('/etc/tgt/targets.conf', 'targets.conf'),
                            ('/etc/resolv.conf', 'resolv.conf'),
                            ('/etc/hosts', 'hosts'), ('/etc/passwd', 'passwd'),
                            ('/etc/group', 'group')]
        config_dir_list = [(pki_dir, 'pki')]

        now_local_epoch, err = datetime_utils.get_epoch(when='now')
        if err:
            raise Exception(err)
        now_local_str, err = datetime_utils.convert_from_epoch(
            now_local_epoch,
            return_format='str',
            str_format='%Y_%m_%d_%H_%M',
            to='local')
        if err:
            raise Exception(err)

        zf_name = 'IntegralSTOR_system_configuration_%s.zip' % now_local_str
        try:
            os.makedirs(config_archives_dir)
        except:
            pass

        try:
            zf = zipfile.ZipFile('%s/%s' % (config_archives_dir, zf_name), 'w')
            for entry in config_file_list:
                if os.path.exists(entry[0]):
                    zf.write(entry[0], arcname=entry[1])
            for entry in config_dir_list:
                if os.path.exists(entry[0]):
                    if entry[0][-1] == '/':
                        path = entry[0][:-1]
                    else:
                        path = entry[0]
                    for root, dirs, files in os.walk(path):
                        base = root[len(path) + 1:]
                        for file in files:
                            if base:
                                zf.write(os.path.join(root, file),
                                         '%s/%s/%s' % (entry[1], base, file))
                            else:
                                zf.write(os.path.join(root, file),
                                         '%s/%s' % (entry[1], file))
            zf.close()
        except Exception as e:
            raise Exception("Error compressing log file : %s" % str(e))
    except Exception, e:
        # print str(e)
        lock.release_lock('generate_current_config_archive')
        logger.log_or_print('Error generating current config archive : %s' % e,
                            lg,
                            level='critical')
        return -1, 'Error generating current config archive: %s' % e