#!/usr/bin/python
# Security Hardening script during node join
import logging
import os
import time
import sys
import syslog
import errno
import subprocess
import re

JOIN_PATH = "/var/log"
SSHD_CONF = "/etc/mcp/templates/sshd_config"
LOG_FILE = os.path.join(JOIN_PATH, "hardening_join.log")
logger = logging.getLogger("hardening_join")
MAX_RETRIES = 10


def execute_command(cmd):
    """ To execute external commands """
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            bufsize=-1, shell=True)
    stdout, stderr = proc.communicate()
    result = 0
    if stderr or proc.returncode:
        print 'Error %s occured while executing command %s' % (stderr, cmd)
        logger.error('Error %s occured while executing command %s' %
                     (stderr, cmd))
        result = proc.returncode
    return result

"""
Function to revert hardening on the old node joining the cluster
"""


def prep_setup(operation=None):
    try:
        # Check Environment
        import isi.hardening.util as util
        util.env_check()
        if not util.is_locked():  # XXX: Check funciton for more details
            running_operation = util.get_status_from_lck()
            if running_operation == 'apply':
                syslog.syslog(syslog.LOG_NOTICE,
                    "Hardening apply on this cluster is in progress ...")
            elif running_operation == 'revert':
                syslog.syslog(syslog.LOG_NOTICE,
                    "Hardening revert on this cluster is in progress ...")
            sys.exit(2)
        else:
            # Aquire Lock and Set join Flag
            if operation and operation not in ['apply', 'revert']:
                logger.error("Failing, Invalid operation %s", operation)
                return 1
            aquire_lock(operation)
            try:
                os.chmod(LOG_FILE, 0640)
            except OSError, e:
                # log chmod errors and continue
                syslog.syslog(syslog.LOG_NOTICE,
                              "Error chmod'ing %s (errno: %d)" % (LOG_FILE, e.errno))

    except Exception as exception:
        logger.error("Exception occured in join process %s" % exception)


def aquire_lock(operation):
    try:
        import isi.hardening.util as util
        lock_status = util.acquire_lock(operation)
        util.JOIN_FLAG = True
        retry = MAX_RETRIES
        while retry:
            try:
                logger.setLevel(logging.DEBUG)
                fh = logging.FileHandler(LOG_FILE, 'a')
                fh.setLevel(logging.DEBUG)
                logger.addHandler(fh)
                break
            except EnvironmentError, e:
                syslog.syslog(syslog.LOG_NOTICE,
                              "Error during logging "
                              "in hardening-upgrade script, %s %d" % (e, (MAX_RETRIES - retry + 1)))
                if retry == 1:
                    syslog.syslog(
                        syslog.LOG_NOTICE, "Error: Exiting from hardening-upgrade script")
                    return 1
                time.sleep(5)
                retry = retry - 1

    except Exception as exception:
        logger.error("Failed to aquire Lock on Hardening Engine")


def harden_new_node(upgraded=False):
    """
    Description: Applies hardening on the joining node.

    """
    import isi.hardening.util as util
    if not os.path.isfile(util.CHE_META_FILE):
        open(util.CHE_META_FILE, 'a').close()
    else:
        syslog.syslog(syslog.LOG_NOTICE,
            "/etc/ifs/isi_hardening_join_already_ran present already,.exiting")
        return 0
    try:
        # /usr/sbin/tcpdump is missing on joining node for somecases to avoid
        # issues around this copy 'tcpdump' from the backup.tar.gz in /ifs
        if not os.path.isfile(util.TCPDUMP):
            cmd = 'cp ' + util.CHE_BACKUP_TAR_LOCATION + ' ' + util.BACKUP_LOCATION
            try:
                c_ret = util.execute_command(cmd)
                if c_ret ==0:
                    syslog.syslog(syslog.LOG_NOTICE, "copied tcpdump back on node.")
                else:
                    syslog.syslog(syslog.LOG_NOTICE, "Copy tcpdump failed.")
            except Exception, e:
                logger.error("%s command execution failed" %cmd)
        prep_setup(operation='apply')
        logger.info("Calling Hardening Engine Components now...")
        # Check expected state before the Hardening apply operation
        if upgraded:
            CHE_ces_cmd = "python " + util.CHE_BIN_PATH + "/check_expected_state.py -j " \
                + util.NON_H_JOIN_CONFIG_PATH + " >> /dev/null 2>&1 "
            CHE_apply_cmd = "python " + util.CHE_BIN_PATH + "/apply.py -j " \
                + util.NON_H_JOIN_CONFIG_PATH + " >> /dev/null 2>&1"
        else:
            CHE_ces_cmd = "python " + util.CHE_BIN_PATH + "/check_expected_state.py -n " \
                + util.NON_H_JOIN_CONFIG_PATH + " >> /dev/null 2>&1 "
            CHE_apply_cmd = "python " + util.CHE_BIN_PATH + "/apply.py -n " \
                + util.NON_H_JOIN_CONFIG_PATH + " >> /dev/null 2>&1"
        try:
            CHE_ces_ret = util.execute_command(CHE_ces_cmd)
            logger.info(CHE_ces_cmd)
            if CHE_ces_ret == 0:
                logger.info("%s: Check Expected State completed successfully"
                            % time.ctime())
                success = True
            else:
                logger.error("%s: Check Expected State failed" %
                             time.ctime())
                success = False
        except Exception, e:
            success = False
            logger.error("%s: Error during Check Expected State run %s (errno: %d)" %
                         (time.ctime(), LOG_FILE, e.errno))
        # Apply the Hardening operation

        if success:
            try:
                logger.info(CHE_apply_cmd)
                CHE_apply_ret = util.execute_command(CHE_apply_cmd)
                if CHE_apply_ret != 0:
                    logger.error("%s: Error during Hardening Engine Apply run" %
                                 time.ctime())
                    success = False
                else:
                    logger.error("%s: Hardening Engine Apply completed successfully" %
                                 time.ctime())
                    success = True
            except Exception, e:
                success = False
                logger.error("%s: Error during Hardening Engine Apply %s (errno: %d)" %
                             (time.ctime(), LOG_FILE, e.errno))

        if success:
            logger.error("%s: Hardening completed successfully during join" %
                         time.ctime())
            os.remove(util.CHE_META_FILE)
            return 0
        else:
            logger.error("%s: Hardening failed during node join" %
                         time.ctime())
    except Exception as exception:
        logger.error("Exception occured in join process %s" % exception)

    finally:
        # release lock
        util.release_lock()

def update_sshd_config():
    conf_fname = SSHD_CONF
    conf_file = open(conf_fname)
    conf = conf_file.readlines()
    conf_file.close()

    config = open(conf_fname + '.isi', "w")

    token_re = re.compile(r'^ListenAddress\s+.*')
    for line in conf:
        line = line.rstrip()
        tokens = token_re.findall(line)
        if tokens:
            continue
        config.write('%s\n' % line)

    config.flush()
    os.fsync(config.fileno())
    config.close()
    os.chmod(conf_fname + '.isi', 0640)
    os.rename(conf_fname + '.isi', conf_fname)


def main():
    """ Hardening Join starts here"""
    # Generate Metadata required for Hardening
    cmd = "/usr/bin/isi_hardening/metadata_generator.py"
    try:
        cmd_ret = execute_command(cmd)
        if cmd_ret != 0:
            syslog.syslog(syslog.LOG_NOTICE, "%s failed to execute" % cmd)
        else:
            syslog.syslog(syslog.LOG_NOTICE, "%s : Executed" % cmd)
    except Exception as exception:
        syslog.syslog(syslog.LOG_NOTICE, "Un-Expected Error occured")

    import isi.hardening.util as util
    if (util.is_cluster_hardened()):
        syslog.syslog(syslog.LOG_NOTICE, "Cluster is Hardened")
        # Case A
        if (util.is_node_hardened()):  # case A.1
            # New Node should be Hardened with config on the Cluster.
            return 0
        else:  # Case A.2
            # New node should be hardened with the config as on Cluster.
            # skip if the node is re-imaged case A.1
            import isi.hardening.util as util
            if (os.path.exists(util.META_HARDENING_JOIN)):
                with open(util.META_HARDENING_JOIN, 'r') as file:
                    text = file.read()
                    text = text.strip('\n')
                    if text == "ReimagedNode" or text == "ReimagedNodeNormalNode":
                        update_sshd_config()
                        harden_new_node(upgraded=True)
                        return 0
                    else:
                        syslog.syslog(syslog.LOG_NOTICE, "Hardening the Node with Configuration on Cluster")
                        harden_new_node()
                        return 0
            else:
                syslog.syslog(syslog.LOG_NOTICE, '%s missing on joining node' % util.META_HARDENING_JOIN)
                return 1
    else:
        # This case is handled with in the isi_join_d code path.
        syslog.syslog(syslog.LOG_NOTICE, "Cluster is Not hardened")
        return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception, e:
        syslog.syslog(syslog.LOG_ERR,
                      "Error running hardening script during join, %s" % e)
