Пример #1
0
def create_persistent_diy_dirs():
    if not os.path.exists(DIY_STATE_PATH):
        process, output, error = linuxutil.popen_communicate(
            ["sudo", "mkdir", "-p", "-m", "770", DIY_STATE_PATH])
        if process.returncode != 0:
            raise Exception("Unable to create dir " + DIY_STATE_PATH +
                            ". Error: " + str(error))

    if not os.path.exists(DIY_WORKING_DIR):
        process, output, error = linuxutil.popen_communicate(
            ["sudo", "mkdir", "-p", "-m", "770", DIY_WORKING_DIR])
        if process.returncode != 0:
            raise Exception("Unable to create dir " + DIY_WORKING_DIR +
                            ". Error: " + str(error))

    linuxutil.set_user_and_group_recursive(owning_username="******",
                                           owning_group_name="omiusers",
                                           path=NXAUTOMATION_HOME_DIR)
    linuxutil.set_permission_recursive(permission="770",
                                       path=NXAUTOMATION_HOME_DIR)

    linuxutil.set_user_and_group_recursive(owning_username="******",
                                           owning_group_name="omiusers",
                                           path=DIY_WORKING_DIR)
    linuxutil.set_permission_recursive(permission="770", path=DIY_WORKING_DIR)
Пример #2
0
def generate_hmac(str_to_sign, secret):
    """Signs the specified string using the specified secret.

    Args:
        str_to_sign : string, the string to sign
        secret      : string, the secret used to sign

    Returns:
        signed_message : string, the signed str_to_sign
    """
    message = str_to_sign.encode('utf-8')
    secret = secret.encode('utf-8')
    cmd = [
        'echo -n "' + str(message.decode("utf-8")) +
        '" | openssl dgst -sha256 -binary -hmac "' +
        str(secret.decode("utf-8")) + '"'
    ]
    process, signed_message, error = linuxutil.popen_communicate(cmd,
                                                                 shell=True)

    error = error.decode() if isinstance(error, bytes) else error
    if process.returncode != 0:
        raise Exception("Unable to generate signature. " + str(error))

    return signed_message
Пример #3
0
def create_persistent_diy_dirs():
    if not os.path.exists(DIY_STATE_PATH):
        process, output, error = linuxutil.popen_communicate(["sudo", "mkdir", "-p", "-m", "770", DIY_STATE_PATH])
        if process.returncode != 0:
            raise Exception("Unable to create dir " + DIY_STATE_PATH + ". Error: " + str(error))

    if not os.path.exists(DIY_WORKING_DIR):
        process, output, error = linuxutil.popen_communicate(["sudo", "mkdir", "-p", "-m", "770", DIY_WORKING_DIR])
        if process.returncode != 0:
            raise Exception("Unable to create dir " + DIY_WORKING_DIR + ". Error: " + str(error))


    linuxutil.set_user_and_group_recursive(owning_username="******", owning_group_name="omiusers",
                                           path=NXAUTOMATION_HOME_DIR)
    linuxutil.set_permission_recursive(permission="770", path=NXAUTOMATION_HOME_DIR)

    linuxutil.set_user_and_group_recursive(owning_username="******", owning_group_name="omiusers",
                                           path=DIY_WORKING_DIR)
    linuxutil.set_permission_recursive(permission="770", path=DIY_WORKING_DIR)
def set_permission_recursive(permission, path):
    """Sets the permission for a specific path and it's child items recursively.

    Args:
        permission  : string, linux permission (i.e 770).
        path        : string, the target path.
    """
    cmd = ["chmod", "-R", permission, path]
    process, output, error = linuxutil.popen_communicate(cmd)
    if process.returncode != 0:
        raise Exception(
            "Unable to change permission of " + str(path) + " to " + str(permission) + ". Error : " + str(error))
    print "Permission changed to " + str(permission) + " for " + str(path)
def set_user_and_group_recursive(owning_username, owning_group_name, path):
    """Sets the owner for a specific path and it's child items recursively.

    Args:
        owning_username     : string, the owning user
        owning_group_name   : string, the owning group
        path                : string, the target path.
    """
    owners = owning_username + ":" + owning_group_name
    cmd = ["chown", "-R", owners, path]
    process, output, error = linuxutil.popen_communicate(cmd)
    if process.returncode != 0:
        raise Exception("Unable to change owner of " + str(path) + " to " + str(owners) + ". Error : " + str(error))
    print "Owner changed to " + str(owners) + " for " + str(path)
def generate_self_signed_certificate(certificate_path, key_path):
    """Creates a self-signed x509 certificate and key pair in the spcified path.

    Args:
        certificate_path    : string, the output path of the certificate
        key_path            : string, the output path of the key
    """
    cmd = ["openssl", "req", "-subj",
           "/C=US/ST=Washington/L=Redmond/O=Microsoft Corporation/OU=Azure Automation/CN=Hybrid Runbook Worker",
           "-new", "-newkey", "rsa:2048", "-days", "365", "-nodes", "-x509", "-keyout", key_path, "-out",
           certificate_path]
    process, certificate_creation_output, error = linuxutil.popen_communicate(cmd)
    if process.returncode != 0:
        raise Exception("Unable to create certificate/key. " + str(error))
    print "Certificate/Key created."
def generate_self_signed_certificate(certificate_path, key_path):
    """Creates a self-signed x509 certificate and key pair in the spcified path.

    Args:
        certificate_path    : string, the output path of the certificate
        key_path            : string, the output path of the key
    """
    cmd = ["openssl", "req", "-subj",
           "/C=US/ST=Washington/L=Redmond/O=Microsoft Corporation/OU=Azure Automation/CN=Hybrid Runbook Worker",
           "-new", "-newkey", "rsa:2048", "-days", "365", "-nodes", "-x509", "-keyout", key_path, "-out",
           certificate_path]
    process, certificate_creation_output, error = linuxutil.popen_communicate(cmd)
    if process.returncode != 0:
        raise Exception("Unable to create certificate/key. " + str(error))
    print "Certificate/Key created."
def sha256_digest(payload):
    """Sha256 digest of the specified payload.

    Args:
        payload : string, the payload to digest

    Returns:
        payload_hash : string, the sha256 hash of the payload
    """
    cmd = ['echo -n "' + str(json.dumps(json.dumps(payload))) + '" | openssl dgst -sha256 -binary']
    process, payload_hash, error = linuxutil.popen_communicate(cmd, shell=True)

    if process.returncode != 0:
        raise Exception("Unable to generate payload hash. " + str(error))

    return payload_hash
def get_hostname():
    oms_agent_hostname_command = ['/opt/microsoft/omsagent/ruby/bin/ruby', '-r',
                                  '/opt/microsoft/omsagent/plugin/oms_common.rb', '-e', 'puts OMS::Common.get_hostname']
    # Use the ruby util OMS agent uses to get hostname
    try:
        process, output, error = linuxutil.popen_communicate(oms_agent_hostname_command)
        if process.returncode == 0 and not error:
            return output.strip()
    except OSError:
        pass
    # Unable to use ruby util, falling back on socket to get hostname
    hostname = socket.gethostname()
    if is_ipv4(hostname):
        return hostname
    else:
        return hostname.split(".")[0]
def get_hostname():
    oms_agent_hostname_command = ['/opt/microsoft/omsagent/ruby/bin/ruby', '-r',
                                  '/opt/microsoft/omsagent/plugin/oms_common.rb', '-e', 'puts OMS::Common.get_hostname']
    # Use the ruby util OMS agent uses to get hostname
    try:
        process, output, error = linuxutil.popen_communicate(oms_agent_hostname_command)
        if process.returncode == 0 and not error:
            return output.strip()
    except OSError:
        pass
    # Unable to use ruby util, falling back on socket to get hostname
    hostname = socket.gethostname()
    if is_ipv4(hostname):
        return hostname
    else:
        return hostname.split(".")[0]
def sha256_digest(payload):
    """Sha256 digest of the specified payload.

    Args:
        payload : string, the payload to digest

    Returns:
        payload_hash : string, the sha256 hash of the payload
    """
    cmd = ['echo -n "' + str(json.dumps(json.dumps(payload))) + '" | openssl dgst -sha256 -binary']
    process, payload_hash, error = linuxutil.popen_communicate(cmd, shell=True)

    if process.returncode != 0:
        raise Exception("Unable to generate payload hash. " + str(error))

    return payload_hash
def generate_hmac(str_to_sign, secret):
    """Signs the specified string using the specified secret.

    Args:
        str_to_sign : string, the string to sign
        secret      : string, the secret used to sign

    Returns:
        signed_message : string, the signed str_to_sign
    """
    message = str_to_sign.encode('utf-8')
    secret = secret.encode('utf-8')
    cmd = ['echo -n "' + str(message) + '" | openssl dgst -sha256 -binary -hmac "' + str(secret) + '"']
    process, signed_message, error = linuxutil.popen_communicate(cmd, shell=True)

    if process.returncode != 0:
        raise Exception("Unable to generate signature. " + str(error))

    return signed_message
Пример #13
0
def initialize():
    """Initializes the OMS environment. Meant to be executed everytime the resource's set method is invoked.
    Steps:
        - Sets omsagent group to nxautomation user (if needed).
        - Sets group read permission to MSFT keyring.gpg
        - Sets group read and execute to the OMS certificate folder.

    Args:
        None
    """
    # add nxautomation to omsagent group
    nxautomation_uid = int(pwd.getpwnam(USERNAME_NXAUTOMATION).pw_uid)
    if os.getuid() == nxautomation_uid:
        omsagent_group = grp.getgrnam(GROUPNAME_OMSAGENT)
        if USERNAME_NXAUTOMATION not in omsagent_group.gr_mem:
            print_success_message = False
            process, output, error = linuxutil.popen_communicate(["sudo", "/usr/sbin/usermod", "-g", "nxautomation",
                                                                  "-a", "-G", "omsagent,omiusers", "nxautomation"])
            if process.returncode != 0:
                # try again with -A instead of -a for SUSE Linux
                process, output, error = linuxutil.popen_communicate(["sudo", "/usr/sbin/usermod", "-g", "nxautomation",
                                                                      "-A", "omsagent,omiusers", "nxautomation"])
                if process.returncode != 0:
                    raise Exception("Unable to add nxautomation to omsagent group. Error: " + str(error))
                else:
                    print_success_message = True
            else:
                print_success_message = True
            if print_success_message:
                print "Successfully added omsagent secondary group to nxautomation user."

    # change permissions for the keyring.gpg
    process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "g+r",
                                                          "/etc/opt/omi/conf/omsconfig/keyring.gpg"])
    if process.returncode != 0:
        raise Exception("Unable set group permission to keyring. Error: " + str(error))
    else:
        print "Successfully set group permissions to keyring.gpg."

    # change permission for the certificate folder, oms.crt and oms.key
    process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "g+rx", "-R",
                                                          "/etc/opt/microsoft/omsagent/certs"])
    if process.returncode != 0:
        raise Exception("Unable set group permissions to certificate folder. Error: " + str(error))
    else:
        print "Successfully set group permissions to certificate folder."

    # change owner for the worker working directory
    process, output, error = linuxutil.popen_communicate(["sudo", "chown", "nxautomation:omiusers", "-R",
                                                          "/var/opt/microsoft/omsagent/run/automationworker"])
    if process.returncode != 0:
        raise Exception("Unable set group owner to certificate folder. Error: " + str(error))
    else:
        print "Successfully set group permissions to certificate folder."

    process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "g+rx", "-R",
                                                          "/var/opt/microsoft/omsagent/run/automationworker"])
    if process.returncode != 0:
        raise Exception("Unable set owners of certificate folder. Error: " + str(error))
    else:
        print "Successfully set owners of certificate folder."

    proxy_paths = ["/etc/opt/microsoft/omsagent/conf/proxy.conf", "/etc/opt/microsoft/omsagent/proxy.conf"]
    for path in proxy_paths:
        if os.path.exists(path):
            process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "g+r", path])

            if process.returncode != 0:
                raise Exception("Unable set read permission to proxy configuration file. Error: " + str(error))
            else:
                print "Successfully set read permission to proxy configuration file."
Пример #14
0
def initialize():
    """Initializes the OMS environment. Meant to be executed everytime the resource's set method is invoked.
    Steps:
        - Sets omsagent group to nxautomation user (if needed).
        - Sets group read permission to MSFT keyring.gpg
        - Sets group read and execute to the OMS certificate folder.

    Args:
        None
    """
    # add nxautomation to omsagent group
    nxautomation_uid = int(pwd.getpwnam(USERNAME_NXAUTOMATION).pw_uid)
    if os.getuid() == nxautomation_uid:
        omsagent_group = grp.getgrnam(GROUPNAME_OMSAGENT)
        if USERNAME_NXAUTOMATION not in omsagent_group.gr_mem:
            print_success_message = False
            process, output, error = linuxutil.popen_communicate(["sudo", "/usr/sbin/usermod", "-g", "nxautomation",
                                                                  "-a", "-G", "omsagent,omiusers", "nxautomation"])
            if process.returncode != 0:
                # try again with -A instead of -a for SUSE Linux
                process, output, error = linuxutil.popen_communicate(["sudo", "/usr/sbin/usermod", "-g", "nxautomation",
                                                                      "-A", "omsagent,omiusers", "nxautomation"])
                if process.returncode != 0:
                    raise Exception("Unable to add nxautomation to omsagent group. Error: " + str(error))
                else:
                    print_success_message = True
            else:
                print_success_message = True
            if print_success_message:
                print "Successfully added omsagent secondary group to nxautomation user."

    # change permissions for the keyring.gpg
    process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "g+r",
                                                          "/etc/opt/omi/conf/omsconfig/keyring.gpg"])
    if process.returncode != 0:
        raise Exception("Unable set group permission to keyring. Error: " + str(error))
    else:
        print "Successfully set group permissions to keyring.gpg."

    # change permission for the certificate folder, oms.crt and oms.key
    process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "g+rx", "-R",
                                                          "/etc/opt/microsoft/omsagent/certs"])
    if process.returncode != 0:
        raise Exception("Unable set group permissions to certificate folder. Error: " + str(error))
    else:
        print "Successfully set group permissions to certificate folder."

    # change owner for the worker working directory
    process, output, error = linuxutil.popen_communicate(["sudo", "chown", "nxautomation:omiusers", "-R",
                                                          "/var/opt/microsoft/omsagent/run/automationworker"])
    if process.returncode != 0:
        raise Exception("Unable set group owner on working directory. Error: " + str(error))
    else:
        print "Successfully set group permissions on working directory."

    # change permission for the worker working directory
    process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "gu=rwx", "-R",
                                                          "/var/opt/microsoft/omsagent/run/automationworker"])
    if process.returncode != 0:
        raise Exception("Unable set permissions on working directory. Error: " + str(error))
    else:
        print "Successfully set permissions on working directory."

    # explicitly prevent others from accessing the worker working directory
    process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "o=", "-R",
                                                          "/var/opt/microsoft/omsagent/run/automationworker"])
    if process.returncode != 0:
        raise Exception("Unable set permissions on working directory. Error: " + str(error))
    else:
        print "Successfully set permissions on working directory."

    proxy_paths = ["/etc/opt/microsoft/omsagent/conf/proxy.conf", "/etc/opt/microsoft/omsagent/proxy.conf"]
    for path in proxy_paths:
        if os.path.exists(path):
            process, output, error = linuxutil.popen_communicate(["sudo", "chmod", "g+r", path])

            if process.returncode != 0:
                raise Exception("Unable set read permission to proxy configuration file. Error: " + str(error))
            else:
                print "Successfully set read permission to proxy configuration file."

    # create home dir for nxautomation
    diydirs.create_persistent_diy_dirs()