Example #1
0
    def deploy_ssh_pubkey(self, username, pubkey):
        """
        Deploy authorized_key
        """
        path, thumbprint, value = pubkey
        if path is None:
            raise OSUtilError("Public key path is None")

        crytputil = CryptUtil(conf.get_openssl_cmd())

        path = self._norm_path(path)
        dir_path = os.path.dirname(path)
        fileutil.mkdir(dir_path, mode=0o700, owner=username)
        if value is not None:
            if not value.startswith("ssh-"):
                raise OSUtilError("Bad public key: {0}".format(value))
            fileutil.write_file(path, value)
        elif thumbprint is not None:
            lib_dir = conf.get_lib_dir()
            crt_path = os.path.join(lib_dir, thumbprint + '.crt')
            if not os.path.isfile(crt_path):
                raise OSUtilError("Can't find {0}.crt".format(thumbprint))
            pub_path = os.path.join(lib_dir, thumbprint + '.pub')
            pub = crytputil.get_pubkey_from_crt(crt_path)
            fileutil.write_file(pub_path, pub)
            self.set_selinux_context(pub_path,
                                     'unconfined_u:object_r:ssh_home_t:s0')
            self.openssl_to_openssh(pub_path, path)
            fileutil.chmod(pub_path, 0o600)
        else:
            raise OSUtilError("SSH public key Fingerprint and Value are None")

        self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
        fileutil.chowner(path, username)
        fileutil.chmod(path, 0o644)
Example #2
0
 def conf_sudoer(self, username, nopasswd=False, remove=False):
     doas_conf = "/etc/doas.conf"
     doas = None
     if not remove:
         if not os.path.isfile(doas_conf):
             # always allow root to become root
             doas = "permit keepenv nopass root\n"
             fileutil.append_file(doas_conf, doas)
         if nopasswd:
             doas = "permit keepenv nopass {0}\n".format(username)
         else:
             doas = "permit keepenv persist {0}\n".format(username)
         fileutil.append_file(doas_conf, doas)
         fileutil.chmod(doas_conf, 0o644)
     else:
         # Remove user from doas.conf
         if os.path.isfile(doas_conf):
             try:
                 content = fileutil.read_file(doas_conf)
                 doas = content.split("\n")
                 doas = [x for x in doas if username not in x]
                 fileutil.write_file(doas_conf, "\n".join(doas))
             except IOError as err:
                 raise OSUtilError("Failed to remove sudoer: "
                                   "{0}".format(err))
Example #3
0
    def conf_sudoer(self, username, nopasswd=False, remove=False):
        sudoers_dir = conf.get_sudoers_dir()
        sudoers_wagent = os.path.join(sudoers_dir, 'waagent')

        if not remove:
            # for older distros create sudoers.d
            if not os.path.isdir(sudoers_dir):
                sudoers_file = os.path.join(sudoers_dir, '../sudoers')
                # create the sudoers.d directory
                os.mkdir(sudoers_dir)
                # add the include of sudoers.d to the /etc/sudoers
                sudoers = '\n#includedir ' + sudoers_dir + '\n'
                fileutil.append_file(sudoers_file, sudoers)
            sudoer = None
            if nopasswd:
                sudoer = "{0} ALL=(ALL) NOPASSWD: ALL\n".format(username)
            else:
                sudoer = "{0} ALL=(ALL) ALL\n".format(username)
            fileutil.append_file(sudoers_wagent, sudoer)
            fileutil.chmod(sudoers_wagent, 0o440)
        else:
            #Remove user from sudoers
            if os.path.isfile(sudoers_wagent):
                try:
                    content = fileutil.read_file(sudoers_wagent)
                    sudoers = content.split("\n")
                    sudoers = [x for x in sudoers if username not in x]
                    fileutil.write_file(sudoers_wagent, "\n".join(sudoers))
                except IOError as e:
                    raise OSUtilError("Failed to remove sudoer: {0}".format(e))
 def conf_sudoer(self, username, nopasswd=False, remove=False):
     doas_conf = "/etc/doas.conf"
     doas = None
     if not remove:
         if not os.path.isfile(doas_conf):
             # always allow root to become root
             doas = "permit keepenv nopass root\n"
             fileutil.append_file(doas_conf, doas)
         if nopasswd:
             doas = "permit keepenv nopass {0}\n".format(username)
         else:
             doas = "permit keepenv persist {0}\n".format(username)
         fileutil.append_file(doas_conf, doas)
         fileutil.chmod(doas_conf, 0o644)
     else:
         # Remove user from doas.conf
         if os.path.isfile(doas_conf):
             try:
                 content = fileutil.read_file(doas_conf)
                 doas = content.split("\n")
                 doas = [x for x in doas if username not in x]
                 fileutil.write_file(doas_conf, "\n".join(doas))
             except IOError as err:
                 raise OSUtilError("Failed to remove sudoer: "
                                   "{0}".format(err))
Example #5
0
    def deploy_ssh_pubkey(self, username, pubkey):
        """
        Deploy authorized_key
        """
        path, thumbprint, value = pubkey
        if path is None:
            raise OSUtilError("Public key path is None")

        crytputil = CryptUtil(conf.get_openssl_cmd())

        path = self._norm_path(path)
        dir_path = os.path.dirname(path)
        fileutil.mkdir(dir_path, mode=0o700, owner=username)
        if value is not None:
            if not value.startswith("ssh-"):
                raise OSUtilError("Bad public key: {0}".format(value))
            fileutil.write_file(path, value)
        elif thumbprint is not None:
            lib_dir = conf.get_lib_dir()
            crt_path = os.path.join(lib_dir, thumbprint + '.crt')
            if not os.path.isfile(crt_path):
                raise OSUtilError("Can't find {0}.crt".format(thumbprint))
            pub_path = os.path.join(lib_dir, thumbprint + '.pub')
            pub = crytputil.get_pubkey_from_crt(crt_path)
            fileutil.write_file(pub_path, pub)
            self.set_selinux_context(pub_path,
                                     'unconfined_u:object_r:ssh_home_t:s0')
            self.openssl_to_openssh(pub_path, path)
            fileutil.chmod(pub_path, 0o600)
        else:
            raise OSUtilError("SSH public key Fingerprint and Value are None")

        self.set_selinux_context(path, 'unconfined_u:object_r:ssh_home_t:s0')
        fileutil.chowner(path, username)
        fileutil.chmod(path, 0o644)
Example #6
0
    def conf_sudoer(self, username, nopasswd=False, remove=False):
        sudoers_dir = conf.get_sudoers_dir()
        sudoers_wagent = os.path.join(sudoers_dir, 'waagent')

        if not remove:
            # for older distros create sudoers.d
            if not os.path.isdir(sudoers_dir):
                sudoers_file = os.path.join(sudoers_dir, '../sudoers')
                # create the sudoers.d directory
                os.mkdir(sudoers_dir)
                # add the include of sudoers.d to the /etc/sudoers
                sudoers = '\n#includedir ' + sudoers_dir + '\n'
                fileutil.append_file(sudoers_file, sudoers)
            sudoer = None
            if nopasswd:
                sudoer = "{0} ALL=(ALL) NOPASSWD: ALL\n".format(username)
            else:
                sudoer = "{0} ALL=(ALL) ALL\n".format(username)
            fileutil.append_file(sudoers_wagent, sudoer)
            fileutil.chmod(sudoers_wagent, 0o440)
        else:
            #Remove user from sudoers
            if os.path.isfile(sudoers_wagent):
                try:
                    content = fileutil.read_file(sudoers_wagent)
                    sudoers = content.split("\n")
                    sudoers = [x for x in sudoers if username not in x]
                    fileutil.write_file(sudoers_wagent, "\n".join(sudoers))
                except IOError as e:
                    raise OSUtilError("Failed to remove sudoer: {0}".format(e))
    def __set_service_unit_file(self):
        service_unit_file = self.get_service_file_path()
        binary_path = os.path.join(conf.get_lib_dir(), self.BINARY_FILE_NAME)
        try:
            fileutil.write_file(
                service_unit_file,
                self.__SERVICE_FILE_CONTENT.format(binary_path=binary_path,
                                                   py_path=sys.executable,
                                                   version=self._UNIT_VERSION))
            fileutil.chmod(service_unit_file, 0o644)

            # Finally enable the service. This is needed to ensure the service is started on system boot
            cmd = ["systemctl", "enable", self._network_setup_service_name]
            try:
                shellutil.run_command(cmd)
            except CommandError as error:
                msg = ustr(
                    "Unable to enable service: {0}; deleting service file: {1}. Command: {2}, Exit-code: {3}.\nstdout: {4}\nstderr: {5}"
                ).format(self._network_setup_service_name, service_unit_file,
                         ' '.join(cmd), error.returncode, error.stdout,
                         error.stderr)
                raise Exception(msg)

        except Exception:
            self.__remove_file_without_raising(service_unit_file)
            raise
Example #8
0
    def download(self):
        self.logger.info("Download extension package")
        self.set_operation(WALAEventOperation.Download)
        if self.pkg is None:
            raise ExtensionError("No package uri found")
        
        package = None
        for uri in self.pkg.uris:
            try:
                package = self.protocol.download_ext_handler_pkg(uri.uri)
                if package is not None:
                    break
            except Exception as e:
                logger.warn("Error while downloading extension: {0}", e)
        
        if package is None:
            raise ExtensionError("Failed to download extension")

        self.logger.info("Unpack extension package")
        pkg_file = os.path.join(conf.get_lib_dir(),
                                os.path.basename(uri.uri) + ".zip")
        try:
            fileutil.write_file(pkg_file, bytearray(package), asbin=True)
            zipfile.ZipFile(pkg_file).extractall(self.get_base_dir())
        except IOError as e:
            raise ExtensionError(u"Failed to write and unzip plugin", e)

        #Add user execute permission to all files under the base dir
        for file in fileutil.get_all_files(self.get_base_dir()):
            fileutil.chmod(file, os.stat(file).st_mode | stat.S_IXUSR)

        self.report_event(message="Download succeeded")

        self.logger.info("Initialize extension directory")
        #Save HandlerManifest.json
        man_file = fileutil.search_file(self.get_base_dir(),
                                        'HandlerManifest.json')

        if man_file is None:
            raise ExtensionError("HandlerManifest.json not found")
        
        try:
            man = fileutil.read_file(man_file, remove_bom=True)
            fileutil.write_file(self.get_manifest_file(), man)
        except IOError as e:
            raise ExtensionError(u"Failed to save HandlerManifest.json", e)

        #Create status and config dir
        try:
            status_dir = self.get_status_dir()
            fileutil.mkdir(status_dir, mode=0o700)
            conf_dir = self.get_conf_dir()
            fileutil.mkdir(conf_dir, mode=0o700)
        except IOError as e:
            raise ExtensionError(u"Failed to create status or config dir", e)

        #Save HandlerEnvironment.json
        self.create_handler_env()
    def download(self):
        self.logger.verbose("Download extension package")
        self.set_operation(WALAEventOperation.Download)
        if self.pkg is None:
            raise ExtensionError("No package uri found")

        package = None
        for uri in self.pkg.uris:
            try:
                package = self.protocol.download_ext_handler_pkg(uri.uri)
                if package is not None:
                    break
            except Exception as e:
                logger.warn("Error while downloading extension: {0}", e)

        if package is None:
            raise ExtensionError("Failed to download extension")

        self.logger.verbose("Unpack extension package")
        pkg_file = os.path.join(conf.get_lib_dir(),
                                os.path.basename(uri.uri) + ".zip")
        try:
            fileutil.write_file(pkg_file, bytearray(package), asbin=True)
            zipfile.ZipFile(pkg_file).extractall(self.get_base_dir())
        except IOError as e:
            raise ExtensionError(u"Failed to write and unzip plugin", e)

        #Add user execute permission to all files under the base dir
        for file in fileutil.get_all_files(self.get_base_dir()):
            fileutil.chmod(file, os.stat(file).st_mode | stat.S_IXUSR)

        self.report_event(message="Download succeeded")

        self.logger.info("Initialize extension directory")
        #Save HandlerManifest.json
        man_file = fileutil.search_file(self.get_base_dir(),
                                        'HandlerManifest.json')

        if man_file is None:
            raise ExtensionError("HandlerManifest.json not found")

        try:
            man = fileutil.read_file(man_file, remove_bom=True)
            fileutil.write_file(self.get_manifest_file(), man)
        except IOError as e:
            raise ExtensionError(u"Failed to save HandlerManifest.json", e)

        #Create status and config dir
        try:
            status_dir = self.get_status_dir()
            fileutil.mkdir(status_dir, mode=0o700)
            conf_dir = self.get_conf_dir()
            fileutil.mkdir(conf_dir, mode=0o700)
        except IOError as e:
            raise ExtensionError(u"Failed to create status or config dir", e)

        #Save HandlerEnvironment.json
        self.create_handler_env()
Example #10
0
    def download(self):
        begin_utc = datetime.datetime.utcnow()
        self.logger.verbose("Download extension package")
        self.set_operation(WALAEventOperation.Download)
        if self.pkg is None:
            raise ExtensionError("No package uri found")

        package = None
        for uri in self.pkg.uris:
            try:
                package = self.protocol.download_ext_handler_pkg(uri.uri)
                if package is not None:
                    break
            except Exception as e:
                logger.warn("Error while downloading extension: {0}", e)

        if package is None:
            raise ExtensionError("Failed to download extension")

        self.logger.verbose("Unpack extension package")
        self.pkg_file = os.path.join(conf.get_lib_dir(),
                                     os.path.basename(uri.uri) + ".zip")
        try:
            fileutil.write_file(self.pkg_file, bytearray(package), asbin=True)
            zipfile.ZipFile(self.pkg_file).extractall(self.get_base_dir())
        except IOError as e:
            fileutil.clean_ioerror(e,
                                   paths=[self.get_base_dir(), self.pkg_file])
            raise ExtensionError(u"Failed to write and unzip plugin", e)

        #Add user execute permission to all files under the base dir
        for file in fileutil.get_all_files(self.get_base_dir()):
            fileutil.chmod(file, os.stat(file).st_mode | stat.S_IXUSR)

        duration = elapsed_milliseconds(begin_utc)
        self.report_event(message="Download succeeded", duration=duration)

        self.logger.info("Initialize extension directory")
        #Save HandlerManifest.json
        man_file = fileutil.search_file(self.get_base_dir(),
                                        'HandlerManifest.json')

        if man_file is None:
            raise ExtensionError("HandlerManifest.json not found")

        try:
            man = fileutil.read_file(man_file, remove_bom=True)
            fileutil.write_file(self.get_manifest_file(), man)
        except IOError as e:
            fileutil.clean_ioerror(e,
                                   paths=[self.get_base_dir(), self.pkg_file])
            raise ExtensionError(u"Failed to save HandlerManifest.json", e)

        #Create status and config dir
        try:
            status_dir = self.get_status_dir()
            fileutil.mkdir(status_dir, mode=0o700)

            seq_no, status_path = self.get_status_file_path()
            if seq_no > -1:
                now = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
                status = {
                    "version": 1.0,
                    "timestampUTC": now,
                    "status": {
                        "name": self.ext_handler.name,
                        "operation": "Enabling Handler",
                        "status": "transitioning",
                        "code": 0
                    }
                }
                fileutil.write_file(json.dumps(status), status_path)

            conf_dir = self.get_conf_dir()
            fileutil.mkdir(conf_dir, mode=0o700)

        except IOError as e:
            fileutil.clean_ioerror(e,
                                   paths=[self.get_base_dir(), self.pkg_file])
            raise ExtensionError(u"Failed to create status or config dir", e)

        #Save HandlerEnvironment.json
        self.create_handler_env()
Example #11
0
    def download(self):
        begin_utc = datetime.datetime.utcnow()
        self.logger.verbose("Download extension package")
        self.set_operation(WALAEventOperation.Download)

        if self.pkg is None:
            raise ExtensionError("No package uri found")
        
        uris_shuffled = self.pkg.uris
        random.shuffle(uris_shuffled)
        file_downloaded = False

        for uri in uris_shuffled:
            try:
                destination = os.path.join(conf.get_lib_dir(), os.path.basename(uri.uri) + ".zip")
                file_downloaded = self.protocol.download_ext_handler_pkg(uri.uri, destination)

                if file_downloaded and os.path.exists(destination):
                    self.pkg_file = destination
                    break

            except Exception as e:
                logger.warn("Error while downloading extension: {0}", ustr(e))
        
        if not file_downloaded:
            raise ExtensionError("Failed to download extension", code=1001)

        self.logger.verbose("Unzip extension package")
        try:
            zipfile.ZipFile(self.pkg_file).extractall(self.get_base_dir())
            os.remove(self.pkg_file)
        except IOError as e:
            fileutil.clean_ioerror(e, paths=[self.get_base_dir(), self.pkg_file])
            raise ExtensionError(u"Failed to unzip extension package", e, code=1001)

        # Add user execute permission to all files under the base dir
        for file in fileutil.get_all_files(self.get_base_dir()):
            fileutil.chmod(file, os.stat(file).st_mode | stat.S_IXUSR)

        duration = elapsed_milliseconds(begin_utc)
        self.report_event(message="Download succeeded", duration=duration)

        self.logger.info("Initialize extension directory")
        # Save HandlerManifest.json
        man_file = fileutil.search_file(self.get_base_dir(), 'HandlerManifest.json')

        if man_file is None:
            raise ExtensionError("HandlerManifest.json not found")
        
        try:
            man = fileutil.read_file(man_file, remove_bom=True)
            fileutil.write_file(self.get_manifest_file(), man)
        except IOError as e:
            fileutil.clean_ioerror(e, paths=[self.get_base_dir(), self.pkg_file])
            raise ExtensionError(u"Failed to save HandlerManifest.json", e)

        # Create status and config dir
        try:
            status_dir = self.get_status_dir()
            fileutil.mkdir(status_dir, mode=0o700)

            seq_no, status_path = self.get_status_file_path()
            if status_path is not None:
                now = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
                status = {
                    "version": 1.0,
                    "timestampUTC": now,
                    "status": {
                        "name": self.ext_handler.name,
                        "operation": "Enabling Handler",
                        "status": "transitioning",
                        "code": 0
                    }
                }
                fileutil.write_file(status_path, json.dumps(status))

            conf_dir = self.get_conf_dir()
            fileutil.mkdir(conf_dir, mode=0o700)

        except IOError as e:
            fileutil.clean_ioerror(e, paths=[self.get_base_dir(), self.pkg_file])
            raise ExtensionError(u"Failed to create status or config dir", e)

        # Save HandlerEnvironment.json
        self.create_handler_env()