2015-06-14 14:01:28 -04:00
|
|
|
package powershell
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
2016-07-24 09:44:07 -04:00
|
|
|
"encoding/binary"
|
|
|
|
"unicode/utf16"
|
|
|
|
"unicode/utf8"
|
2016-07-12 19:28:14 -04:00
|
|
|
|
|
|
|
"golang.org/x/text/encoding/unicode"
|
2015-06-14 14:01:28 -04:00
|
|
|
)
|
|
|
|
|
2016-07-24 09:44:07 -04:00
|
|
|
func convertUtf8ToUtf16LE(message string) (string, error) {
|
|
|
|
utf16le := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
|
|
|
|
utfEncoder := utf16le.NewEncoder()
|
|
|
|
ut16LeEncodedMessage, err := utfEncoder.String(message)
|
2016-07-12 19:28:14 -04:00
|
|
|
|
2016-07-24 09:44:07 -04:00
|
|
|
return ut16LeEncodedMessage, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// UTF16BytesToString converts UTF-16 encoded bytes, in big or little endian byte order,
|
|
|
|
// to a UTF-8 encoded string.
|
|
|
|
func UTF16BytesToString(b []byte, o binary.ByteOrder) string {
|
|
|
|
utf := make([]uint16, (len(b)+(2-1))/2)
|
|
|
|
for i := 0; i+(2-1) < len(b); i += 2 {
|
|
|
|
utf[i/2] = o.Uint16(b[i:])
|
|
|
|
}
|
|
|
|
if len(b)/2 < len(utf) {
|
|
|
|
utf[len(utf)-1] = utf8.RuneError
|
|
|
|
}
|
|
|
|
return string(utf16.Decode(utf))
|
2016-07-12 19:28:14 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func powershellEncode(message string) (string, error) {
|
2016-07-24 09:44:07 -04:00
|
|
|
utf16LEEncodedMessage, err := convertUtf8ToUtf16LE(message)
|
2016-07-12 19:28:14 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Base64 encode the command
|
2016-07-24 09:44:07 -04:00
|
|
|
input := []uint8(utf16LEEncodedMessage)
|
2016-07-12 19:28:14 -04:00
|
|
|
return base64.StdEncoding.EncodeToString(input), nil
|
2015-06-14 14:01:28 -04:00
|
|
|
}
|
2016-07-04 18:44:33 -04:00
|
|
|
|
2016-07-24 09:44:07 -04:00
|
|
|
func powershellDecode(messageBase64 string) (retour string, err error) {
|
|
|
|
messageUtf16LeByteArray, err := base64.StdEncoding.DecodeString(messageBase64)
|
|
|
|
|
2016-07-12 19:28:14 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2016-07-24 09:44:07 -04:00
|
|
|
|
|
|
|
message := UTF16BytesToString(messageUtf16LeByteArray, binary.LittleEndian)
|
|
|
|
|
|
|
|
return message, nil
|
2016-07-04 18:44:33 -04:00
|
|
|
}
|