Example #1
0
def audit_bind(args):
    '''
    Audit bind installation.

    Check if bind installation is properly done.

    '''
    error = False
    # The named-checkconf program checks the syntax of a named.conf file.
    result = x("named-checkconf -t /var/named/chroot /etc/named.conf")
    if result:
        app.print_verbose("ERROR: Invalid data in config file\n{0}".format(result))
        error = True

    #
    search = 'server is up and running'
    result = x('/etc/init.d/named status |grep "{0}"'.format(search))
    if result.strip() != search:
        app.print_verbose("ERROR: Server is down")
        error = True

    if error:
        app.print_verbose("Fail - named didn't pass audit.")
    else:
        app.print_verbose("Ok - named did pass audit.")
    def create_kvm_host(self):
        devicename = disk.create_lvm_volumegroup(
            self.hostname,
            int(self.property_list['\$total_disk_gb']) + 1,
            config.host(self.hostname).get_vol_group())

        cmd = " virt-install"
        cmd += " -d --connect qemu:///system"
        cmd += " --name " + self.hostname
        cmd += " --ram " + self.ram
        cmd += " --vcpus=" + self.cpu
        if self.cpu_max is not None and self.cpu_max != "": cmd += ",maxvcpus=" + self.cpu_max
        cmd += " --vnc --noautoconsole"
        cmd += " --hvm"
        cmd += " --virt-type=kvm"
        cmd += " --autostart"
        cmd += " --disk path=" + devicename
        cmd += " --os-variant=rhel6"
        cmd += " --arch x86_64"
        if config.general.is_back_enabled(): cmd += " --network bridge:br0"
        cmd += " --network bridge:br1"
        cmd += " --location nfs:" + self.kvm_host_ip + ":/dvd"
        cmd += ' -x "ks=nfs:' + self.kvm_host_ip + ':/kickstart/' + self.hostname + '.ks'
        cmd += ' ksdevice=eth1'
        cmd += ' ip=' + config.host(self.hostname).get_front_ip()
        cmd += ' netmask=' + config.general.get_front_netmask()
        cmd += ' dns=' + config.general.get_front_resolver_ip()
        cmd += ' gateway=' + self.kvm_host_ip
        cmd += ' "'

        x(cmd)
        self.wait_for_installation_to_complete()
        self.autostart_guests()
Example #3
0
def _setup_keys():
    '''
    Download client keys from server.

    Needed for client to be allowed to communicate with server.

    '''
    ossecserver = config.general.get_ossec_server_ip()
    hostname = socket.gethostname()
    fqdn = '{0}.{1}'.format(hostname, config.general.get_resolv_domain())

    # Wait until ssh is responsive on server. However this doesn't mean that
    # the server is fully installed.
    general.wait_for_server_to_start(ossecserver, 22)

    # Loop until ossec server has created client keys and made it possible
    # to copy them.
    while True:
        scp_from(
            ossecserver,
            "/var/ossec/etc/{0}_client.keys".format(fqdn),
            "/var/ossec/etc/client.keys"
        )

        # Loop until the keys are downloaded.
        if os.path.exists('/var/ossec/etc/client.keys'):
            break

        # Wait awhile and then try to download the files again.
        time.sleep(40)

    x('chown root:ossec /var/ossec/etc/client.keys')
    x('chmod 640 /var/ossec/etc/client.keys')
Example #4
0
def yum_update():
  '''
  yum update is the first thing that is done when hardening the server,
  to minimize the risk that an updated package revert any hardening mods.
  '''
  app.print_verbose("Update with yum")
  x("yum update -y")
Example #5
0
def install_bind_client(args):
    """
    Setup current server to use syco dns server as recursive name server.

    """
    app.print_verbose("Install bind client.")
    version_obj = version.Version("InstallBindClient", SCRIPT_VERSION)
    version_obj.check_executed()

    # Iptables is already configured with iptables._setup_dns_resolver_rules

    general.wait_for_server_to_start(config.general.get_nameserver_server_ip(), "53")

    # Set what resolver to use (this will be rewritten by networkmanager at
    # reboot)
    resolv = scOpen("/etc/resolv.conf")
    resolv.remove("nameserver.*")
    for ip in config.general.get_nameserver_server_ips():
        resolv.add("nameserver {0} ".format(ip))

    # Change config files for networkmanager.
    x("""
        grep -irl dns ifcfg*|xargs \
        sed -i 's/.*\(dns.*\)[=].*/\\1={0}/ig'""".format(
            config.general.get_nameserver_server_ip()
        ), cwd = "/etc/sysconfig/network-scripts"
    )

    version_obj.mark_executed()
Example #6
0
def _install_server_plugins_dependencies():
    '''
    Install libraries/binaries that the server plugins depend on.

    '''
    # Dependency for check_switch_mac_table
    x("yum install -y net-snmp-utils")
Example #7
0
def httpd_rotate():
    if not os.path.exists('/etc/init.d/httpd'):
        return

    app.print_verbose("Adding httpd logrotate")
    x("mkdir -p /var/log/httpd/archive")
    x("cp %svar/logrotate/httpd /etc/logrotate.d/" % app.SYCO_PATH)
Example #8
0
def uninstall_docker(args):
    """Uninstall docker"""
    x("service docker stop")
    x("yum -y remove docker-engine")
    x("rm -f /etc/yum.repos.d/docker.repo")
    x("rm -f /etc/sysconfig/docker")
    x("rm -rf /var/lib/docker")
Example #9
0
def _install_http_index():
    '''
    Moves a static http index file to the apache root directory. TODO: HttpdUtils function.

    '''
    x("cp /opt/syco/var/icinga/index.html /var/www/html/index.html")
    x("chown apache:apache /var/www/html/index.html")
Example #10
0
    def remove(self, search, output = None):
        '''
        Remove a value from a file using sed.

        '''
        search = self.esc(search)
        x("sed -i '/%s/d' %s" % (search, self.filename), output = output if output is not None else self.output)
Example #11
0
    def remove_eof(self, lines, output = None):
        '''
        Remove the last N lines of the file using head.

        '''
        x("head -n-%s %s > /tmp/syco-remove-eof" % (lines, self.filename), output = output if output is not None else self.output)
        x("cp /tmp/syco-remove-eof " + self.filename, output = output if output is not None else self.output)
Example #12
0
def ldapadd(user, value, uri="-H ldap:///"):
    '''
    Add ldif to openldap over ldap with shell command ldapadd.

    user
        The user used to bind with openldap.
        Only user 'admin' and 'manager' are allowed.

    value
        The ldif value that should be added to openldap.

    '''
    if user == 'admin':
        user = '******'
    elif user == 'manager':
        user = '******' + config.general.get_ldap_dn()
    else:
        raise Exception("Only admin and manager users are supported by ldapXadd")

    if isinstance(value, ListType):
        tmpvalue = ""
        for val in value:
            tmpvalue += val
        value = tmpvalue

    x("ldapadd %s -x -D '%s' -w '%s' << EOF\n%s\nEOF\n\n" % (
        uri,
        user,
        app.get_ldap_admin_password(),
        value
    ))
Example #13
0
def save():
  '''
  Save all current iptable rules to file, so it will be reloaded after reboot.

  '''
  app.print_verbose("Save current iptables rules to /etc/sysconfig/iptables.")
  x("/sbin/iptables-save > /etc/sysconfig/iptables")
Example #14
0
def enable_selinux():
    '''
    Enable SELinux for higher security.

    '''
    x("setenforce 1")
    x("setsebool -P domain_kernel_load_modules 1")
Example #15
0
def enable_ssl():
    '''
    Configure slapd to only be accessible over ssl,
    with client certificate.

    Learn more:
        http://www.openldap.org/pub/ksoper/OpenLDAP_TLS.html#4.0
        http://www.openldap.org/faq/data/cache/185.html

    '''
    ldapadd("admin", """
dn: cn=config
changetype:modify
replace: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: /etc/openldap/cacerts/slapd.key
-
replace: olcTLSCertificateFile
olcTLSCertificateFile: /etc/openldap/cacerts/slapd.crt
-
replace: olcTLSCACertificateFile
olcTLSCACertificateFile: /etc/openldap/cacerts/ca.crt
-
replace: olcTLSCipherSuite
olcTLSCipherSuite: HIGH:MEDIUM:-SSLv2
-
replace: olcTLSVerifyClient
olcTLSVerifyClient: allow""")

    # Enable LDAPS and dispable LDAP
    scOpen('/etc/sysconfig/ldap').replace('[#]*SLAPD_LDAPS=.*', 'SLAPD_LDAPS=yes')
    scOpen('/etc/sysconfig/ldap').replace('[#]*SLAPD_LDAP=.*', 'SLAPD_LDAP=no')
    x("service slapd restart")

    configure_client_cert_for_ldaptools()
Example #16
0
def setup_repo_folder():
  '''
  Create folders where all git repos are stored.

  '''
  x("mkdir /var/lib/git")
  x("ln -s /var/lib/git /git")
Example #17
0
def configured_sssd():
    # If the authentication provider is offline, specifies for how long to allow
    # cached log-ins (in days). This value is measured from the last successful
    # online log-in. If not specified, defaults to 0 (no limit).
    scOpen("/etc/sssd/sssd.conf").remove("^offline_credentials_expiration.*")
    x("sed -i '/\[pam\]/a offline_credentials_expiration=5' /etc/sssd/sssd.conf")

    # Enumeration means that the entire set of available users and groups on the
    # remote source is cached on the local machine. When enumeration is disabled,
    # users and groups are only cached as they are requested.
    scOpen("/etc/sssd/sssd.conf").remove("^enumerate=true")
    scOpen("/etc/sssd/sssd.conf").replace("\[domain/default\]","\[domain/default\]\nenumerate=true")

    # Configure client certificate auth.
    scOpen("/etc/sssd/sssd.conf").remove("^ldap_tls_cert.*")
    scOpen("/etc/sssd/sssd.conf").remove("^ldap_tls_key.*")
    scOpen("/etc/sssd/sssd.conf").remove("^ldap_tls_reqcert.*")
    scOpen("/etc/sssd/sssd.conf").replace("\[domain/default\]",
        "\[domain/default\]\n" +
        "ldap_tls_cert = /etc/openldap/cacerts/client.pem\n" +
        "ldap_tls_key = /etc/openldap/cacerts/client.pem\n" +
        "ldap_tls_reqcert = demand"
    )

    # Only users with this employeeType are allowed to login to this computer.
    scOpen("/etc/sssd/sssd.conf").remove("^access_provider.*")
    scOpen("/etc/sssd/sssd.conf").remove("^ldap_access_filter.*")
    scOpen("/etc/sssd/sssd.conf").replace("\[domain/default\]",
        "\[domain/default\]\n" +
        "access_provider = ldap\n" +
        "ldap_access_filter = (employeeType=Sysop)"
    )

    # Login to ldap with a specified user.
    scOpen("/etc/sssd/sssd.conf").remove("^ldap_default_bind_dn.*")
    scOpen("/etc/sssd/sssd.conf").remove("^ldap_default_authtok_type.*")
    scOpen("/etc/sssd/sssd.conf").remove("^ldap_default_authtok.*")
    scOpen("/etc/sssd/sssd.conf").replace("\[domain/default\]",
        "\[domain/default\]\n" +
        "ldap_default_bind_dn = cn=sssd," + config.general.get_ldap_dn()
    )
    scOpen("/etc/sssd/sssd.conf").replace("\[domain/default\]",
        "\[domain/default\]\n" +
        "ldap_default_authtok_type = password"
    )
    scOpen("/etc/sssd/sssd.conf").replace("\[domain/default\]",
        "\[domain/default\]\n" +
        "ldap_default_authtok = " + app.get_ldap_sssd_password()
    )

    # Need to change the modified date before restarting, to tell sssd to reload
    # the config file.
    x("touch /etc/sssd/sssd.conf")

    # Restart sssd and read in all new configs.
    x("rm /var/lib/sss/db/config.ldb")
    x("service sssd restart")

    # Start sssd after reboot.
    x("chkconfig sssd on")
Example #18
0
def setup_clam_and_freshclam():
    #
    # Setup clamav and freshclam
    #
    app.print_verbose("Setup clamav and freshclam")

    app.print_verbose("  Setup config files.")
    x("cp /usr/local/etc/clamd.conf.sample /usr/local/etc/clamd.conf")
    clamd = scOpen("/usr/local/etc/clamd.conf")
    clamd.replace("^[#]\?Example.*",            "#Example")
    clamd.replace("^[#]\?LogFileMaxSize.*",     "LogFileMaxSize 100M")
    clamd.replace("^[#]\?LogFile.*",            "LogFile /var/log/clamav/clamd.log")
    clamd.replace("^[#]\?LogTime.*",            "LogTime yes")
    clamd.replace("^[#]\?LogSyslog.*",          "LogSyslog yes")
    clamd.replace("^[#]\?TCPSocket.*",          "TCPSocket 3310")
    clamd.replace("^[#]\?TCPAddr.*",            "TCPAddr 127.0.0.1")
    clamd.replace("^[#]\?ExcludePath.*/proc.*", "ExcludePath ^/proc")
    clamd.replace("^[#]\?ExcludePath.*/sys.*",  "ExcludePath ^/sys")
    clamd.replace("^[#]\?User.*",               "User clamav")
    clamd.replace("^[#]\?LocalSocket.*",        "LocalSocket /var/run/clamav/clamd.socket")
    clamd.replace("^[#]\?PidFile.*",            "PidFile /var/run/clamav/clamd.pid")
    clamd.replace("^[#]\?DatabaseDirectory.*",  "DatabaseDirectory /var/lib/clamav")

    x("cp /usr/local/etc/freshclam.conf.sample /usr/local/etc/freshclam.conf")
    freshclam = scOpen("/usr/local/etc/freshclam.conf")
    freshclam.replace("^[#]\?Example.*",        "#Example")
    freshclam.replace("^[#]\?LogFileMaxSize.*", "LogFileMaxSize 100M")
    freshclam.replace("^[#]\?LogTime.*",        "LogTime yes")
    freshclam.replace("^[#]\?LogSyslog.*",      "LogSyslog yes")
    freshclam.replace("^[#]\?DatabaseOwner.*",  "DatabaseOwner clamav")
    freshclam.replace("^[#]\?PidFile.*",        "PidFile /var/run/clamav/freshclam.pid")
    freshclam.replace("^[#]\?DatabaseMirror.*", "DatabaseMirror db.se.clamav.net")
    freshclam.replace("^[#]\?UpdateLogFile.*",  "UpdateLogFile /var/log/clamav/freshclam.log")
    freshclam.replace("^[#]\?DatabaseDirectory.*", "DatabaseDirectory /var/lib/clamav")
Example #19
0
def _install_glassfish():
  '''
  Installation of the glassfish application server.

  '''
  x("yum install zip -y")
  if (not os.access(GLASSFISH_INSTALL_PATH + "/glassfish", os.F_OK)):
    os.chdir(app.INSTALL_DIR)
    if (not os.access(GLASSFISH_INSTALL_FILE, os.F_OK)):
      general.download_file(GLASSFISH_REPO_URL, user="******")

    # Set executeion permissions and run the installation.
    if ".zip" in GLASSFISH_INSTALL_FILE:
      install.package("unzip")
      x("unzip " + GLASSFISH_INSTALL_FILE + " -d /usr/local/")
      x("chown glassfish:glassfish -R "+GLASSFISH_INSTALL_PATH)
    else:
      raise Exception("Only installing zip version of glassfish")

    # Install the start script
    # It's possible to do this from glassfish with "asadmin create-service",
    # but our own script is a little bit better. It creates startup log files
    # and has a better "start user" functionality.
    x(GLASSFISH_INSTALL_PATH+"/bin/asadmin create-service")
    x("su glassfish " + GLASSFISH_INSTALL_PATH + "/bin/asadmin start-domain")
Example #20
0
    def remove(self, search):
        '''
        Remove a value from a file using sed.

        '''
        search = self.esc(search)
        x("sed -i '/%s/d' %s" % (search, self.filename))
Example #21
0
    def remove_eof(self, lines):
        '''
        Remove the last N lines of the file using head.

        '''
        x("head -n-%s %s > /tmp/syco-remove-eof" % (lines, self.filename))
        x("cp /tmp/syco-remove-eof " + self.filename)
Example #22
0
def set_syco_permissions():
    """Set permissions on all syco files"""
    x("chmod 0750 /opt/syco")
    x("chmod 0750 /opt/syco/var")
    x("chmod 0750 /opt/syco/var/mysql")
    x("chmod 0750 /opt/syco/var/mysql/mysql-lvm-backup.py")
    x("chmod 0750 /opt/syco/var/mysql/mysqldump-backup.sh")
Example #23
0
def install_freeradius(args):
    '''
    Install and configure the freeradius on the local host.

    '''
    app.print_verbose("Install FreeRadius version: %d" % SCRIPT_VERSION)
    version_obj = version.Version("InstallFreeRadius", SCRIPT_VERSION)
    version_obj.check_executed()

    # Initialize all passwords used by the script
    app.get_ldap_admin_password()

    _install_packages()

    # Configure iptables
    iptables.add_freeradius_chain()
    iptables.save()

    _configure_ldap()
    _enable_ldap()
    _configure_radius()
    _setup_radius_clients()

    x("/etc/init.d/radiusd restart")

    version_obj.mark_executed()
Example #24
0
File: common.py Project: Nemie/syco
def customize_shell():
    app.print_verbose("Customize shell")

    app.print_verbose("  Add Date And Time To History Output")
    scOpen("/etc/bashrc").replace_add(
        "^export HISTTIMEFORMAT=.*$",
        "export HISTTIMEFORMAT=\"%h/%d - %H:%M:%S \""
    )

    app.print_verbose("  Add Color To Grep")
    root = scOpen("/root/.bash_profile")
    root.replace_add("^export GREP_COLOR=.*$",   "export GREP_COLOR='1;32'")
    root.replace_add("^export GREP_OPTIONS=.*$", "export GREP_OPTIONS=--color=auto")

    skel = scOpen("/etc/skel/.bash_profile")
    skel.replace_add("^export GREP_COLOR=.*$",   "export GREP_COLOR='1;32'")
    skel.replace_add("^export GREP_OPTIONS=.*$", "export GREP_OPTIONS=--color=auto")

    app.print_verbose("  Enable SSH key forwarding to work with sudo su")
    tmp_sudo_file = get_install_dir() + "sudoers"
    x("cp /etc/sudoers " + tmp_sudo_file)
    sudoers = scOpen(tmp_sudo_file)
    sudoers.remove("Defaults    env_keep += \"SSH_AUTH_SOCK\"")
    sudoers.add("Defaults    env_keep += \"SSH_AUTH_SOCK\"")
    xRes = x("visudo -c -f " + tmp_sudo_file)
    if tmp_sudo_file + ": parsed OK" in xRes:
        x("mv " + tmp_sudo_file + " /etc/sudoers")
    else:
        app.print_error("Temporary sudoers file corrupt, not updating")
Example #25
0
def install_haproxy(args):
    app.print_verbose("Install HA Proxy version: %d" % script_version)
    version_obj = version.Version("InstallHaproxy", script_version)
    version_obj.check_executed()

    global CERT_SERVER, CERT_SERVER_PATH, CERT_COPY_TO_PATH, SYCO_PLUGIN_PATH
    CERT_SERVER = config.general.get_cert_server_ip()
    CERT_SERVER_PATH = config.general.get_option('haproxy.remote_cert_path')
    CERT_COPY_TO_PATH = config.general.get_option('haproxy.local_cert_path')
    SYCO_PLUGIN_PATH = app.get_syco_plugin_paths("/var/haproxy/").next()

    # Validate all command line parameters.
    if len(sys.argv) != 4:
        print_killmessage()

    haproxy_env()
    haproxy_state()

    x("yum install -y tcl haproxy")
    iptables.add_haproxy_chain()
    iptables.save()
    _copy_certificate_files()
    _configure_haproxy()

    version_obj.mark_executed()
Example #26
0
def uninstall_docker(args):
    """Uninstall docker"""
    x('service docker stop')
    x('yum -y remove docker-engine')
    x('rm -f /etc/yum.repos.d/docker.repo') 
    x('rm -f /etc/sysconfig/docker')
    x('rm -rf /var/lib/docker')
Example #27
0
def remove_file():
    '''
    Delete dumpfile if existing.

    '''
    if os.path.exists(filename()):
        x("rm " + filename())
Example #28
0
def _libvirt_init_config():

    x("yum install augeas -y")
    #Initialize augeas
    augeas = Augeas(x)

    augeas.set_enhanced("/files/etc/sysconfig/libvirt-guests/ON_SHUTDOWN","shutdown")
Example #29
0
def install_cobbler(args):
  '''
  Install cobbler on current host.

  '''
  app.print_verbose("Install cobbler version: %d" % SCRIPT_VERSION)
  version_obj = version.Version("installCobbler", SCRIPT_VERSION)
  version_obj.check_executed()

  # Initialize password.
  app.get_root_password_hash()

  # Disable SELINUX it just messes with me.
  x("echo 0 > /selinux/enforce")
  general.set_config_property("/etc/selinux/config", '^SELINUX=.*', "SELINUX=permissive")

  _install_cobbler()

  iptables.add_cobbler_chain()
  iptables.save()

  _modify_cobbler_settings()

  _import_repos()
  setup_all_systems(args)

  # Start/Restart used services.
  x("/etc/init.d/dhcpd restart")

  version_obj.mark_executed()
Example #30
0
def install_rsyslogd(args):
    """
    Install rsyslogd on the server.

    """
    app.print_verbose("Install rsyslogd.")
    version_obj = version.Version("InstallRsyslogd", SCRIPT_VERSION)
    version_obj.check_executed()

    # Installing packages
    install_packages("rsyslog rsyslog-gnutls gnutls-utils")

    # Autostart rsyslog at boot
    x("chkconfig rsyslog on")

    # Generation new certs if no certs exsists
    if not os.path.exists('/etc/pki/rsyslog/ca.crt'):
        rsyslog_newcerts(args)

    _setup_rsyslogd()

    # Add iptables chains
    iptables.add_rsyslog_chain("server")
    iptables.save()

    # Restarting service
    x("service rsyslog restart")

    install_compress_logs()

    # Configure logrotate
    installLogrotate.install_logrotate(args)

    version_obj.mark_executed()
Example #31
0
def _create_kvm_snapshot_partition():
    '''
    Create a partion that will be used by kvm/qemu to store guest snapshots.

    Memory snapshots when rebooting and such.

    TODO: Size should be equal to RAM.
    '''
    volgroup = disk.active_volgroup_name()
    devicename = "/dev/" + volgroup + "/qemu"
    result = x("lvdisplay -v " + devicename, output = False)
    if (devicename not in result):
        x("lvcreate -n qemu -L 100G " + volgroup)
        x("mkfs.ext4 -j " + devicename)
        x("mkdir -p /var/lib/libvirt/qemu")
        x("mount " + devicename + " /var/lib/libvirt/qemu")
        x("chown qemu:qemu /var/lib/libvirt/qemu")
        x("restorecon -R -v /var/lib/libvirt/qemu")

        # Automount the new partion when rebooting.
        value = devicename + "        /var/lib/libvirt/qemu     ext4        defaults                1 2"
        general.set_config_property("/etc/fstab", value, value)
Example #32
0
def install_kvmhost(args):
    '''
    The actual installation of the kvm host.

    '''
    app.print_verbose("Install kvm host version: %d" % SCRIPT_VERSION)
    version_obj = version.Version("InstallKvmHost", SCRIPT_VERSION)
    version_obj.check_executed()

    if (not general.grep("/proc/cpuinfo", "vmx|svm")):
        app.print_error("CPU don't support virtualization.")
        _abort_kvm_host_installation()

    if (not general.grep("/proc/cpuinfo", "constant_tsc")):
        app.print_error("CPU don't have a constant Time Stamp Counter.")
        _abort_kvm_host_installation()

    # Install the kvm packages
    install.package("qemu-kvm")
    install.package("libvirt")
    install.package("libguestfs-tools")
    install.package("avahi")

    # Provides the virt-install command for creating virtual machines.
    install.package("python-virtinst")

    # Before libvirtd starts, create a snapshot partion for qemu.
    _create_kvm_snapshot_partition()

    # Start services libvirtd depends on.
    x("service messagebus restart")
    x("service avahi-daemon start")
    x("chkconfig avahi-daemon on")

    # Start virsh
    x("service libvirtd start")

    _enable_ksm()

    # Looks like we need to wait for the libvirtd to start, otherwise
    # the virsh nodeinfo below doesn't work.
    time.sleep(1)

    # Set selinux
    x("setenforce 1")

    # Is virsh started?
    result = x("virsh nodeinfo")
    if "CPU model:" not in result:
        app.print_error("virsh not installed.")
        _abort_kvm_host_installation()

    result = x("virsh -c qemu:///system list")
    if "Id" not in result and "Name" not in result:
        app.print_error("virsh not installed.")
        _abort_kvm_host_installation()

    _setup_network_interfaces()

    iptables.add_kvm_chain()
    iptables.save()

    version_obj.mark_executed()

    # Set selinux
    x("reboot")

    # Wait for the reboot to be executed, so the script
    # doesn't proceed to next command in install.cfg
    time.sleep(1000)
Example #33
0
def _install_cobbler():
    #
    # Install cobbler
    #
    # See http://linux.die.net/man/1/cobbler
    # See https://fedorahosted.org/cobbler/wiki/DownloadInstructions
    # See https://fedorahosted.org/cobbler/wiki/UsingCobblerImport
    # See http://www.ithiriel.com/content/2010/02/22/installing-linux-vms-under-kvm-cobbler-and-koan

    # Cobbler packages are in the EPEL repo.
    install.epel_repo()

    # To get cobbler and kvm work correct.
    x("yum -y install cobbler koan httpd dhcp createrepo mkisofs mod_wsgi " +
      "python-cheetah python-netaddr python-simplejson python-urlgrabber " +
      "PyYAML rsync tftp-server yum-utils pykickstart")

    # Cobbler web only has one other requirement besides cobbler itself
    x("yum -y install Django")

    # Autostart services
    x("/sbin/chkconfig httpd on")
    x("/sbin/chkconfig cobblerd on")
    x("/sbin/chkconfig dhcpd on")

    # This allows the Apache httpd server to connect to the network
    x('/usr/sbin/semanage fcontext -a -t public_content_rw_t "/var/lib/tftpboot/.*"'
      )
    x('/usr/sbin/semanage fcontext -a -t public_content_rw_t "/var/www/cobbler/images/.*"'
      )
    x('/usr/sbin/semanage fcontext -a -t httpd_sys_content_rw_t "/var/lib/cobbler/webui_sessions/.*"'
      )
    x('restorecon -R -v "/var/lib/tftpboot/"')
    x('restorecon -R -v "/var/www/cobbler/images"')
    x('restorecon -R -v "/var/lib/cobbler/webui_sessions/"')

    # Enables cobbler to read/write public_content_rw_t
    x('/usr/sbin/setsebool -P cobbler_anon_write on')

    # Enable httpd to connect to cobblerd (optional, depending on if web interface is installed)
    # Notice: If you enable httpd_can_network_connect_cobbler and you should switch httpd_can_network_connect off
    x('/usr/sbin/setsebool -P httpd_can_network_connect off')
    x('/usr/sbin/setsebool -P httpd_can_network_connect_cobbler on')

    #Enabled cobbler to use rsync etc.. (optional)
    x('/usr/sbin/setsebool -P cobbler_can_network_connect on')

    #Enable cobbler to use CIFS based filesystems (optional)
    #x('/usr/sbin/setsebool -P cobbler_use_cifs on')

    # Enable cobbler to use NFS based filesystems (optional)
    #x('/usr/sbin/setsebool -P cobbler_use_nfs on')

    _install_custom_selinux_policy()

    # Double check your choices
    x('getsebool -a|grep cobbler')

    app.print_verbose("Update xinetd config files")
    general.set_config_property("/etc/xinetd.d/tftp", '[\s]*disable[\s]*[=].*',
                                "        disable                 = no")
    general.set_config_property("/etc/xinetd.d/rsync",
                                '[\s]*disable[\s]*[=].*',
                                "        disable         = no")
    x("/etc/init.d/xinetd restart")
Example #34
0
def uninstall_openldap(args):
    '''
    Uninstall openldap.

    '''
    app.print_verbose("Uninstall openldap script-version: %d" % SCRIPT_VERSION)
    x("service slapd stop")
    x("yum -y remove openldap-servers openldap-clients")

    x("rm -f /etc/openldap/cacerts/*")
    x("rm -rf /etc/openldap/schema")
    x("rm -f /etc/openldap/slapd.conf.bak")
    x("rm -rf /etc/openldap/slapd.d")
    x("rm -rf /var/lib/ldap")

    # Remove client cert configs
    scOpen("/etc/profile").remove(
        "^LDAPTLS_CERT.*\|^LDAPTLS_KEY.*\|export LDAPTLS_CERT LDAPTLS_KEY.*")

    # Remove sudo configs.
    scOpen("/etc/nsswitch.conf").remove("^sudoers.*")
    scOpen("/etc/ldap.conf").remove(
        "^sudoers_base.*\|^binddn.*\|^bindpw.*\|^ssl on.*\|^tls_cert.*\|^tls_key.*\|sudoers_debug.*"
    )

    # Host information
    scOpen("/etc/hosts").remove('^' + config.general.get_ldap_server_ip() +
                                ".*")

    # Remove web files
    x("rm -rf /var/www/ldap")
    x("rm -f /etc/httpd/conf.d/010-ldap.conf")
    x("rm -rf /var/log/slapd")

    iptables.del_ldap_chain()
    iptables.save()

    version_obj = version.Version("InstallOpenLdap", SCRIPT_VERSION)
    version_obj.mark_uninstalled()
Example #35
0
def _install_web_page():
    # Install cgi-bin and html files
    x("cp -R " + app.SYCO_PATH + "var/ldap/html /var/www/ldap")
    x("chmod -R 555 /var/www/ldap")
    x("chcon -R system_u:object_r:httpd_sys_content_t:s0 /var/www/ldap")
    x("chcon -R system_u:object_r:httpd_sys_script_exec_t:s0 /var/www/ldap/cgi-bin"
      )

    scOpen("/var/www/ldap/cgi-bin/ldappassword.cgi").replace(
        "${LDAP_DN}", config.general.get_ldap_dn())

    scOpen("/var/www/ldap/cgi-bin/ldappassword.cgi").replace(
        "${LDAP_HOSTNAME}", config.general.get_ldap_hostname())

    # Config apache
    x("cp " + app.SYCO_PATH + "var/ldap/010-ldap.conf /etc/httpd/conf.d/")
    scOpen("/etc/httpd/conf.d/010-ldap.conf").replace(
        "${LDAP_HOSTNAME}", config.general.get_ldap_hostname())

    x("chcon system_u:object_r:httpd_config_t:s0 /etc/httpd/conf.d/010-ldap.conf"
      )
    x("chown root:root /etc/httpd/conf.d/010-ldap.conf")
    x("chmod 644 /etc/httpd/conf.d/010-ldap.conf")
    x("/etc/init.d/httpd restart")
Example #36
0
def add_read_permission(filename):
    if (os.path.exists(filename)):
        x("chmod 744 " + filename)
Example #37
0
def create_ca_cert():
    x("echo '00' > /etc/openldap/cacerts/ca.srl")
    x("openssl req -new -x509 -sha512 -nodes -days 3650 -newkey rsa:4096" +
      " -out /etc/openldap/cacerts/ca.crt" +
      " -keyout /etc/openldap/cacerts/ca.key" + " -subj " +
      get_cert_subj(config.general.get_organization_name() + "CA"))
Example #38
0
def configure_sudo_in_ldap():
    '''
    Configure sudo in ldap

    Users that should have sudo rights, are configured in the ldap-db. The ldap
    sudo schema are not configured by default, and are here created.

    Learn more:
        http://eatingsecurity.blogspot.com/2008/10/openldap-continued.html
        http://www.sudo.ws/sudo/man/1.8.2/sudoers.ldap.man.html

    '''
    # Update the locate database
    x('updatedb')

    # Copy the sudo Schema into the LDAP schema repository
    filepath = x('locate /usr/share/doc/*/schema.OpenLDAP').strip()
    x("/bin/cp -f %s /etc/openldap/schema/sudo.schema" % filepath)
    x("restorecon /etc/openldap/schema/sudo.schema")

    # Create a conversion file for the schema.
    x("mkdir /tmp/sudoWork")
    x("echo 'include /etc/openldap/schema/sudo.schema' > /tmp/sudoWork/sudoSchema.conf"
      )

    # Convert the "Schema" to "LDIF".
    x("slapcat -f /tmp/sudoWork/sudoSchema.conf -F /tmp/ -n0 -s 'cn={0}sudo,cn=schema,cn=config' > /tmp/sudoWork/sudo.ldif"
      )

    # Remove invalid data.
    scOpen('/tmp/sudoWork/sudo.ldif').replace('{0}sudo', 'sudo')

    # Remove last 8 (invalid) lines.
    scOpen('/tmp/sudoWork/sudo.ldif').remove_eof(8)

    # Load the schema into the LDAP server
    ldapadd("admin", open("/tmp/sudoWork/sudo.ldif").readlines())

    x("rm -rf /tmp/sudoWork")

    # Add index to sudoers db
    ldapadd(
        "admin", """
dn: olcDatabase={2}bdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: sudoUser eq""")
Example #39
0
def _service(service,command):
    x("/sbin/service {0} {1}".format(service, command))
Example #40
0
def _setup_network_interfaces():
    """
    Setup bonded network interfaces and bridges.

    Read more.
    http://serverfault.com/questions/316623/what-is-the-correct-way-to-setup-a-bonded-bridge-on-centos-6-for-kvm-guests
    http://www.linuxfoundation.org/collaborate/workgroups/networking/bridge
    http://www.cyberciti.biz/faq/rhel-linux-kvm-virtualization-bridged-networking-with-libvirt/
    http://www.linux-kvm.org/page/HOWTO_BONDING
    https://fedorahosted.org/cobbler/wiki/VirtNetworkingSetupForUseWithKoan
    http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Virtualization/sect-Virtualization-Network_Configuration-Bridged_networking_with_libvirt.html
    http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s1-networkscripts-interfaces.html
    http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/sec-Using_Channel_Bonding.html

    """
    # Remove the virbr0, "NAT-interface".
    # http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Virtualization/chap-Virtualization-Network_Configuration.html
    x("virsh net-destroy default")
    x("virsh net-undefine default")
    x("service libvirtd restart")

    # Install network bridge
    install.package("bridge-utils")

    general.set_config_property2("/etc/modprobe.d/syco.conf",
                                 "alias bond0 bonding")

    num_of_if = net.num_of_eth_interfaces()

    front_gw = config.general.get_front_gateway_ip()
    front_resolver = config.general.get_front_resolver_ip()
    front_netmask = config.general.get_front_netmask()
    front_ip = config.host(net.get_hostname()).get_front_ip()

    back_gw = config.general.get_back_gateway_ip()
    back_resolver = config.general.get_back_resolver_ip()
    back_netmask = config.general.get_back_netmask()
    back_ip = config.host(net.get_hostname()).get_back_ip()
    if (num_of_if >= 4):
        # Setup back-net
        _setup_bridge("br0", back_ip, back_netmask, back_gw, back_resolver)
        _setup_bond("bond0", "br0")
        _setup_eth("eth0", "bond0")
        _setup_eth("eth1", "bond0")

        # _setup front-net
        _setup_bridge("br1", front_ip, front_netmask, front_gw, front_resolver)
        _setup_bond("bond1", "br1")
        _setup_eth("eth2", "bond1")
        _setup_eth("eth3", "bond1")
    elif (num_of_if == 2):
        # Setup back-net
        _setup_bridge("br0", back_ip, back_netmask, back_gw, back_resolver)
        _setup_bond("bond0", "br0")
        _setup_eth("eth0", "bond0")

        # _setup front-net
        _setup_bridge("br1", front_ip, front_netmask, front_gw, front_resolver)
        _setup_bond("bond1", "br1")
        _setup_eth("eth1", "bond1")
    else:
        app.print_error("To few network interfaces: " + str(num_of_if))
        _abort_kvm_host_installation()
Example #41
0
def install_mysql(args):
    """
    Install and configure the mysql-server on the local host.

    """
    app.print_verbose("Install mysql version: %d" % SCRIPT_VERSION)
    version_obj = version.Version("InstallMysql", SCRIPT_VERSION)
    version_obj.check_executed()

    if len(args) != 3:
        raise Exception(
            "syco install-mysql [server-id] [innodb-buffer-pool-size]")

    server_id = args[1]
    innodb_buffer_pool_size = args[2]

    # Initialize all passwords used by the script
    app.init_mysql_passwords()

    # Install the mysql-server packages.
    if not os.access("/usr/bin/mysqld_safe", os.W_OK | os.X_OK):
        x("yum -y install mysql-server hdparm")

        x("/sbin/chkconfig mysqld on ")
        if not os.access("/usr/bin/mysqld_safe", os.F_OK):
            raise Exception("Couldn't install mysql-server")

    # Configure iptables
    iptables.add_mysql_chain()
    iptables.save()

    # Disable mysql history logging
    if os.access("/root/.mysql_history", os.F_OK):
        x("rm /root/.mysql_history")
    x("ln -s /dev/null /root/.mysql_history")

    # Used to log slow queries, configured in my.cnf with log-slow-queries=
    x("touch /var/log/mysqld-slow.log")
    x("chown mysql:mysql /var/log/mysqld-slow.log")
    x("chmod 0640 /var/log/mysqld-slow.log")
    x("chcon system_u:object_r:mysqld_log_t:s0 /var/log/mysqld-slow.log")

    # Not used at the moment, just preventing mysql to load any modules.
    if not os.access("/usr/share/mysql/plugins", os.W_OK | os.X_OK):
        os.mkdir("/usr/share/mysql/plugins")
        os.chmod("/usr/share/mysql/plugins", 0)
        os.chown("/usr/share/mysql/plugins", 0, 0)

    # Under Linux, it is advisable to disable the write-back cache. Otherwise data
    # can get lost when computer get power-failures. Beware that some drives or
    # disk controllers may be unable to disable the write-back cache.
    #
    app.print_verbose("TODO: Might need to be done from bios?")
    x("hdparm -W0 /dev/mapper/VolGroup00-var")

    app.print_verbose("Install /etc/my.cnf")
    shutil.copy(app.SYCO_PATH + "var/mysql/my.cnf", "/etc/my.cnf")
    x("chown mysql:mysql /etc/my.cnf")
    x("chmod 600 /etc/my.cnf")
    for line in fileinput.FileInput("/etc/my.cnf", inplace=1):
        line = line.replace("${server-id}", server_id)
        line = line.replace("${innodb_buffer_pool_size}",
                            innodb_buffer_pool_size)
        print line,

    # When the innodb files are configured to be large, it takes some time to
    # generate the files.
    app.print_verbose(
        "Increaste timeout for /etc/init.d/mysqld to 120 seconds.")
    for line in fileinput.FileInput("/etc/init.d/mysqld", inplace=1):
        line = line.replace("STARTTIMEOUT=30", "STARTTIMEOUT=120")
        print line,

    x("service mysqld start")

    # Secure the mysql installation.
    mysql_exec("truncate mysql.db")
    mysql_exec("truncate mysql.user")

    current_host_config = config.host(net.get_hostname())

    # Used by monitor services (icingas nrpe plugin etc.)
    mysql_exec("GRANT REPLICATION CLIENT ON *.* " +
               "TO 'monitor'@'127.0.0.1' IDENTIFIED BY '%s'" %
               (app.get_mysql_monitor_password()))

    # Used by backup scripts to flush master and check slave status etc. when
    # doing an lvm backup.
    mysql_exec("GRANT RELOAD,SUPER,REPLICATION CLIENT ON *.* " +
               "TO 'backup'@'127.0.0.1' IDENTIFIED BY '%s'" %
               (app.get_mysql_backup_password()))

    mysql_exec("DROP DATABASE test;")
    mysql_exec("SELECT host,user FROM mysql.db;")
    mysql_exec("SELECT host,user FROM mysql.user;")
    mysql_exec(
        "GRANT ALL PRIVILEGES ON *.* TO "
        "'root'@'127.0.0.1' IDENTIFIED BY '%s', "
        "'root'@'localhost' IDENTIFIED BY '%s', "
        "'root'@'%s' IDENTIFIED BY '%s'"
        " WITH GRANT OPTION" %
        (app.get_mysql_root_password(), app.get_mysql_root_password(),
         current_host_config.get_front_ip(), app.get_mysql_root_password()))

    mysql_exec("flush privileges;", )

    repl_peer = current_host_config.get_option("repl_peer")
    if repl_peer:
        mysql_exec("GRANT ALL PRIVILEGES ON *.* TO "
                   "'root'@'%s' IDENTIFIED BY '%s'"
                   " WITH GRANT OPTION" %
                   (repl_peer, app.get_mysql_root_password()),
                   with_user=True)

    mysql_exec("RESET MASTER;", with_user=True)
    mysql_exec("FLUSH PRIVILEGES;", with_user=True)

    version_obj.mark_executed()
Example #42
0
def _chkconfig(service,command):
    x("/sbin/chkconfig {0} {1}".format(service, command))
Example #43
0
def uninstall_mysql(args):
    """
    Uninstall mysql

    """
    if os.access("/etc/init.d/mysqld", os.F_OK):
        x("/etc/init.d/mysqld stop")
    x("yum -y remove mysql-server")
    x("rm -f /root/.mysql_history")
    x("rm -fr /var/lib/mysql")
    x("rm -f /var/log/mysqld-slow.log")
    x("rm -f /var/log/mysqld.log.rpmsave")
    x("rm -f /var/log/mysqld.log")
    x("rm -f /etc/my.cnf")

    version_obj = version.Version("InstallMysql", SCRIPT_VERSION)
    version_obj.mark_uninstalled()
Example #44
0
def iptables(args, output=True):
    '''
    Execute the iptables shell command.

    '''
    x("/sbin/iptables " + args, output=output)
Example #45
0
def _set_domain_passwords(domain_name, admin_port):
    '''
  Security configuration

  '''
    asadmin_exec("stop-domain " + domain_name)

    # Change master password, default=empty
    asadmin_exec("change-master-password --savemasterpassword=true " +
                 domain_name,
                 admin_port=None,
                 events={
                     "(?i)Enter the current master password.*":
                     "changeit\n",
                     "(?i)Enter the new master password.*":
                     app.get_glassfish_master_password() + "\n",
                     "(?i)Enter the new master password again.*":
                     app.get_glassfish_master_password() + "\n"
                 })

    # Create new cert for https
    os.chdir(GLASSFISH_DOMAINS_PATH + domain_name + "/config/")
    x("keytool -delete -alias s1as -keystore keystore.jks -storepass '" +
      app.get_glassfish_master_password() + "'",
      user="******")
    x('keytool -keysize 2048 -genkey -alias s1as -keyalg RSA -dname "' +
      'CN=' + config.general.get_organization_name() + ',O=' +
      config.general.get_organization_name() + ',L=' +
      config.general.get_locality() + ',S=' + config.general.get_state() +
      ',C=' + config.general.get_country_name() + '" -validity 3650' +
      " -keypass '" + app.get_glassfish_master_password() + "'" +
      ' -keystore keystore.jks' + " -storepass '" +
      app.get_glassfish_master_password() + "'",
      user="******")
    x("keytool -list -keystore keystore.jks -storepass '" +
      app.get_glassfish_master_password() + "'",
      user="******")

    asadmin_exec("start-domain " + domain_name)

    # Change admin password
    asadmin_exec(" change-admin-password",
                 admin_port,
                 events={
                     '(?i)Enter admin user name \[default: admin\]> ':
                     "admin\n",
                     '(?i)Enter admin password> ':
                     "\n",
                     '(?i)Enter new admin password> ':
                     app.get_glassfish_admin_password() + "\n",
                     '(?i)Enter new admin password again> ':
                     app.get_glassfish_admin_password() + "\n"
                 })

    # Stores login info for glassfish user in /home/glassfish/.asadminpass
    asadmin_exec("login",
                 admin_port,
                 events={
                     "Enter admin user name \[default: admin\]> ":
                     "admin\n",
                     "Enter admin password> ":
                     app.get_glassfish_admin_password() + "\n"
                 })
Example #46
0
def install_mysql_client():
    """
    Install mysql command line client.

    """
    x("yum -y install mysql.x86_64")
Example #47
0
def uninstall_glassfish(args):
    '''
  The main function the glassfish uninstallation.

  '''
    app.print_verbose("Uninstall " + GLASSFISH_VERSION +
                      " version: %d" % SCRIPT_VERSION)

    if (os.access(GLASSFISH_INSTALL_PATH, os.F_OK)):
        os.chdir("/tmp")
        x("/etc/init.d/" + GLASSFISH_VERSION + " stop -an")
        x("rm -rf " + GLASSFISH_INSTALL_PATH)
        x("/sbin/chkconfig --del " + GLASSFISH_VERSION)
        x("rm " + "/etc/init.d/" + GLASSFISH_VERSION)

    if (_is_glassfish_user_installed()):
        # Change dir if some of the rm commands fails, so not everythig will
        # be deleted by mistake.
        x("rm -rf /home/glassfish")
        x("userdel glassfish")
        x("groupdel glassfishadm")

    if (os.access("/usr/java/jdk1.6.0_22", os.F_OK)):
        x("rpm -e sun-javadb-core-10.5.3-0.2")
        x("rpm -e sun-javadb-client-10.5.3-0.2")
        x("rpm -e sun-javadb-demo-10.5.3-0.2")
        x("rpm -e sun-javadb-docs-10.5.3-0.2")
        x("rpm -e sun-javadb-javadoc-10.5.3-0.2")
        x("rpm -e sun-javadb-common-10.5.3-0.2")
        x("rpm -e jdk-1.6.0_22-fcs")

    if (os.access("/usr/java/jdk1.6.0_24", os.F_OK)):
        x("rpm -e sun-javadb-core-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-client-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-demo-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-docs-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-javadoc-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-common-10.6.2-1.1.i386")
        x("rpm -e jdk-1.6.0_24-fcs")
        x("rpm -e jdk-6u24-linux-amd64")

    if (os.access("/usr/java/jdk1.6.0_29", os.F_OK)):
        x("rpm -e sun-javadb-javadoc-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-docs-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-demo-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-client-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-core-10.6.2-1.1.i386")
        x("rpm -e sun-javadb-common-10.6.2-1.1.i386")
        x("rpm -e jdk-6u29-linux-amd64")

    iptables.del_glassfish_chain()
    iptables.save()

    version_obj = version.Version("Install" + GLASSFISH_VERSION,
                                  SCRIPT_VERSION)
    version_obj.mark_uninstalled()
Example #48
0
def _set_java_temp_dir(admin_port):
    x("mkdir " + JAVA_TEMP_PATH)
    x("chown glassfish:glassfishadm " + JAVA_TEMP_PATH)
    asadmin_exec(
        "create-jvm-options '-Djava.io.tmpdir=" + JAVA_TEMP_PATH + "'",
        admin_port)
Example #49
0
def clear_login_screen():
    '''Clear information shown on the console login screen.'''
    app.print_verbose("CIS 8.1 Set Warning Banner for Standard Login Services")
    x('cp %s/hardening/issue.net /etc/motd' % app.SYCO_VAR_PATH)
    x('cp %s/hardening/issue.net /etc/issue' % app.SYCO_VAR_PATH)
    x('cp %s/hardening/issue.net /etc/issue.net' % app.SYCO_VAR_PATH)

    x("chown root:root /etc/motd")
    x("chmod 644 /etc/motd")
    x("chown root:root /etc/issue")
    x("chmod 644 /etc/issue")
    x("chown root:root /etc/issue.net")
    x("chmod 644 /etc/issue.net")
Example #50
0
def _install_glassfish():
    '''
  Installation of the glassfish application server.

  '''
    if (not os.access(GLASSFISH_INSTALL_PATH + "/glassfish", os.F_OK)):
        os.chdir(app.INSTALL_DIR)
        if (not os.access(GLASSFISH_INSTALL_FILE, os.F_OK)):
            general.download_file(GLASSFISH_REPO_URL, user="******")

        # Create installation dir
        if (not os.access(GLASSFISH_INSTALL_PATH, os.F_OK)):
            x("mkdir -p " + GLASSFISH_INSTALL_PATH)
            x("chmod 770 " + GLASSFISH_INSTALL_PATH)
            x("chown 200:200 " + GLASSFISH_INSTALL_PATH)

        # Set executeion permissions and run the installation.
        if ".zip" in GLASSFISH_INSTALL_FILE:
            install.package("unzip")
            x("unzip " + GLASSFISH_INSTALL_FILE + " -d " +
              GLASSFISH_INSTALL_PATH,
              user="******")
            x("mv " + GLASSFISH_INSTALL_PATH + "glassfish3/* " +
              GLASSFISH_INSTALL_PATH,
              user="******")
            x("rm -rf " + GLASSFISH_INSTALL_PATH + "glassfish3",
              user="******")
        else:
            raise Exception("Only installing zip version of glassfish")

        # Install the start script
        # It's possible to do this from glassfish with "asadmin create-service",
        # but our own script is a little bit better. It creates startup log files
        # and has a better "start user" functionality.
        if (not os.access("/etc/init.d/" + GLASSFISH_VERSION, os.F_OK)):
            x("cp " + app.SYCO_PATH + "var/glassfish/" + GLASSFISH_VERSION +
              " /etc/init.d/" + GLASSFISH_VERSION)
            x("chmod 0755 " + "/etc/init.d/" + GLASSFISH_VERSION)
            x("/sbin/chkconfig --add " + GLASSFISH_VERSION)
            x("/sbin/chkconfig --level 3 " + GLASSFISH_VERSION + " on")

            scOpen("/etc/init.d/" + GLASSFISH_VERSION).replace(
                "${MYSQL_PRIMARY}",
                config.general.get_mysql_primary_master_ip())
            scOpen("/etc/init.d/" + GLASSFISH_VERSION).replace(
                "${MYSQL_SECONDARY}",
                config.general.get_mysql_secondary_master_ip())

    if (not os.access(GLASSFISH_DOMAINS_PATH + "domain1/config/domain.xml",
                      os.F_OK)):
        raise Exception("Failed to install " + GLASSFISH_INSTALL_PATH)

    if (not os.access("/etc/init.d/" + GLASSFISH_VERSION, os.F_OK)):
        raise Exception("Failed to install /etc/init.d/" + GLASSFISH_VERSION)
Example #51
0
 def autostart_guests(self):
     # Autostart guests.
     x("virsh autostart " + self.hostname)
     x("virsh start " + self.hostname)
Example #52
0
def install_logstash_syslog(args):
    '''
	Install the logstash plugin for syslog
	'''
    if len(args) != 2:
        raise Exception("syco install-logstash-syslog 1.5.0")

    if not os.path.isfile('/usr/bin/java'):
        raise Exception("No Java stopping")

    x('yum install wget -y')
    os.system(
        'wget http://download.elastic.co/logstash/logstash/logstash-{0}.tar.gz -O /tmp/logstash.tar.gz'
        .format(args[1]))
    x('tar zxvf /tmp/logstash.tar.gz -C /opt/')
    x('rm -rf /opt/logstash')
    x('ln -s /opt/logstash* /opt/logstash')
    x('mkdir /etc/logstash')
    x('cp /opt/syco/usr/syco-private/var/logstash/logstash_shipper.conf /etc/logstash/'
      )
    x('cp /opt/syco/usr/syco-private/var/logstash/start/shipper /etc/init.d/')
    x('chmod 775 /etc/init.d/shipper')
    x('chkconfig --add shipper')
    x('chkconfig  shipper on')
Example #53
0
def install_nodejs(args):
	if len(args) != 2:
		raise Exception("syco install-nodejs 0.12.2 (or other version)")
	version = args[1]
	x('rm -rf /usr/node')
	x('mkdir /usr/node')
	os.chdir('/usr/node')
	#use general.shell_exec since x(wget) gives an error for each progress output
	general.shell_exec('wget http://nodejs.org/dist/v{0}/node-v{1}.tar.gz'.format(version, version))
	x('tar xzvf node-v* && cd node-v*')
	x('yum install gcc gcc-c++ -y')
	x('cd node-v* && ./configure')
	x('cd node-v* && make')
	x('cd node-v* && make install')
Example #54
0
 def check_if_host_is_installed(self):
     result = x("virsh list --all")
     if (self.hostname in result):
         raise Exception(self.hostname + " already installed")
Example #55
0
def _install_guice():
    '''
  Installing guice to glassfish
  '''
    os.chdir(app.INSTALL_DIR)
    general.download_file(GUICE_URL)
    x("unzip " + GUICE_NAME + ".zip")
    x("cp " + GUICE_NAME + "/" + GUICE_NAME + ".jar " +
      GLASSFISH_INSTALL_PATH + "/glassfish/domains/domain1/lib/ext/")
    x("cp " + GUICE_NAME + "/guice-assistedinject* " + GLASSFISH_INSTALL_PATH +
      "/glassfish/domains/domain1/lib/ext/")
    x("cp " + GUICE_NAME + "/aopalliance* " + GLASSFISH_INSTALL_PATH +
      "/glassfish/domains/domain1/lib/ext/")
    x("cp " + GUICE_NAME + "/javax.inject* " + GLASSFISH_INSTALL_PATH +
      "/glassfish/domains/domain1/lib/ext/")
    x("chown glassfish:glassfish -R " + GLASSFISH_INSTALL_PATH +
      "/glassfish/domains/domain1/lib/ext/*")
    x("yum remove unzip -y")
Example #56
0
 def unmount_dvd(self):
     x("umount /media/dvd")
Example #57
0
def _modify_cobbler_settings():
    app.print_verbose("Update cobbler config files")
    general.set_config_property(
        "/etc/cobbler/settings", '^server:.*',
        "server: " + config.general.get_installation_server_ip())
    general.set_config_property(
        "/etc/cobbler/settings", '^next_server:.*',
        "next_server: " + config.general.get_installation_server_ip())
    general.set_config_property("/etc/cobbler/settings",
                                '^default_virt_bridge:.*',
                                "default_virt_bridge: br0")
    general.set_config_property(
        "/etc/cobbler/settings", '^default_password_crypted:.*',
        "default_password_crypted: " + app.get_root_password_hash())
    general.set_config_property("/etc/cobbler/settings",
                                '^default_virt_type:.*',
                                "default_virt_type: qemu")
    general.set_config_property("/etc/cobbler/settings", '^anamon_enabled:.*',
                                "anamon_enabled: 1")
    general.set_config_property("/etc/cobbler/settings",
                                '^yum_post_install_mirror:.*',
                                "yum_post_install_mirror: 1")
    general.set_config_property("/etc/cobbler/settings", '^manage_dhcp:.*',
                                "manage_dhcp: 1")

    # Email out a report when cobbler finishes installing a system.
    general.set_config_property('/etc/cobbler/settings',
                                '^build_reporting_enabled:.*',
                                'build_reporting_enabled: 1')
    general.set_config_property(
        '/etc/cobbler/settings', '^build_reporting_email::.*',
        "build_reporting_email: [ '%s' ]" % config.general.get_admin_email())

    # Setup kickstart files.
    shutil.copyfile(app.SYCO_PATH + "/var/kickstart/cobbler.ks",
                    "/var/lib/cobbler/kickstarts/cobbler.ks")

    # Configure DHCP
    shutil.copyfile(app.SYCO_PATH + "/var/dhcp/dhcp.template",
                    "/etc/cobbler/dhcp.template")

    # Config crontab to update repo automagically
    general.set_config_property2("/etc/crontab",
                                 "01 4 * * * syco install-cobbler-repo")

    # Set apache servername
    general.set_config_property(
        "/etc/httpd/conf/httpd.conf", "#ServerName www.example.com:80",
        "ServerName " + config.general.get_installation_server() + ":80")
    x("/etc/init.d/httpd restart")

    x("/etc/init.d/cobblerd restart")

    # Wait for cobblered to restart
    time.sleep(1)

    # Iptables rules need be fixed now.
    x("cobbler get-loaders")

    # Setup distro/repo for centos
    x("cobbler check")
Example #58
0
def net_setup_bond_br(args):
    """
    Setup bonded network interfaces and bridges.

    This must work together with a virtual host using KVM.

    Read more.
    http://serverfault.com/questions/316623/what-is-the-correct-way-to-setup-a-bonded-bridge-on-centos-6-for-kvm-guests
    http://www.linuxfoundation.org/collaborate/workgroups/networking/bridge
    http://www.cyberciti.biz/faq/rhel-linux-kvm-virtualization-bridged-networking-with-libvirt/
    http://www.linux-kvm.org/page/HOWTO_BONDING
    https://fedorahosted.org/cobbler/wiki/VirtNetworkingSetupForUseWithKoan
    http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Virtualization/sect-Virtualization-Network_Configuration-Bridged_networking_with_libvirt.html
    http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s1-networkscripts-interfaces.html
    http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/sec-Using_Channel_Bonding.html

    """
    app.print_verbose("Install bonded bridges host version: %d" %
                      SCRIPT_VERSION)
    version_obj = version.Version("NetSetupBondBr", SCRIPT_VERSION)
    version_obj.check_executed()

    #
    app.print_verbose(
        "Install yum package with all tools that is required to setup bridges."
    )
    install.package("bridge-utils")

    #
    print_verbose(
        "Setup modprobe alias for bonding, don't know exactly why we need to "
        +
        "do that. Maybe because the ifcfg files referars to bond0 instead of "
        +
        "bonding, or because it loads the module bonding at the same time as "
        + "the alias is created.")
    sycoConf = scOpen("/etc/modprobe.d/syco.conf")
    sycoConf.remove("alias bond.*")
    sycoConf.add("alias bond0 bonding")

    # Get all parameters from syco config.
    # Check if interfaces are defined, otherwise fall back to autodetecting
    front_interfaces = config.host(net.get_hostname()).get_front_interfaces()
    back_interfaces = config.host(net.get_hostname()).get_back_interfaces()

    num_of_if = len(front_interfaces) + len(back_interfaces)
    if num_of_if == 0:
        # Autodetect
        num_of_if = net.num_of_eth_interfaces()

    front_ip = config.host(net.get_hostname()).get_front_ip()
    front_netmask = config.general.get_front_netmask()
    front_gw = config.general.get_front_gateway_ip()
    front_resolver = config.general.get_front_resolver_ip()
    net_count = 1

    if config.general.is_back_enabled():
        back_ip = config.host(net.get_hostname()).get_back_ip()
        back_netmask = config.general.get_back_netmask()
        back_gw = config.general.get_back_gateway_ip()
        back_resolver = config.general.get_back_resolver_ip()
        net_count += 1

    eth_count = 0
    if len(front_interfaces) < 1:
        # Use default eth interfaces
        # Also, if you don't specify front net interfaces, you may not specify back net interfaces.
        if_per_net_count = int(math.floor(num_of_if / net_count))

        if net_count > 1:
            back_interfaces = []
            for i in range(if_per_net_count):
                back_interfaces.append("eth" + str(eth_count))
                eth_count += 1

        front_interfaces = []
        for i in range(if_per_net_count):
            front_interfaces.append("eth" + str(eth_count))
            eth_count += 1

    app.print_verbose(
        "Configuring front net bond bond1 with interfaces: {0}".format(
            front_interfaces))
    setup_bridge("br1", front_ip, front_netmask, front_gw, front_resolver)
    setup_bond("bond1", "br1")
    for front_interface in front_interfaces:
        setup_eth(front_interface, "bond1")

    if net_count == 2:
        app.print_verbose(
            "Found back-net configuration, configuring second bond bond0 with interfaces: {0}"
            .format(back_interfaces))
        setup_bridge("br0", back_ip, back_netmask, back_gw, back_resolver)
        setup_bond("bond0", "br0")
        for back_interface in back_interfaces:
            setup_eth(back_interface, "bond0")

    #
    app.print_verbose(
        "Restart the network service so all changes will be applied.")
    x("service network restart")
    x("echo \"nameserver 8.8.8.8\" > /etc/resolv.conf")

    #
    version_obj.mark_executed()
Example #59
0
def edit_iface_attr(hostname, iface, key, value):
    if (key and value):
        x("cobbler system edit --name=%s --interface=%s %s=%s" %
          (hostname, iface, key, value))
Example #60
0
def _install_jdk():
    '''
  Installation of the java sdk.

  '''
    if (not os.access(JDK_INSTALL_PATH, os.F_OK)):
        os.chdir(app.INSTALL_DIR)
        if (not os.access(JDK_INSTALL_FILE, os.F_OK)):
            general.download_file(JDK_REPO_URL)

            x("chmod u+rx " + JDK_INSTALL_FILE)

        if (os.access(JDK_INSTALL_FILE, os.F_OK)):
            x("tar -zxvf " + JDK_INSTALL_FILE)
            x("mkdir /usr/java")
            x("mv " + JDK_VERSION + " /usr/java")
            x("rm -f /usr/java/default")
            x("rm -f /usr/java/latest")
            x("ln -s /usr/java/" + JDK_VERSION + " /usr/java/default")
            x("ln -s /usr/java/default /usr/java/latest")
            x("chown root:glassfish -R /usr/java/" + JDK_VERSION)
            x("chmod 774 -R /usr/java/" + JDK_VERSION)
            x("chmod 701 /usr/java")
            x("alternatives --install /usr/bin/javac javac /usr/java/latest/bin/javac 20000"
              )
            x("alternatives --install /usr/bin/jar jar /usr/java/latest/bin/jar 20000"
              )
            x("alternatives --install /usr/bin/java java /usr/java/latest/jre/bin/java 20000"
              )
            x("alternatives --install /usr/bin/javaws javaws /usr/java/latest/jre/bin/javaws 20000"
              )

        else:
            raise Exception("Not able to download " + JDK_INSTALL_FILE)