go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/resources/powershell/encode.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package powershell
     5  
     6  import (
     7  	"encoding/base64"
     8  	"fmt"
     9  
    10  	"github.com/rs/zerolog/log"
    11  	"golang.org/x/text/encoding/unicode"
    12  )
    13  
    14  // Encode encodes a long powershell script as base64 and returns the wrapped command
    15  //
    16  // wraps a script to deactivate progress listener
    17  // https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7
    18  //
    19  // deactivates loading powershell profile
    20  // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/powershell
    21  func Encode(cmd string) string {
    22  	// avoid messages to stderr that are not required in our execution
    23  	script := "$ProgressPreference='SilentlyContinue';" + cmd
    24  
    25  	encodedScript, err := ToBase64String(script)
    26  	if err != nil {
    27  		// Ignore this for now to keep the method interface identical
    28  		// lets see if this becomes an issue
    29  		log.Error().Err(err).Msg("could not encode powershell command")
    30  	}
    31  
    32  	return fmt.Sprintf("powershell.exe -NoProfile -EncodedCommand %s", encodedScript)
    33  }
    34  
    35  // ToBase64String encodes a powershell script to a UTF16-LE, base64 encoded string
    36  // The encoded command can be used with powershell.exe -EncodedCommand
    37  //
    38  // $text = Get-Content .\script.ps1 -Raw;
    39  // $encodedScript = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($text));
    40  // $encodedScript;
    41  func ToBase64String(script string) (string, error) {
    42  	uni := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
    43  	encoded, err := uni.NewEncoder().String(script)
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  	return base64.StdEncoding.EncodeToString([]byte(encoded)), nil
    48  }
    49  
    50  func Wrap(cmd string) string {
    51  	return fmt.Sprintf("powershell -c \"%s\"", cmd)
    52  }