Пример #1
0
    def startup(self):
        if self.local:
            ldap_server = 'localhost'
        else:
            ldap_server = self.server

        ldap_server = Server("ldaps://{}:1636".format(self.server), use_ssl=True)
        self.conn = Connection(ldap_server, user="******", password=self.ldap_password)
        r = self.conn.bind()
        if not r:
            print "Can't conect to LDAP Server"
            return False

        self.container = '/opt/gluu-server-{}'.format(self.gluu_version)
        if not self.local:
            print "NOT LOCAL?"

            sys.path.append("..")
            from clustermgr.core.remote import RemoteClient
            self.c = RemoteClient(self.server)
            self.c.startup()
        else:
            self.c = FakeRemote()
            if os.path.exists('/etc/gluu/conf/ox-ldap.properties'):
                self.container = '/'
                self.c.fake_remote = True


        self.installer = Installer(self.c, self.gluu_version, self.os_type)

        self.appliance_inum = self.get_appliance_inum()
        self.base_inum = self.get_base_inum()

        return True
Пример #2
0
def httpd_certs():

    app_config = AppConfiguration.query.first()

    server = Server.query.filter_by(primary_server=True).first()

    installer = Installer(server, app_config.gluu_version, logger_tid=None)
    httpd_key_io = installer.c.get_file(
        os.path.join(installer.container, 'etc/certs/httpd.key'))

    if httpd_key_io[0]:
        httpd_key = httpd_key_io[1].read(
        )  #.replace('-----BEGIN RSA PRIVATE KEY-----','').replace('-----END RSA PRIVATE KEY-----','').strip()

    httpd_crt_io = installer.c.get_file(
        os.path.join(installer.container, 'etc/certs/httpd.crt'))

    if httpd_crt_io[0]:
        httpd_crt = httpd_crt_io[1].read(
        )  #.replace('-----BEGIN CERTIFICATE-----','').replace('-----END CERTIFICATE-----','').strip()

    cert_form = httpdCertificatesForm()
    cert_form.httpd_key.data = httpd_key
    cert_form.httpd_crt.data = httpd_crt

    return render_template('httpd_certificates.html', cert_form=cert_form)
Пример #3
0
def app_configuration():
    """This view provides application configuration forms"""

    # create forms
    conf_form = AppConfigForm()
    sch_form = SchemaForm()
    config = AppConfiguration.query.first()
    schemafiles = os.listdir(app.config['SCHEMA_DIR'])

    conf_form.gluu_archive.choices = [
        (f, os.path.split(f)[1]) for f in glob.glob(
            os.path.join(app.config['GLUU_REPO'], 'gluu-server-*'))
    ]

    # If the form is submitted and password for replication user was not
    # not supplied, make password "**dummy**", so don't change
    # what we have before

    #external_lb_checked = False
    external_lb_checked = conf_form.external_load_balancer.data

    if request.method == 'POST':

        if conf_form.gluu_version.data < '3.1.4':
            conf_form.use_ldap_cache.data = False

        if config and not conf_form.replication_pw.data.strip():
            conf_form.replication_pw.validators = []
            conf_form.replication_pw_confirm.validators = []

        if conf_form.external_load_balancer.data:
            conf_form.nginx_ip.validators = []

        print "OFFLINE", conf_form.offline.data, conf_form.gluu_archive.data

        if not conf_form.offline.data:
            del conf_form._fields['gluu_archive']

    if not config:
        #del conf_form.replication_pw
        #del conf_form.replication_pw_confirm
        config = AppConfiguration()
        db.session.add(config)

    # If form is submitted and validated process it
    if conf_form.update.data and conf_form.validate_on_submit():

        if config.replication_pw:
            new_replication_passwd = conf_form.replication_pw.data.strip()
            if conf_form.replication_pw.data:

                c = None
                server = Server.query.first()

                if server:

                    c = RemoteClient(server.hostname, ip=server.ip)

                    try:
                        c.startup()
                    except Exception as e:
                        flash(
                            "Can't establish SSH connection to {}. "
                            "Replication password is not changed".format(
                                server.hostname), "warning")
                    if c:

                        installer = Installer(c, config.gluu_version,
                                              server.os)

                        cmd = (
                            '/opt/opendj/bin/ldappasswordmodify --bindDN '
                            '\'cn=Directory Manager\' --bindPassword $\'{}\' '
                            '--port 4444 --newPassword $\'{}\' --authzID '
                            '\'cn=admin,cn=Administrators,cn=admin data\' '
                            '--trustAll --useSSL'.format(
                                server.ldap_password.replace("'", "\\'"),
                                new_replication_passwd.replace("'", "\\'"),
                            ))

                        result = installer.run(cmd)
                        if result[1].strip() == \
                        'The LDAP password modify operation was successful':
                            flash("Replication password is changed", "success")
                            config.replication_pw = new_replication_passwd

        config.gluu_version = conf_form.gluu_version.data.strip()
        config.nginx_host = conf_form.nginx_host.data.strip()
        config.nginx_ip = conf_form.nginx_ip.data.strip()
        config.modify_hosts = conf_form.modify_hosts.data

        config.ldap_update_period = conf_form.ldap_update_period.data
        config.ldap_update_period_unit = 's'
        config.external_load_balancer = conf_form.external_load_balancer.data
        config.use_ldap_cache = conf_form.use_ldap_cache.data

        if conf_form.offline.data:
            config.offline = True
            config.gluu_archive = conf_form.gluu_archive.data
        else:
            config.offline = False
            config.gluu_archive = ''

        if getattr(conf_form, 'replication_pw'):
            if conf_form.replication_pw_confirm.data:
                config.replication_pw = conf_form.replication_pw.data.strip()

        config.gluu_version = conf_form.gluu_version.data.strip()

        db.session.commit()

        flash(
            "Gluu Cluster Manager application configuration has been "
            "updated.", "success")

    elif sch_form.upload.data and sch_form.validate_on_submit():
        f = sch_form.schema.data
        filename = secure_filename(f.filename)
        if any(filename in s for s in schemafiles):
            name, extension = os.path.splitext(filename)
            matches = [s for s in schemafiles if name in s]
            filename = name + "_" + str(len(matches)) + extension
        f.save(os.path.join(app.config['SCHEMA_DIR'], filename))
        schemafiles.append(filename)
        flash(
            "Schema: {0} has been uploaded sucessfully. "
            "Please edit slapd.conf of primary server and "
            "re-deploy all servers.".format(filename), "success")

    # request.method == GET gets processed here
    if config:
        conf_form.nginx_host.data = config.nginx_host
        conf_form.modify_hosts.data = config.modify_hosts
        conf_form.nginx_ip.data = config.nginx_ip
        conf_form.external_load_balancer.data = config.external_load_balancer
        conf_form.use_ldap_cache.data = config.use_ldap_cache
        conf_form.offline.data = config.offline

        service_status_update_period = config.ldap_update_period

        if service_status_update_period and config.ldap_update_period_unit != 's':
            service_status_update_period = service_status_update_period * 60

        conf_form.ldap_update_period.data = str(service_status_update_period)

        #conf_form.use_ip.data = config.use_ip
        if config.gluu_version:
            conf_form.gluu_version.data = config.gluu_version

    if not config.id:
        conf_form.use_ldap_cache.data = True

    #create fake remote class that provides the same interface with RemoteClient
    fc = FakeRemote()

    #Getermine local OS type
    localos = get_os_type(fc)

    app.jinja_env.globals['use_ldap_cache'] = config.use_ldap_cache

    return render_template(
        'app_config.html',
        cform=conf_form,
        sform=sch_form,
        config=config,
        schemafiles=schemafiles,
        localos=localos,
        external_lb_checked=external_lb_checked,
        repo_dir=app.config['GLUU_REPO'],
        next=request.args.get('next'),
    )
Пример #4
0
class ChangeGluuHostname:
    def __init__(self, old_host, new_host, cert_city, cert_mail, cert_state,
                    cert_country, ldap_password, os_type, ip_address, 
                    gluu_version='', server='localhost', local=True):

        self.old_host = old_host
        self.new_host = new_host
        self.ip_address = ip_address
        self.cert_city = cert_city
        self.cert_mail = cert_mail
        self.cert_state = cert_state
        self.cert_country = cert_country
        self.server = server
        self.ldap_password = ldap_password
        self.os_type = os_type
        self.gluu_version = gluu_version
        self.local = local
        self.base_inum = None
        self.appliance_inum = None


    def startup(self):
        if self.local:
            ldap_server = 'localhost'
        else:
            ldap_server = self.server

        ldap_server = Server("ldaps://{}:1636".format(self.server), use_ssl=True)
        self.conn = Connection(ldap_server, user="******", password=self.ldap_password)
        r = self.conn.bind()
        if not r:
            print "Can't conect to LDAP Server"
            return False

        self.container = '/opt/gluu-server-{}'.format(self.gluu_version)
        if not self.local:
            print "NOT LOCAL?"

            sys.path.append("..")
            from clustermgr.core.remote import RemoteClient
            self.c = RemoteClient(self.server)
            self.c.startup()
        else:
            self.c = FakeRemote()
            if os.path.exists('/etc/gluu/conf/ox-ldap.properties'):
                self.container = '/'
                self.c.fake_remote = True


        self.installer = Installer(self.c, self.gluu_version, self.os_type)

        self.appliance_inum = self.get_appliance_inum()
        self.base_inum = self.get_base_inum()

        return True
    def get_appliance_inum(self):
        self.conn.search(search_base='ou=appliances,o=gluu',
                    search_filter='(objectclass=*)',
                    search_scope=SUBTREE, attributes=['inum'])

        for r in self.conn.response:
            if r['attributes']['inum']:
                return r['attributes']['inum'][0]


    def get_base_inum(self):
        self.conn.search(search_base='o=gluu',
                search_filter='(objectclass=gluuOrganization)',
                search_scope=SUBTREE, attributes=['o'])

        for r in self.conn.response:
            if r['attributes']['o']:
                return r['attributes']['o'][0]


    def change_appliance_config(self):
        print "Changing LDAP Applience configurations"
        config_dn = 'ou=configuration,inum={},ou=appliances,o=gluu'.format(
                    self.appliance_inum)


        for dns, cattr in (
                    ('', 'oxIDPAuthentication'),
                    ('oxauth', 'oxAuthConfDynamic'),
                    ('oxidp', 'oxConfApplication'),
                    ('oxtrust', 'oxTrustConfApplication'),
                    ):
            if dns:
                dn = 'ou={},{}'.format(dns, config_dn)
            else:
                dn = 'inum={},ou=appliances,o=gluu'.format(self.appliance_inum)

            self.conn.search(search_base=dn,
                        search_filter='(objectClass=*)',
                        search_scope=BASE, attributes=[cattr])

            config_data = json.loads(self.conn.response[0]['attributes'][cattr][0])

            for k in config_data:
                kVal = config_data[k]
                if type(kVal) == type(u''):
                    if self.old_host in kVal:
                        kVal=kVal.replace(self.old_host, self.new_host)
                        config_data[k]=kVal

            config_data = json.dumps(config_data)
            self.conn.modify(dn, {cattr: [MODIFY_REPLACE, config_data]})


    def change_clients(self):
        print "Changing LDAP Clients configurations"
        dn = "ou=clients,o={},o=gluu".format(self.base_inum)
        self.conn.search(search_base=dn,
                    search_filter='(objectClass=oxAuthClient)',
                    search_scope=SUBTREE, attributes=[
                                                'oxAuthPostLogoutRedirectURI',
                                                'oxAuthRedirectURI',
                                                'oxClaimRedirectURI',
                                                ])

        result = self.conn.response[0]['attributes']

        dn = self.conn.response[0]['dn']

        for atr in result:
            for i in range(len(result[atr])):
                changeAttr = False
                if self.old_host in result[atr][i]:
                    changeAttr = True
                    result[atr][i] = result[atr][i].replace(self.old_host, self.new_host)
                    self.conn.modify(dn, {atr: [MODIFY_REPLACE, result[atr]]})



    def change_uma(self):
        print "Changing LDAP UMA Configurations"

        for ou, cattr in (
                    ('resources','oxResource'),
                    ('scopes', 'oxId'),
                    ):

            dn = "ou={},ou=uma,o={},o=gluu".format(ou, self.base_inum)

            self.conn.search(search_base=dn, search_filter='(objectClass=*)', search_scope=SUBTREE, attributes=[cattr])
            result = self.conn.response

            for r in result:
                for i in range(len( r['attributes'][cattr])):
                    changeAttr = False
                    if self.old_host in r['attributes'][cattr][i]:
                        r['attributes'][cattr][i] = r['attributes'][cattr][i].replace(self.old_host, self.new_host)
                        self.conn.modify(r['dn'], {cattr: [MODIFY_REPLACE, r['attributes'][cattr]]})


    def change_httpd_conf(self):
        print "Changing httpd configurations"
        if 'CentOS' in self.os_type:

            httpd_conf = os.path.join(self.container, 'etc/httpd/conf/httpd.conf')
            https_gluu = os.path.join(self.container, 'etc/httpd/conf.d/https_gluu.conf')
            conf_files = [httpd_conf, https_gluu]

        elif 'Ubuntu' in self.os_type:
            https_gluu = os.path.join(self.container, 'etc/apache2/sites-available/https_gluu.conf')
            conf_files = [https_gluu]

        for conf_file in conf_files:
            result, fileObj = self.c.get_file(conf_file)
            if result:
                config_text = fileObj.read()
                config_text = config_text.replace(self.old_host, self.new_host)
                self.c.put_file(conf_file, config_text)

    def create_new_certs(self):
        print "Backing up certificates"
        cmd_list = [
            'mkdir /etc/certs/backup',
            'cp /etc/certs/* /etc/certs/backup'
            ]
        for cmd in cmd_list:
            print self.installer.run(cmd)

        print "Creating certificates"
        cmd_list = [
            '/usr/bin/openssl genrsa -des3 -out /etc/certs/{0}.key.orig -passout pass:secret 2048',
            '/usr/bin/openssl rsa -in /etc/certs/{0}.key.orig -passin pass:secret -out /etc/certs/{0}.key',
            '/usr/bin/openssl req -new -key /etc/certs/{0}.key -out /etc/certs/{0}.csr -subj '
            '"/C={4}/ST={5}/L={1}/O=Gluu/CN={2}/emailAddress={3}"'.format('{0}', self.cert_city, self.new_host, self.cert_mail, self.cert_country, self.cert_state),
            '/usr/bin/openssl x509 -req -days 365 -in /etc/certs/{0}.csr -signkey /etc/certs/{0}.key -out /etc/certs/{0}.crt',
            'chown root:gluu -R /etc/certs/',
            'chown jetty:jetty /etc/certs/oxauth-keys*'
            ]

        cert_list = ['httpd', 'idp-encryption', 'idp-signing', 'shibIDP', 'opendj', 'passport-sp']

        for crt in cert_list:

            for cmd in cmd_list:
                cmd = cmd.format(crt)
                print self.installer.run(cmd)


            if not crt == 'saml.pem':

                del_key = ( '/opt/jre/bin/keytool -delete -alias {}_{} -keystore '
                        '/opt/jre/jre/lib/security/cacerts -storepass changeit').format(self.old_host, crt)


                r = self.installer.run(del_key)

                add_key = ('/opt/jre/bin/keytool -import -trustcacerts -alias '
                      '{0}_{1} -file /etc/certs/{2}.crt -keystore '
                      '/opt/jre/jre/lib/security/cacerts -storepass changeit -noprompt').format(self.new_host, crt, crt)

                r = self.installer.run(add_key)

        self.installer.run('chown jetty:jetty /etc/certs/oxauth-keys.*')

    def modify_saml_passport(self):
        print "Modifying SAML & Passport if installed"
        
        files = [
            '/opt/gluu-server-{0}/opt/shibboleth-idp/conf/idp.properties'.format(self.gluu_version),
            '/opt/gluu-server-{0}/etc/gluu/conf/passport-config.json'.format(self.gluu_version),
            ]

        for fn in files:
            if self.c.exists(fn):
                print "Modifying Shibboleth {0}".format(fn)
                r = self.c.get_file(fn)
                if r[0]:
                    f = r[1].read()
                    f = f.replace(self.old_host, self.new_host)
                    print self.c.put_file(fn, f)

    def change_host_name(self):
        print "Changing hostname"
        hostname_file = os.path.join(self.container, 'etc/hostname')
        print self.c.put_file(hostname_file, self.new_host)

    def modify_etc_hosts(self):
        print "Modifying /etc/hosts"
        hosts_file = os.path.join(self.container, 'etc/hosts')
        r = self.c.get_file(hosts_file)
        if r[0]:
            old_hosts = r[1]
            news_hosts = modify_etc_hosts([(self.new_host, self.ip_address)], old_hosts, self.old_host)
            print self.c.put_file(hosts_file, news_hosts)