예제 #1
0
파일: monit.py 프로젝트: optionalg/drop
    def run(self, context):
        complete = super(monitSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        # XXX Monit wants to talk directly to the mail server and so far
        #     we are using ssmtp instead of a local maildrop.
        monit_conf = os.path.join(context.value('etcDir'), 'monitrc')
        notify_email = context.value('notifyEmail')
        if notify_email:
            email_host = context.value('emailHost')
            email_port = context.value('emailPort')
            email_host_user = context.value('emailHostUser')
            email_host_password = context.value('emailHostPassword')
            setup.modify_config(monit_conf, settings={
                'mailserver': "%(email_host)s port %(email_port)s,"\
            " username %(email_host_user)s password %(email_host_password)s"\
            " using tlsv1" % {'email_host': email_host,
                              'email_port': email_port,
                              'email_host_user': email_host_user,
                              'email_host_password': email_host_password,
                             },
                'mail-format': "{ from: %s }" % notify_email,
                'alert': notify_email
            }, context=context)

        return complete
예제 #2
0
파일: syslog.py 프로젝트: optionalg/drop
    def run(self, context):
        complete = super(syslog_ngSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        journald_conf = "/etc/systemd/journald.conf"
        setup.modify_config(journald_conf,
                            settings={'ForwardToSyslog': "yes"},
                            sep='=',
                            context=context)

        setup.postinst.shellCommand(
            ['rm', '-f', '/etc/systemd/system/syslog.service'])

        # Configure SELinux to run syslog-ng
        syslog_te = os.path.join(
            os.path.dirname(setup.postinst.postinst_run_path), 'syslog-ng.te')

        _, syslog_te_path = stageFile(syslog_te, context)
        with open(syslog_te_path, 'w') as syslog_te_file:
            syslog_te_file.write(self.syslog_te_config_template)
        setup.postinst.install_selinux_module(
            syslog_te, comment="Configure SELinux to run syslog-ng.")

        return complete
예제 #3
0
    def run(self, context):
        complete = super(cronSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        anacrontab_conf = os.path.join(context.value('etcDir'), 'anacrontab')
        crontab_conf = os.path.join(context.value('etcDir'), 'crontab')
        notify_email = context.value('notifyEmail')
        if notify_email:
            modify_config(anacrontab_conf,
                          settings={'MAILTO': notify_email},
                          context=context)
            modify_config(crontab_conf,
                          settings={'MAILTO': notify_email},
                          context=context)

        for key, vals in six.iteritems(self.managed['iptables']['files']):
            if key.startswith('/etc/cron.d'):
                for cmds in vals:
                    lines = cmds[0]
                    _, cron = stageFile(key, context=context)
                    cronfile = open(cron, 'w')
                    cronfile.write('# m  h dom mon dow command\n')
                    cronfile.write(lines)
                    cronfile.close()
        return complete
예제 #4
0
    def run(self, context):
        complete = super(fail2banSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        jail_conf = os.path.join(context.value('etcDir'), 'fail2ban',
                                 'jail.conf')
        # XXX in filter.d/apache-badbots.conf:
        # ^<HOST> -.*"(GET|POST).*(\.php|\.asp|\.exe|\.pl).*HTTP.*".*$
        # jail.conf:
        # apache-badbots: /var/log/nginx/*-access.log

        # XXX /etc/fail2ban/jail.conf
        # 1. sendmail-whois[name=SSH, dest=root, [email protected]]
        # 2. add fail2ban user or use root.
        # XXX nginx settings!
        jail_settings = {
            'apache': {
                'enabled': 'true'
            },
            'apache-noscript': {
                'enabled': 'true'
            },
            'apache-overflows': {
                'enabled': 'true'
            },
            'ssh-iptables': {
                'maxretry': '3'
            },
            'spamassassin': {
                'enabled': 'true',
                'bantime': '3600',
                'port': 'http,https,smtp,ssmtp',
                'filter': 'spamassassin',
                'logpath': '/var/log/mail.log'
            }
        }
        try:
            notify_email = context.value('notifyEmail')
            jail_settings.update({
                'destemail': notify_email,
                'sender': notify_email
            })
        except Error:
            # We don't have an e-mail to send notification to
            pass

        modify_config(jail_conf, settings=jail_settings, context=context)
        # XXX http://blog.darkseer.org/wordpress/?p=149
        # Add in /etc/fail2ban/filter.d/sshd.conf
        # ^%(__prefix_line)sReceived disconnect from <HOST>: \
        # 11: Bye Bye \[preauth\]\s*$
        return complete
예제 #5
0
파일: openssh.py 프로젝트: optionalg/drop
    def run(self, context):
        complete = super(openssh_serverSetup, self).run(context)
        ldapHost = context.value('ldapHost')
        domain_parts = tuple(context.value('companyDomain').split('.'))
        banner = os.path.join(context.value('etcDir'), 'issue.net')
        _, new_banner_path = stageFile(banner, context=context)
        with open(new_banner_path, 'w') as new_banner:
            new_banner.write(
                'This server is private property. Authorized use only.\n')
        settings = {'Banner': banner}
        for key, vals in six.iteritems(
                self.managed['openssh-server']['files']):
            if key == self.sshd_conf:
                settings.update(vals[0][0])
        modify_config(self.sshd_conf,
                      settings=settings,
                      sep=' ',
                      context=context)

        ldapCertPath = os.path.join(context.value('etcDir'), 'pki', 'tls',
                                    'certs', '%s.crt' % ldapHost)
        names = {
            'ldapHost': ldapHost,
            'domainNat': domain_parts[0],
            'domainTop': domain_parts[1],
            'ldapCertPath': ldapCertPath
        }
        modify_config(
            self.ldap_conf,
            settings={
                'URI': 'ldaps://%(ldapHost)s' % names,
                'BASE': 'ou=people,dc=%(domainNat)s,dc=%(domainTop)s' % names,
                'TLS_CACERT': ldapCertPath,
                'TLS_REQCERT': 'demand',
                'TIMELIMIT': '15',
                'TIMEOUT': '20'
            },
            sep=' ',
            context=context)

        config_path = os.path.join('/usr', 'libexec', 'openssh',
                                   'ssh-ldap-wrapper')
        _, new_config_path = stageFile(config_path, context)
        with open(new_config_path, 'w') as new_config:
            new_config.write("""#!/bin/sh
if [ "$1" == "fedora" ] ; then
    exit 1
fi
exec /usr/libexec/openssh/ssh-ldap-helper -s "$1"
""")
        postinst.shellCommand(['chmod', '755', config_path])
        postinst.shellCommand(['chmod', '644', self.ldap_conf])
        return complete
예제 #6
0
파일: openssh.py 프로젝트: smirolo/drop
    def run(self, context):
        complete = super(openssh_serverSetup, self).run(context)
        banner = os.path.join(context.SYSCONFDIR, 'issue.net')
        _, new_banner_path = stageFile(
            banner, context=context)
        with open(new_banner_path, 'w') as new_banner:
            new_banner.write(
                'This server is private property. Authorized use only.\n')
        settings = {'Banner': banner}
        for key, vals in self.files.iteritems():
            if key == self.sshd_conf:
                settings.update(vals[0][0])
        modify_config(self.sshd_conf,
            settings=settings, sep=' ', context=context)

        ldapDomain = 'dbs.internal'
        domain_parts = tuple(context.value('domainName').split('.'))
        ldapCertPath = os.path.join(context.SYSCONFDIR,
            'pki', 'tls', 'certs', '%s.crt' % ldapDomain)
        names = {
            'ldapDomain': ldapDomain,
            'domainNat': domain_parts[0],
            'domainTop': domain_parts[1],
            'ldapCertPath': ldapCertPath
        }
        modify_config(self.ldap_conf,
            settings={
                'URI': 'ldaps://%(ldapDomain)s' % names,
                'BASE': 'ou=people,dc=%(domainNat)s,dc=%(domainTop)s' % names,
                'TLS_CACERT': ldapCertPath,
                'TLS_REQCERT': 'demand',
                'TIMELIMIT': '15',
                'TIMEOUT': '20'
            }, sep=' ', context=context)

        config_path = os.path.join(
            '/usr', 'libexec', 'openssh', 'ssh-ldap-wrapper')
        _, new_config_path = stageFile(config_path, context)
        with open(new_config_path, 'w') as new_config:
            new_config.write(
"""#!/bin/sh
if [ "$1" == "fedora" ] ; then
    exit 1
fi
exec /usr/libexec/openssh/ssh-ldap-helper -s "$1"
""")
        postinst.shellCommand(['chmod', '755', config_path])
        postinst.shellCommand(['chmod', '644', self.ldap_conf])
        return complete
예제 #7
0
파일: sldap.py 프로젝트: optionalg/drop
    def run(self, context):
        complete = super(openldap_clientsSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        ldapHost = context.value('ldapHost')
        modify_config(os.path.join(context.value('etcDir'),
            'openldap', 'ldap.conf'), sep=' ', context=context,
            settings={
                'TLS_CACERT': os.path.join(
                    context.value('etcDir'), 'pki', 'tls', 'certs',
                    '%s.crt' % ldapHost),
                'TLS_REQCERT': 'demand'})

        return complete
예제 #8
0
파일: sldap.py 프로젝트: smirolo/drop
    def run(self, context):
        complete = super(openldap_clientsSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        domain = 'dbs.internal'
        modify_config(os.path.join(context.SYSCONFDIR,
            'openldap', 'ldap.conf'), sep=' ', context=context,
            settings={
                'TLS_CACERT': os.path.join(
                    context.SYSCONFDIR, 'pki', 'tls', 'certs',
                    '%s.crt' % domain),
                'TLS_REQCERT': 'demand'})

        return complete
예제 #9
0
    def run(self, context):
        complete = super(sstmpSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        revaliases_conf = os.path.join(
            context.value('etcDir'), 'ssmtp', 'revaliases')
        sstmp_conf = os.path.join(
            context.value('etcDir'), 'ssmtp', 'ssmtp.conf')

        domain = context.value('domainName')
        notify_email = context.value('notifyEmail')
        if notify_email:
            email_host = context.value('emailHost')
            email_port = context.value('emailPort')
            email_host_user = context.value('emailHostUser')
            email_host_password = context.value('emailHostPassword')
            modify_config(sstmp_conf, settings={
                'root': notify_email,
                'mailhub': email_host,
                'RewriteDomain': domain,
                'Hostname': domain,
                'FromLineOverride': "NO",
                'UseSTARTTLS': "YES",
                'UseTLS': "YES",
                'AuthUser': email_host_user,
                'AuthPass': email_host_password
            }, sep='=', context=context)
            modify_config(revaliases_conf, settings={
                'root': notify_email
            }, sep=':', context=context)

        return complete
예제 #10
0
    def run(self, context):
        complete = super(postgresql_serverSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        db_host = context.value('dbHost')
        vpc_cidr = context.value('vpc_cidr')
        pg_user = context.value('dbUser')
        postgresql_conf = os.path.join(self.pgdata, 'postgresql.conf')
        pg_ident_conf = os.path.join(self.pgdata, 'pg_ident.conf')
        pg_hba_conf = os.path.join(self.pgdata, 'pg_hba.conf')

        if not os.path.exists(postgresql_conf):
            # /var/lib/pgsql/data will be empty unless we run initdb once.
            shell_command([self.postgresql_setup, 'initdb'])

        listen_addresses = "'localhost'"
        for key, val in six.iteritems(
                self.managed['%s-server' %
                             self.daemons[0].replace('-', '')]['files']):
            if key == 'listen_addresses':
                listen_addresses = ', '.join(
                    ["'%s'" % address[0] for address in val])

        postgresql_conf_settings = {'listen_addresses': listen_addresses}
        if db_host:
            db_ssl_key_file = "/etc/pki/tls/private/%s.key" % db_host
            db_ssl_cert_file = "/etc/pki/tls/certs/%s.crt" % db_host
            dh_params = "/etc/ssl/certs/dhparam.pem"
            if (os.path.exists(db_ssl_key_file)
                    and os.path.exists(db_ssl_cert_file)):
                postgresql_conf_settings.update({
                    'ssl':
                    "on",
                    'ssl_cert_file':
                    "'%s'" % db_ssl_cert_file,
                    'ssl_key_file':
                    "'%s'" % db_ssl_key_file,
                    'ssl_prefer_server_ciphers':
                    "on",
                    #ssl_ca_file = ''
                    #ssl_crl_file = ''
                    #ssl_ecdh_curve = 'prime256v1'
                    #ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
                })
                if os.path.exists(dh_params):
                    postgresql_conf_settings.update({
                        'ssl_dh_params_file':
                        "'%s'" % dh_params,
                    })
                postinst.shellCommand(
                    ['chown', 'root:postgres', db_ssl_key_file])
                postinst.shellCommand(['chmod', '640', db_ssl_key_file])
                postinst.shellCommand(
                    ['chmod', '755',
                     os.path.dirname(db_ssl_key_file)])
        modify_config(postgresql_conf,
                      settings=postgresql_conf_settings,
                      sep=' = ',
                      context=context)

        # pg_ident
        system_to_pg_mapping = {'postgres': 'postgres'}
        if pg_user:
            system_to_pg_mapping.update({'/^(.*)$': pg_user})
        else:
            logging.warning("dbUser is '%s'. No regular user will be created"\
                " to access the database remotely.")
        old_conf_path, new_conf_path = stageFile(pg_ident_conf, context)
        with open(new_conf_path, 'w') as new_conf:
            with open(old_conf_path) as old_conf:
                for line in old_conf.readlines():
                    look = re.match(r'^mymap\s+(\S+)\s+(\S+)', line.strip())
                    if look:
                        system_user = look.group(1)
                        if system_user in system_to_pg_mapping:
                            self.write_ident_line(
                                new_conf, system_user,
                                system_to_pg_mapping[system_user])
                            del system_to_pg_mapping[system_user]
                    else:
                        new_conf.write(line)
                for system_user, pgident_user in six.iteritems(
                        system_to_pg_mapping):
                    self.write_ident_line(new_conf, system_user, pgident_user)

        # pg_hba
        connections = [
            ['all', 'postgres', vpc_cidr],
            # 'all' because we need to add a constraint on auth_user
            ['all', pg_user, vpc_cidr]
        ]
        old_conf_path, new_conf_path = stageFile(pg_hba_conf, context)
        with open(new_conf_path, 'w') as new_conf:
            with open(old_conf_path) as old_conf:
                source_host = 'host'
                if (postgresql_conf_settings.get('ssl')
                        and postgresql_conf_settings.get('ssl') == "on"):
                    source_host = 'hostssl'
                for line in old_conf.readlines():
                    look = re.match(r'^local.*peer$', line.strip())
                    if look:
                        new_conf.write(line.strip() + ' map=mymap\n')
                    else:
                        look = re.match(r'^(host|hostssl|hostnossl)\s+'\
'(?P<db>\S+)\s+(?P<pg_user>\S+)\s+(?P<cidr>\S+)\s+(?P<method>\S+)',
                            line.strip())
                        if look:
                            found = None
                            remains = []
                            for conn in connections:
                                if (conn[0] == look.group('db')
                                        and conn[1] == look.group('pg_user')):
                                    found = conn
                                else:
                                    remains += [conn]
                            connections = remains
                            if found:
                                new_conf.write(
                                    '%(host)s    %(db)s%(pg_user)s%(cidr)smd5\n'
                                    % {
                                        'host': source_host.ljust(10),
                                        'db': found[0].ljust(16),
                                        'pg_user': found[1].ljust(16),
                                        'cidr': found[2].ljust(24)
                                    })
                            else:
                                new_conf.write(line)
                        else:
                            new_conf.write(line)
                if connections:
                    new_conf.write("# Remote connections\n")
                    for conn in connections:
                        new_conf.write(
                            '%(host)s    %(db)s%(pg_user)s%(cidr)smd5\n' % {
                                'host': source_host.ljust(10),
                                'db': conn[0].ljust(16),
                                'pg_user': conn[1].ljust(16),
                                'cidr': conn[2].ljust(24)
                            })

        self.create_cron_conf(context)
        #XXX optimizations?
        #https://people.planetpostgresql.org/devrim/index.php?/archives/83-Using-huge-pages-on-RHEL-7-and-PostgreSQL-9.4.html

        postinst.shellCommand([
            '[ -d %(pgdata)s/base ] ||' % {
                'pgdata': self.pgdata
            }, self.postgresql_setup, 'initdb'
        ])

        return complete
예제 #11
0
파일: sldap.py 프로젝트: optionalg/drop
    def run(self, context):
        complete = super(openldap_serversSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete
        ldapHost = context.value('ldapHost')
        company_domain = context.value('companyDomain')
        password_hash = context.value('ldapPasswordHash')
        priv_key = os.path.join(context.value('etcDir'),
            'pki', 'tls', 'private', '%s.key' % ldapHost)
        config_path = os.path.join(context.value('etcDir'),
            'openldap', 'slapd.d', 'cn=config.ldif')
        _, new_config_path = stageFile(config_path, context)
        modify_config(config_path,
            sep=': ', context=context,
            settings={
                'olcTLSCACertificatePath': os.path.join(
                    context.value('etcDir'), 'pki', 'tls', 'certs'),
                'olcTLSCertificateFile': os.path.join(context.value('etcDir'),
                    'pki', 'tls', 'certs', '%s.crt' % ldapHost),
                'olcTLSCertificateKeyFile': priv_key
            })
        self._update_crc32(new_config_path)

        domain_parts = tuple(company_domain.split('.'))
        db_config_path = os.path.join(context.value('etcDir'),
            'openldap', 'slapd.d', 'cn=config', 'olcDatabase={0}config.ldif')
        _, new_config_path = stageFile(db_config_path, context)
        modify_config(db_config_path,
            sep=': ', enter_block_sep=None, exit_block_sep=None,
            one_per_line=True, context=context, settings={
               'olcRootPW': '%s' % password_hash
            })
        self._update_crc32(new_config_path)
        # XXX using hdb on Fedora27 with an encrypted EBS will lead
        #     to a `BDB0126 mmap: Invalid argument` error. just delete the file!
        for db_path in ['olcDatabase={2}hdb.ldif', 'olcDatabase={2}mdb.ldif']:
            db_path = os.path.join(context.value('etcDir'),
                'openldap', 'slapd.d', 'cn=config', db_path)
            _, new_config_path = stageFile(db_path, context)
            modify_config(db_path,
                sep=': ', enter_block_sep=None, exit_block_sep=None,
                one_per_line=True, context=context, settings={
                    'olcSuffix': 'dc=%s,dc=%s' % domain_parts,
                    'olcRootDN': 'cn=Manager,dc=%s,dc=%s' % domain_parts,
                    'olcRootPW': '%s' % password_hash,
                    'olcAccess': [
                        '{0}to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth manage by * break',
                        '{0}to attrs=userPassword by self write by dn.base="cn=Manager,dc=%s,dc=%s" write by anonymous auth by * none' % domain_parts,
                        '{1}to * by dn.base="cn=Manager,dc=%s,dc=%s" write by self write by * read"' % domain_parts]
                })
            self._update_crc32(new_config_path)

        schema_path = os.path.join(context.value('etcDir'),
            'openldap', 'schema', 'openssh-ldap.ldif')
        _, new_schema_path = stageFile(schema_path, context)
        with open(new_schema_path, 'w') as schema_file:
            schema_file.write("""dn: cn=openssh-openldap,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: openssh-openldap
olcAttributeTypes: {0}( 1.3.6.1.4.1.24552.500.1.1.1.13 NAME 'sshPublicKey' DES
 C 'MANDATORY: OpenSSH Public key' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.
 1.1466.115.121.1.40 )
olcObjectClasses: {0}( 1.3.6.1.4.1.24552.500.1.1.2.0 NAME 'ldapPublicKey' DESC
  'MANDATORY: OpenSSH LPK objectclass' SUP top AUXILIARY MUST ( sshPublicKey $
  uid ) )
""")

        self.create_cron_conf(context)
        self.create_syslogng_conf(context)

        postinst.create_certificate(ldapHost)
        postinst.shellCommand(['chmod', '750', os.path.dirname(priv_key)])
        postinst.shellCommand(['chgrp', 'ldap', os.path.dirname(priv_key)])
        postinst.shellCommand(['chmod', '640', priv_key])
        postinst.shellCommand(['chgrp', 'ldap', priv_key])
        postinst.shellCommand(['chmod', '750', os.path.dirname(priv_key)])
        postinst.shellCommand(['chown', 'ldap:ldap',
            config_path, db_config_path, db_hdb_path])
        postinst.shellCommand(['chmod', '600',
            config_path, db_config_path, db_hdb_path])

        # We need to start the server before adding the schemas.
        postinst.shellCommand(['service', 'slapd', 'restart'])
        postinst.shellCommand(['systemctl', 'enable', 'slapd.service'])
        postinst.shellCommand(['ldapadd', '-Y', 'EXTERNAL', '-H', 'ldapi:///',
            '-f', '/etc/openldap/schema/cosine.ldif', '-D', '"cn=config"'])
        postinst.shellCommand(['ldapadd', '-Y', 'EXTERNAL', '-H', 'ldapi:///',
            '-f', '/etc/openldap/schema/nis.ldif', '-D', '"cn=config"'])
        postinst.shellCommand(['ldapadd', '-Y', 'EXTERNAL', '-H', 'ldapi:///',
          '-f', '/etc/openldap/schema/inetorgperson.ldif', '-D', '"cn=config"'])
        postinst.shellCommand(['ldapadd', '-Y', 'EXTERNAL', '-H', 'ldapi:///',
          '-f', '/etc/openldap/schema/openssh-ldap.ldif', '-D', '"cn=config"'])

        return complete
예제 #12
0
파일: postgres.py 프로젝트: djaodjin/drop
    def run(self, context):
        complete = super(postgresql_serverSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        pg_user = context.value('dbUser')
        vpc_cidr = context.value('vpc_cidr')
        postgresql_conf = '/var/lib/pgsql/data/postgresql.conf'
        pg_ident_conf = '/var/lib/pgsql/data/pg_ident.conf'
        pg_ident_conf = '/var/lib/pgsql/data/pg_ident.conf'
        pg_hba_conf = '/var/lib/pgsql/data/pg_hba.conf'

        listen_addresses = "'localhost'"
        for key, val in self.managed['postgresql-server']['files'].iteritems():
            if key == 'listen_addresses':
                listen_addresses = "'%s'" % val

        modify_config(postgresql_conf,
            settings={'listen_addresses': listen_addresses},
            sep=' = ', context=context)

        # pg_ident
        system_to_pg_mapping = {
            'postgres': 'postgres',
            '/^(.*)$': pg_user
        }
        old_conf_path, new_conf_path = stageFile(pg_ident_conf, context)
        with open(new_conf_path, 'w') as new_conf:
            with open(old_conf_path) as old_conf:
                for line in old_conf.readlines():
                    look = re.match(r'^mymap\s+(\S+)\s+(\S+)', line.strip())
                    if look:
                        system_user = look.group(1)
                        if system_user in system_to_pg_mapping:
                            new_conf.write(
                                '%(map)s%(system_user)s%(pg_user)s\n' % {
                                    'map': 'mymap'.ljust(16),
                                    'system_user': system_user.ljust(24),
                        'pg_user': system_to_pg_mapping[system_user].ljust(16)})
                    else:
                        new_conf.write(line)

        # pg_hba
        connections = [['postgres', 'postgres', vpc_cidr],
                       ['all', pg_user, vpc_cidr]]
        old_conf_path, new_conf_path = stageFile(pg_hba_conf, context)
        with open(new_conf_path, 'w') as new_conf:
            with open(old_conf_path) as old_conf:
                for line in old_conf.readlines():
                    look = re.match(r'^local.*peer$', line.strip())
                    if look:
                        new_conf.write(line.strip() + ' map=mymap\n')
                    else:
                        look = re.match(
r'^host\s+(?P<db>\S+)\s+(?P<pg_user>\S+)\s+(?P<cidr>\S+)\s+(?P<method>\S+)',
                            line.strip())
                        if look:
                            found = None
                            remains = []
                            for conn in connections:
                                if (conn[0] == look.group('db')
                                    and conn[1] == look.group('pg_user')):
                                    found = conn
                                else:
                                    remains += [conn]
                            connections = remains
                            if found:
                                new_conf.write(
                                'host    %(db)s%(pg_user)s%(cidr)smd5\n' % {
                                    'db': found[0].ljust(16),
                                    'pg_user': found[1].ljust(16),
                                    'cidr': found[2].ljust(16)})
                            else:
                                new_conf.write(line)
                        else:
                            new_conf.write(line)
                if len(connections) > 0:
                    new_conf.write("# Remote connections\n")
                    for conn in connections:
                        new_conf.write(
                        'host    %(db)s%(pg_user)s%(cidr)smd5\n' % {
                            'db': conn[0].ljust(16),
                            'pg_user': conn[1].ljust(16),
                            'cidr': conn[2].ljust(16)})

        self.create_cron_conf(context)
        postinst.shellCommand(['[ -d /var/lib/pgsql/data/base ] ||',
            '/usr/bin/postgresql-setup', 'initdb'])

        return complete
예제 #13
0
파일: sldap.py 프로젝트: smirolo/drop
    def run(self, context):
        complete = super(openldap_serversSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete
        domain = 'dbs.internal'
        company_domain = context.value('domainName')
        password_hash = context.value('ldapPasswordHash')
        priv_key = os.path.join(context.SYSCONFDIR,
            'pki', 'tls', 'private', '%s.key' % domain)
        config_path = os.path.join(context.SYSCONFDIR,
            'openldap', 'slapd.d', 'cn=config.ldif')
        _, new_config_path = stageFile(config_path, context)
        modify_config(config_path,
            sep=': ', context=context,
            settings={
                'olcTLSCACertificatePath': os.path.join(
                    context.SYSCONFDIR, 'pki', 'tls', 'certs'),
                'olcTLSCertificateFile': os.path.join(context.SYSCONFDIR,
                    'pki', 'tls', 'certs', '%s.crt' % domain),
                'olcTLSCertificateKeyFile': priv_key
            })
        self._update_crc32(new_config_path)

        domain_parts = tuple(company_domain.split('.'))
        config_path = os.path.join(context.SYSCONFDIR,
            'openldap', 'slapd.d', 'cn=config', 'olcDatabase={0}config.ldif')
        _, new_config_path = stageFile(config_path, context)
        modify_config(config_path,
            sep=': ', enter_block_sep=None, exit_block_sep=None,
            one_per_line=True, context=context, settings={
               'olcRootPW': '{SSHA}%s' % password_hash
            })
        self._update_crc32(new_config_path)
        config_path = os.path.join(context.SYSCONFDIR,
            'openldap', 'slapd.d', 'cn=config', 'olcDatabase={2}mdb.ldif')
        _, new_config_path = stageFile(config_path, context)
        modify_config(config_path,
            sep=': ', enter_block_sep=None, exit_block_sep=None,
            one_per_line=True, context=context, settings={
               'olcSuffix': 'dc=%s,dc=%s' % domain_parts,
               'olcRootDN': 'cn=Manager,dc=%s,dc=%s' % domain_parts,
               'olcRootPW': '{SSHA}%s' % password_hash,
               'olcAccess': [
                   '{0}to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth manage by * break',
                   '{0}to attrs=userPassword by self write by dn.base="cn=Manager,dc=%s,dc=%s" write by anonymous auth by * none' % domain_parts,
                   '{1}to * by dn.base="cn=Manager,dc=%s,dc=%s" write by self write by * read"' % domain_parts]
            })
        self._update_crc32(new_config_path)

        schema_path = os.path.join(context.SYSCONFDIR,
            'openldap', 'schema', 'openssh-ldap.ldif')
        _, new_schema_path = stageFile(schema_path, context)
        with open(new_schema_path, 'w') as schema_file:
            schema_file.write("""dn: cn=openssh-openldap,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: openssh-openldap
olcAttributeTypes: {0}( 1.3.6.1.4.1.24552.500.1.1.1.13 NAME 'sshPublicKey' DES
 C 'MANDATORY: OpenSSH Public key' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.
 1.1466.115.121.1.40 )
olcObjectClasses: {0}( 1.3.6.1.4.1.24552.500.1.1.2.0 NAME 'ldapPublicKey' DESC
  'MANDATORY: OpenSSH LPK objectclass' SUP top AUXILIARY MUST ( sshPublicKey $
  uid ) )
""")

        postinst.shellCommand(['chmod', '750', os.path.dirname(priv_key)])
        postinst.shellCommand(['chgrp', 'ldap', os.path.dirname(priv_key)])
        postinst.shellCommand(['chmod', '640', priv_key])
        postinst.shellCommand(['chgrp', 'ldap', priv_key])

        self.create_syslogng_conf(context)
        postinst.shellCommand([
            'systemctl', 'enable', 'slapd.service'])

        postinst.shellCommand(['ldapadd', '-x', '-W', '-H', 'ldap:///', '-f',
            '/etc/openldap/schema/cosine.ldif', '-D', '"cn=config"'])
        postinst.shellCommand(['ldapadd', '-x', '-W', '-H', 'ldap:///', '-f',
            '/etc/openldap/schema/nis.ldif', '-D', '"cn=config"'])
        postinst.shellCommand(['ldapadd', '-x', '-W', '-H', 'ldap:///', '-f',
            '/etc/openldap/schema/inetorgperson.ldif', '-D', '"cn=config"'])
        postinst.shellCommand(['ldapadd', '-x', '-W', '-H', 'ldap:///', '-f',
            '/etc/openldap/schema/openssh-ldap.ldif', '-D', '"cn=config"'])

        return complete
예제 #14
0
파일: postgres.py 프로젝트: optionalg/drop
    def run(self, context):
        complete = super(postgresql_serverSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        pg_user = context.value('dbUser')
        vpc_cidr = context.value('vpc_cidr')
        postgresql_conf = '/var/lib/pgsql/data/postgresql.conf'
        pg_ident_conf = '/var/lib/pgsql/data/pg_ident.conf'
        pg_ident_conf = '/var/lib/pgsql/data/pg_ident.conf'
        pg_hba_conf = '/var/lib/pgsql/data/pg_hba.conf'

        if not os.path.exists(postgresql_conf):
            # /var/lib/pgsql/data will be empty unless we run initdb once.
            shell_command(['/usr/bin/postgresql-setup', 'initdb'])

        listen_addresses = "'localhost'"
        for key, val in six.iteritems(
                self.managed['postgresql-server']['files']):
            if key == 'listen_addresses':
                listen_addresses = ', '.join(
                    ["'%s'" % address for address in val])

        modify_config(postgresql_conf,
                      settings={'listen_addresses': listen_addresses},
                      sep=' = ',
                      context=context)

        # pg_ident
        system_to_pg_mapping = {'postgres': 'postgres', '/^(.*)$': pg_user}
        old_conf_path, new_conf_path = stageFile(pg_ident_conf, context)
        with open(new_conf_path, 'w') as new_conf:
            with open(old_conf_path) as old_conf:
                for line in old_conf.readlines():
                    look = re.match(r'^mymap\s+(\S+)\s+(\S+)', line.strip())
                    if look:
                        system_user = look.group(1)
                        if system_user in system_to_pg_mapping:
                            new_conf.write(
                                '%(map)s%(system_user)s%(pg_user)s\n' % {
                                    'map':
                                    'mymap'.ljust(16),
                                    'system_user':
                                    system_user.ljust(24),
                                    'pg_user':
                                    system_to_pg_mapping[system_user].ljust(16)
                                })
                    else:
                        new_conf.write(line)

        # pg_hba
        connections = [['postgres', 'postgres', vpc_cidr],
                       ['all', pg_user, vpc_cidr]]
        old_conf_path, new_conf_path = stageFile(pg_hba_conf, context)
        with open(new_conf_path, 'w') as new_conf:
            with open(old_conf_path) as old_conf:
                for line in old_conf.readlines():
                    look = re.match(r'^local.*peer$', line.strip())
                    if look:
                        new_conf.write(line.strip() + ' map=mymap\n')
                    else:
                        look = re.match(
                            r'^host\s+(?P<db>\S+)\s+(?P<pg_user>\S+)\s+(?P<cidr>\S+)\s+(?P<method>\S+)',
                            line.strip())
                        if look:
                            found = None
                            remains = []
                            for conn in connections:
                                if (conn[0] == look.group('db')
                                        and conn[1] == look.group('pg_user')):
                                    found = conn
                                else:
                                    remains += [conn]
                            connections = remains
                            if found:
                                new_conf.write(
                                    'host    %(db)s%(pg_user)s%(cidr)smd5\n' %
                                    {
                                        'db': found[0].ljust(16),
                                        'pg_user': found[1].ljust(16),
                                        'cidr': found[2].ljust(16)
                                    })
                            else:
                                new_conf.write(line)
                        else:
                            new_conf.write(line)
                if connections:
                    new_conf.write("# Remote connections\n")
                    for conn in connections:
                        new_conf.write(
                            'host    %(db)s%(pg_user)s%(cidr)smd5\n' % {
                                'db': conn[0].ljust(16),
                                'pg_user': conn[1].ljust(16),
                                'cidr': conn[2].ljust(16)
                            })

        self.create_cron_conf(context)
        postinst.shellCommand([
            '[ -d /var/lib/pgsql/data/base ] ||', '/usr/bin/postgresql-setup',
            'initdb'
        ])

        return complete
예제 #15
0
    def run(self, context):
        complete = super(jenkinsSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        # Workarounds to get jetty started (webdefault.xml and command line
        # arguments)
        org_webdefault_conf, new_webdefault_conf = setup.stageFile(
            self.webdefault_conf_path, context=context)
        with open(new_webdefault_conf, 'w') as webdefault_conf_file:
            webdefault_conf_file.write(self.webdefault_config_template)
        setup.modify_config(
            os.path.join(self.jetty_home, 'modules/jsp.mod'),
            settings={'-Dorg.apache.jasper.compiler.disablejsr199': 'true'},
            sep='=',
            context=context)

        # Configure jetty/jenkins (environment variables and security context)
        jenkins_default_path = os.path.join(context.value('etcDir'), 'default',
                                            'jenkins')
        setup.modify_config(jenkins_default_path,
                            settings={
                                'JENKINS_HOME': self.jenkins_home,
                                'HUDSON_HOME': self.jenkins_home
                            },
                            sep='=',
                            context=context)
        setup.modifyIniConfig('/usr/lib/systemd/system/jetty.service',
                              settings={
                                  'Service': {
                                      'EnvironmentFile':
                                      '-%s' % jenkins_default_path
                                  }
                              },
                              context=context)
        org_context_conf, new_context_conf = setup.stageFile(os.path.join(
            self.jetty_home, 'webapps', 'jenkins.xml'),
                                                             context=context)
        with open(new_context_conf, 'w') as context_conf_file:
            context_conf_file.write(self.context_config_template %
                                    {'webapp': 'jenkins'})
        setup.stageDir('/var/jenkins/jobs', context)

        jenkins_jobs_dir = os.path.join(self.jenkins_home, 'jobs')
        setup.postinst.shellCommand([
            '[', '-d', jenkins_jobs_dir, ']', '&&', 'mv', jenkins_jobs_dir,
            os.path.join(self.jenkins_home, 'jobs.prev')
        ])
        setup.postinst.shellCommand(
            ['cd', self.jenkins_home, '&&', 'ln', '-s', '/var/jenkins/jobs'])

        # Configure SELinux to allow jetty/jenkins jobs.
        jenkins_te = os.path.join(
            os.path.dirname(setup.postinst.postinst_run_path), 'jenkins.te')
        with open(jenkins_te, 'w') as jenkins_te_file:
            jenkins_te_file.write(self.jenkins_te_config_template)
        setup.postinst.install_selinux_module(
            jenkins_te,
            comment="Configure SELinux to allow jetty/jenkins jobs.")
        setup.postinst.shellCommand(['setsebool', '-P', 'httpd_execmem', '1'])
        setup.postinst.shellCommand(
            ['setsebool', '-P', 'httpd_builtin_scripting', '1'])

        return complete
예제 #16
0
파일: jenkins.py 프로젝트: djaodjin/drop
    def run(self, context):
        complete = super(jenkinsSetup, self).run(context)
        if not complete:
            # As long as the default setup cannot find all prerequisite
            # executable, libraries, etc. we cannot update configuration
            # files here.
            return complete

        # Workarounds to get jetty started (webdefault.xml and command line
        # arguments)
        org_webdefault_conf, new_webdefault_conf = setup.stageFile(
            self.webdefault_conf_path, context=context)
        with open(new_webdefault_conf, 'w') as webdefault_conf_file:
            webdefault_conf_file.write(self.webdefault_config_template)
        setup.modify_config(os.path.join(self.jetty_home, 'modules/jsp.mod'),
            settings={
                '-Dorg.apache.jasper.compiler.disablejsr199': 'true'
            }, sep='=', context=context)


        # Configure jetty/jenkins (environment variables and security context)
        jenkins_default_path = os.path.join(
            context.value('etcDir'), 'default', 'jenkins')
        setup.modify_config(jenkins_default_path,
            settings={
                'JENKINS_HOME': self.jenkins_home,
                'HUDSON_HOME': self.jenkins_home
            }, sep='=', context=context)
        setup.modifyIniConfig('/usr/lib/systemd/system/jetty.service',
            settings={'Service':
                {'EnvironmentFile': '-%s' % jenkins_default_path}},
            context=context)
        org_context_conf, new_context_conf = setup.stageFile(
            os.path.join(self.jetty_home, 'webapps', 'jenkins.xml'),
            context=context)
        with open(new_context_conf, 'w') as context_conf_file:
            context_conf_file.write(
                self.context_config_template % {'webapp': 'jenkins'})
        setup.stageDir('/var/jenkins/jobs', context)

        jenkins_jobs_dir = os.path.join(self.jenkins_home, 'jobs')
        setup.postinst.shellCommand([
            '[', '-d', jenkins_jobs_dir, ']',
            '&&', 'mv', jenkins_jobs_dir,
            os.path.join(self.jenkins_home, 'jobs.prev')])
        setup.postinst.shellCommand([
            'cd', self.jenkins_home,
            '&&', 'ln', '-s', '/var/jenkins/jobs'])

        # Configure SELinux to allow jetty/jenkins jobs.
        jenkins_te = os.path.join(
            os.path.dirname(setup.postinst.postinst_run_path), 'jenkins.te')
        with open(jenkins_te, 'w') as jenkins_te_file:
            jenkins_te_file.write(self.jenkins_te_config_template)
        setup.postinst.install_selinux_module(jenkins_te,
            comment="Configure SELinux to allow jetty/jenkins jobs.")
        setup.postinst.shellCommand(
            ['setsebool', '-P', 'httpd_execmem', '1'])
        setup.postinst.shellCommand(
            ['setsebool', '-P', 'httpd_builtin_scripting', '1'])

        return complete