Exemple #1
0
 def Run(self):
     remove_existing = False
     try:
         src = self._args[0]
         dst = self._args[1]
         if len(self._args) > 2:
             remove_existing = self._args[2]
     except IndexError:
         raise ActionError(
             'Unable to determine source and destination from %s.' %
             str(self._args))
     try:
         if os.path.exists(dst) and remove_existing:
             logging.info('Deleting existing destination: %s', dst)
             shutil.rmtree(dst)
     except (shutil.Error, OSError) as e:
         raise ActionError(
             'Unable to delete existing destination folder %s: %s' %
             (dst, str(e)))
     try:
         logging.info('Copying directory: %s to %s', src, dst)
         shutil.copytree(src, dst)
     except (shutil.Error, OSError) as e:
         raise ActionError('Unable to copy %s to %s: %s' %
                           (src, dst, str(e)))
Exemple #2
0
  def _Run(self, command: Text, success_codes: List[int],
           reboot_codes: List[int], restart_retry: bool, shell: bool):
    logging.debug('Interpreting command: %s', command)
    try:
      command_cache = cache.Cache().CacheFromLine(command, self._build_info)
    except cache.CacheError as e:
      raise ActionError(e)

    try:
      command_list = shlex.split(command_cache, posix=False)
      result = execute.execute_binary(
          command_list[0],
          command_list[1:],
          success_codes + reboot_codes,
          shell=shell)
    except (execute.Error, ValueError) as e:
      raise ActionError(e)
    except KeyboardInterrupt:
      raise ActionError('KeyboardInterrupt detected, exiting.')

    if result in reboot_codes:
      raise RestartEvent(
          'Restart triggered by exit code: %d' % result,
          5,
          retry_on_restart=restart_retry)
    elif result not in success_codes:
      raise ActionError('Command returned invalid exit code: %d' % result)
Exemple #3
0
 def Run(self):
   downloader = download.Download()
   for arg in self._args:
     src = arg[0]
     dst = arg[1]
     full_url = download.Transform(src, self._build_info)
     # support legacy untagged short filenames
     if not (download.IsRemote(full_url) or download.IsLocal(full_url)):
       full_url = download.PathCompile(self._build_info, file_name=full_url)
     try:
       file_util.CreateDirectories(dst)
     except file_util.Error as e:
       raise ActionError('Could not create destination directory %s. %s' %
                         (dst, e))
     try:
       downloader.DownloadFile(full_url, dst, show_progress=True)
     except download.DownloadError as e:
       downloader.PrintDebugInfo()
       raise ActionError('Transfer error while downloading %s: %s' %
                         (full_url, str(e)))
     if len(arg) > 2 and arg[2]:
       logging.info('Verifying SHA256 hash for %s.', dst)
       hash_ok = downloader.VerifyShaHash(dst, arg[2])
       if not hash_ok:
         raise ActionError('SHA256 hash for %s was incorrect.' % dst)
Exemple #4
0
  def _Run(self, command, success_codes, reboot_codes, restart_retry):
    c = cache.Cache()
    logging.debug('Interpreting command %s', command)
    try:
      command = c.CacheFromLine(command, self._build_info)
    except cache.CacheError as e:
      raise ActionError(e)
    logging.info('Executing command %s', command)
    try:
      result = subprocess.Popen(command,
                                shell=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
      while True:
        output = result.stdout.readline()
        if not output and result.poll() is not None:
          break
        if output:
          logging.info(output.strip().decode('UTF-8'))

    except WindowsError as e:  # pylint: disable=undefined-variable
      raise ActionError('Failed to execute command %s (%s)' % (command, str(e)))
    except KeyboardInterrupt:
      logging.debug('Child received KeyboardInterrupt. Ignoring.')

    if result.returncode in reboot_codes:
      raise RestartEvent(
          'Restart triggered by exit code %d' % result.returncode,
          5,
          retry_on_restart=restart_retry)
    elif result.returncode not in success_codes:
      raise ActionError('Command returned invalid exit code %d' %
                        result.returncode)
    time.sleep(5)
Exemple #5
0
 def Run(self):
     try:
         path = self._args[0]
     except IndexError:
         raise ActionError('Unable to determine desired path from %s.' %
                           str(self._args))
     try:
         file_util.CreateDirectories(path)
     except file_util.Error as e:
         raise ActionError(e)
Exemple #6
0
 def Run(self):
   try:
     src = self._args[0]
     dst = self._args[1]
   except IndexError:
     raise ActionError('Unable to determine source and destination from %s.' %
                       str(self._args))
   try:
     file_util.Copy(src, dst)
   except (file_util.Error) as e:
     raise ActionError(str(e))
Exemple #7
0
 def Run(self):
   try:
     src = self._args[0]
     dst = self._args[1]
   except IndexError:
     raise ActionError('Unable to determine source and destination from %s.' %
                       str(self._args))
   try:
     path = os.path.dirname(dst)
     self._CreateDirectories(path)
     shutil.copy2(src, dst)
     logging.info('Copying: %s to %s', src, dst)
   except (shutil.Error, IOError) as e:
     raise ActionError('Unable to copy %s to %s: %s' % (src, dst, str(e)))
Exemple #8
0
  def Run(self):
    use_64bit = True

    if len(self._args) > 3:
      use_64bit = self._args[3]

    try:
      registry.remove_value(self._args[2], self._args[0],
                            self._args[1], use_64bit=use_64bit)
    except registry.Error as e:
      raise ActionError(str(e))
    except IndexError:
      raise ActionError(
          'Unable to access all required arguments. [%s]' % str(self._args))
Exemple #9
0
  def Run(self):

    use_64bit = constants.USE_REG_64
    if len(self._args) > 5:
      use_64bit = self._args[5]

    try:
      registry.set_value(self._args[2], self._args[3],
                         self._args[0], self._args[1],
                         self._args[4], use_64bit=use_64bit)
    except registry.Error as e:
      raise ActionError(str(e))
    except IndexError:
      raise ActionError('Unable to access all required arguments. [%s]' %
                        str(self._args))
Exemple #10
0
    def _ProcessMsu(self, msu_file):
        """Command used to process updates downloaded.

    This command will apply updates to an image.

    If the exit code for the parsed command is anything other than zero, report
    fatal error.

    Args:
      msu_file: current file location.

    Raises:
      ActionError: Error during update application.
    """

        scratch_dir = '%s\\Updates\\' % constants.SYS_CACHE

        # create scratch directory
        file_util.CreateDirectories(scratch_dir)

        # dism commands
        update = [
            '{} /image:c:\\ /Add-Package /PackagePath:{} /ScratchDir:{}'.
            format(constants.WINPE_DISM, msu_file, scratch_dir)
        ]

        logging.info('Applying %s image to main disk.', msu_file)

        # Apply updates to  image
        ex = Execute([update], self._build_info)
        try:
            ex.Run()
        except ActionError as e:
            raise ActionError('Unable to process update %s. (%s)' %
                              (msu_file, e))
Exemple #11
0
 def Run(self):
   for path in self._args:
     logging.info('Removing directory: %s', path)
     try:
       shutil.rmtree(path)
     except (shutil.Error, OSError) as e:
       raise ActionError('Unable to remove directory %s: %s' % (path, str(e)))
Exemple #12
0
    def _AddDriver(self, mount_dir):
        """Command used to process drivers in a given directory.

    This command will process all fo the .inf file in a folder recursively. It
    can be used regardless of how the drivers are added to the local machine.

    If the exit code for the parsed command is anything other than zero, report
    fatal error.

    Args:
      mount_dir: local directory where the driver .inf files can be found.

    Raises:
      ConfigRunnerError: Error during driver application.
    """
        dism = [
            '{} /Image:c: /Add-Driver /Driver:{} /Recurse'.format(
                constants.WINPE_DISM, mount_dir)
        ]
        ex = Execute([dism], self._build_info)
        try:
            ex.Run()
        except ActionError as e:
            raise ActionError('Error applying drivers to image from %s. (%s)' %
                              (mount_dir, e))
Exemple #13
0
 def Run(self):
     mode = str(self._args[0])
     try:
         bl = bitlocker.Bitlocker(mode)
         bl.Enable()
     except bitlocker.BitlockerError as e:
         raise ActionError('Failure enabling Bitlocker. (%s)' % str(e))
Exemple #14
0
 def Validate(self):
     try:
         self._TypeValidator(self._args, list)
     except ValidationError as e:
         raise ActionError(e)
     for arg in self._args:
         PSCommand(arg, self._build_info).Validate()
Exemple #15
0
    def _ProcessMsu(self, msu_file):
        """Command used to process updates downloaded.

    This command will apply updates to an image.

    If the exit code for the parsed command is anything other than zero, report
    fatal error.

    Args:
      msu_file: current file location.

    Raises:
      ActionError: Error during update application.
    """

        scratch_dir = '%s\\Updates\\' % constants.SYS_CACHE

        # create scratch directory
        file_util.CreateDirectories(scratch_dir)

        logging.info('Applying %s image to main disk.', msu_file)

        # Apply updates to  image
        try:
            execute.execute_binary(constants.WINPE_DISM, [
                '/image:c:\\', '/Add-Package'
                f'/PackagePath:{msu_file}'
                f'/ScratchDir:{scratch_dir}'
            ],
                                   shell=True)
        except execute.Error as e:
            raise ActionError('Failed to process update %s: %s' %
                              (msu_file, e))
Exemple #16
0
 def Run(self):
     for arg in self._args:
         try:
             PSScript(arg, self._build_info).Run()
         except IndexError:
             raise ActionError(
                 f'Unable to determine PowerShell scripts from {arg}')
Exemple #17
0
 def Run(self):
   try:
     path = self._args[0]
   except IndexError:
     raise ActionError('Unable to determine desired path from %s.' %
                       str(self._args))
   self._CreateDirectories(path)
Exemple #18
0
    def Run(self):
        command: List[str] = self._args[0].split()
        success_codes: List[int] = [0]
        reboot_codes: List[int] = []
        restart_retry: bool = False
        shell: bool = False
        log: bool = True
        if len(self._args) > 1:
            success_codes = self._args[1]
        if len(self._args) > 2:
            reboot_codes = self._args[2]
        if len(self._args) > 3:
            restart_retry = self._args[3]
        if len(self._args) > 4:
            shell = self._args[4]
        if len(self._args) > 5:
            log = self._args[5]

        # TODO: Remove once updated PowerShell is used in the image.
        # PSScript (which calls powershell.exe -File) does not accept non-string
        # parameters. Instead, if the command string starts with a PowerShell
        # script, cache it's location and run the script using powershell.exe
        # -Command. See link below for more context.
        # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-file----filepath-args
        if command[0] and command[0].endswith('.ps1'):
            logging.info('Interpreting PowerShell script: %s', command[0])
            try:
                command[0] = cache.Cache().CacheFromLine(
                    command[0], self._build_info)
            except cache.CacheError as e:
                raise ActionError(e)

        try:
            # Exit $LASTEXITCODE is necessary because PowerShell.exe -Command only
            # exits 0 or 1 by default.
            result = powershell.PowerShell(shell, log).RunCommand(
                command + ['; exit $LASTEXITCODE'],
                success_codes + reboot_codes)
        except powershell.PowerShellError as e:
            raise ActionError(str(e))

        if result in reboot_codes:
            raise RestartEvent('Restart triggered by exit code %d' % result,
                               5,
                               retry_on_restart=restart_retry)
        elif result not in success_codes:
            raise ActionError('Command returned invalid exit code %d' % result)
Exemple #19
0
 def Run(self):
     try:
         for arg in self._args:
             cf = CopyFile([arg[0], arg[1]], self._build_info)
             cf.Run()
     except IndexError:
         raise ActionError('Unable to determine copy sets from %s.' %
                           str(self._args))
Exemple #20
0
 def Run(self):
     try:
         for arg in self._args:
             ra = RegAdd(arg, self._build_info)
             ra.Run()
     except IndexError:
         raise ActionError('Unable to determine registry sets from %s.' %
                           str(self._args))
Exemple #21
0
 def Run(self):
   try:
     stage.set_stage(int(self._args[0]))
     # Terminal stages exit immediately; the build should be complete.
     if len(self._args) > 1 and self._args[1]:
       stage.exit_stage(int(self._args[0]))
   except stage.Error as e:
     raise ActionError(str(e))
Exemple #22
0
    def Run(self):
        script = self._args[0]
        ps_args = None
        if len(self._args) > 1:
            ps_args = self._args[1]
        ps = powershell.PowerShell(echo_off=True)
        c = cache.Cache()

        logging.debug('Interpreting Powershell script %s', script)
        try:
            script = c.CacheFromLine(script, self._build_info)
        except cache.CacheError as e:
            raise ActionError(e)

        try:
            ps.RunLocal(script, args=ps_args)
        except powershell.PowerShellError as e:
            raise ActionError('Failure executing Powershell script. [%s]' % e)
Exemple #23
0
  def Run(self):
    try:
      zip_file = self._args[0]
      out_path = self._args[1]
    except IndexError:
      raise ActionError('Unable to determine desired paths from %s.' %
                        str(self._args))

    try:
      file_util.CreateDirectories(out_path)
    except file_util.Error:
      raise ActionError('Unable to create output path %s.' % out_path)

    try:
      zf = zipfile.ZipFile(zip_file)
      zf.extractall(out_path)
    except (IOError, zipfile.BadZipfile) as e:
      raise ActionError('Bad zip file given as input.  %s' % e)
Exemple #24
0
    def Run(self):
        use_64bit = True

        if len(self._args) > 5:
            use_64bit = self._args[5]

        try:
            logging.info('Setting registry key: %s', self._args)
            reg = registry.Registry(root_key=self._args[0])
            reg.SetKeyValue(key_path=self._args[1],
                            key_name=self._args[2],
                            key_value=self._args[3],
                            key_type=self._args[4],
                            use_64bit=use_64bit)
        except registry.RegistryError as e:
            raise ActionError(str(e))
        except IndexError:
            raise ActionError('Unable to access all required arguments. [%s]' %
                              str(self._args))
Exemple #25
0
    def _ProcessWim(self, wim_file):
        """Processes WIM driver files using DISM commands.

    Runs necessary commands to process a driver file in WIM format

    Args:
      wim_file: current file location.

    Raises:
      ConfigRunnerError: Failure mounting or unmounting WIM.
    """
        mount_dir = '%s\\Drivers\\' % constants.SYS_CACHE

        # dism commands
        mount = [
            '{} /Mount-Image /ImageFile:{} /MountDir:{} /ReadOnly /Index:1'.
            format(constants.WINPE_DISM, wim_file, mount_dir)
        ]
        unmount = [
            '{} /Unmount-Image /MountDir:{} /Discard'.format(
                constants.WINPE_DISM, mount_dir)
        ]

        # create mount directory
        file_util.CreateDirectories(mount_dir)

        # mount image
        ex = Execute([mount], self._build_info)
        try:
            ex.Run()
        except ActionError as e:
            raise ActionError('Unable to mount image %s. (%s)' % (wim_file, e))

        logging.info('Applying %s image to main disk.', wim_file)
        self._AddDriver(mount_dir)

        # Unmount after running
        ex = Execute([unmount], self._build_info)
        try:
            ex.Run()
        except ActionError as e:
            raise ActionError(
                'Error unmounting image. Unable to continue. (%s)' % e)
Exemple #26
0
    def Run(self):
        use_64bit = True

        if len(self._args) > 3:
            use_64bit = self._args[3]

        try:
            logging.info('Attempting to delete registry key: %s', self._args)
            reg = registry.Registry(root_key=self._args[0])
            reg.RemoveKeyValue(key_path=self._args[1],
                               key_name=self._args[2],
                               use_64bit=use_64bit)
        except registry.RegistryError as e:
            if e.errno == 2:
                logging.warn('Registry key %s not found', self._args)
            else:
                raise ActionError(str(e))
        except IndexError:
            raise ActionError('Unable to access all required arguments. [%s]' %
                              str(self._args))
Exemple #27
0
 def Run(self):
     method = str(self._args[0])
     domain = str(self._args[1])
     ou = None
     if len(self._args) > 2:
         ou = str(self._args[2])
     joiner = domain_join.DomainJoin(method, domain, ou)
     try:
         joiner.JoinDomain()
     except domain_join.DomainJoinError as e:
         raise ActionError('Unable to complete domain join.  %s' % str(e))
Exemple #28
0
    def Run(self):
        for wim in self._args:
            dst = str(wim[1])
            file_ext = os.path.splitext(dst)[1]

            if file_ext not in self.FILE_EXT_SUPPORTED:
                raise ActionError('Unsupported driver file format %s.' % dst)

            g = Get([wim], self._build_info)
            g.Run()

            logging.info('Found WIM file, processing drivers using DISM.')
            self._ProcessWim(dst)
Exemple #29
0
    def Run(self):
        for msu in self._args:
            dst = str(msu[1])
            file_ext = os.path.splitext(dst)[1]

            if file_ext not in self.FILE_EXT_SUPPORTED:
                raise ActionError('Unsupported update file format %s.' % dst)

            g = Get([msu], self._build_info)
            g.Run()

            logging.info('Found MSU file, processing update using DISM.')
            self._ProcessMsu(dst)
Exemple #30
0
    def Run(self):
        script: str = self._args[0]
        ps_args: List[str] = []
        success_codes: List[int] = [0]
        reboot_codes: List[int] = []
        restart_retry: bool = False
        shell: bool = False
        log: bool = True
        if len(self._args) > 1:
            ps_args = self._args[1]
        if len(self._args) > 2:
            success_codes = self._args[2]
        if len(self._args) > 3:
            reboot_codes = self._args[3]
        if len(self._args) > 4:
            restart_retry = self._args[4]
        if len(self._args) > 5:
            shell = self._args[5]
        if len(self._args) > 6:
            log = self._args[6]

        logging.info('Interpreting PowerShell script: %s', script)
        try:
            script = cache.Cache().CacheFromLine(script, self._build_info)  # pytype: disable=annotation-type-mismatch
        except cache.CacheError as e:
            raise ActionError(e)

        try:
            result = powershell.PowerShell(shell, log).RunLocal(
                script, ps_args, success_codes + reboot_codes)
        except powershell.PowerShellError as e:
            raise ActionError(str(e))

        if result in reboot_codes:
            raise RestartEvent('Restart triggered by exit code %d' % result,
                               5,
                               retry_on_restart=restart_retry)
        elif result not in success_codes:
            raise ActionError('Script returned invalid exit code %d' % result)