Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Read signature of .ps1 file with CLI on Linux

If you wish to read the PKCS7-encoded signature on a powershell script, and you don't have osslsigncode verify available to you (from https://github.com/mtrojnar/osslsigncode), you can use this script.

files/2024/listings/read-signature.sh (Source)

#!/usr/bin/env sh
# File: read-signature.sh
# Location: blog
# Author: bgstack15
# SPDX-License-Identifier: GPL-3.0-only
# Startdate: 2024-08-08-5 14:35
# Title: Read Signature
# Purpose: Read codesign signature on a powershell script on Unix-like cli
# History:
# Usage:
# Reference:
# Improve:
# Dependencies:
#    openssl, gsed, gawk, posix shell
# Documentation:
#    Skipping SAN; tends to not be used on codesigning certs?
command -v sed 1>/dev/null 2>&1 && SED=sed
command -v gsed 1>/dev/null 2>&1 && SED=gsed
command -v awk 1>/dev/null 2>&1 && AWK=awk
command -v gawk 1>/dev/null 2>&1 && AWK=gawk
read_sig() {
   _in="${INFILE:-${1}}"
   _in="${_in:-/dev/stdin}"
   test "${_in}" = "-" && _in="/dev/stdin"
   _contents="$(
      printf '%s\n' '-----BEGIN PKCS7-----'
      <"${_in}" "${SED}" -r -n '/^# SIG # Begin/,/^# SIG # End/{s/^\# //;p;}' | tr -d '\r' | grep -v -e 'signature block'
      printf '%s\n' '-----END PKCS7-----'
   )"
   # would need to parse SANs here if any.
   echo "${_contents}" | openssl pkcs7 -in /dev/stdin -print_certs | openssl x509 -in /dev/stdin -noout -subject -issuer -serial -email -dates
   # Print date
   echo "${_contents}" | openssl pkcs7 -in /dev/stdin -print -noout | "${AWK}" '/signingTime/{getline;getline;gsub(":","",$NF);print $NF}' | "${SED}" -r -e 's/^(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})/timestamp=20\1-\2-\3T\4:\5:\6/;'
}

Notice how I make sure we find GNU sed and awk, because the old BSD ones use a different syntax that are not worth learning. Just use real sed and awk.

Comments