Skip to content

Instantly share code, notes, and snippets.

@russau
Last active January 13, 2022 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save russau/c0123ef934ef88808050462a8638a410 to your computer and use it in GitHub Desktop.
Save russau/c0123ef934ef88808050462a8638a410 to your computer and use it in GitHub Desktop.
Verify EC2 PKCS7 Signature in Python
-----BEGIN CERTIFICATE-----
MIIC7TCCAq0CCQCWukjZ5V4aZzAJBgcqhkjOOAQDMFwxCzAJBgNVBAYTAlVTMRkw
FwYDVQQIExBXYXNoaW5ndG9uIFN0YXRlMRAwDgYDVQQHEwdTZWF0dGxlMSAwHgYD
VQQKExdBbWF6b24gV2ViIFNlcnZpY2VzIExMQzAeFw0xMjAxMDUxMjU2MTJaFw0z
ODAxMDUxMjU2MTJaMFwxCzAJBgNVBAYTAlVTMRkwFwYDVQQIExBXYXNoaW5ndG9u
IFN0YXRlMRAwDgYDVQQHEwdTZWF0dGxlMSAwHgYDVQQKExdBbWF6b24gV2ViIFNl
cnZpY2VzIExMQzCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQCjkvcS2bb1VQ4yt/5e
ih5OO6kK/n1Lzllr7D8ZwtQP8fOEpp5E2ng+D6Ud1Z1gYipr58Kj3nssSNpI6bX3
VyIQzK7wLclnd/YozqNNmgIyZecN7EglK9ITHJLP+x8FtUpt3QbyYXJdmVMegN6P
hviYt5JH/nYl4hh3Pa1HJdskgQIVALVJ3ER11+Ko4tP6nwvHwh6+ERYRAoGBAI1j
k+tkqMVHuAFcvAGKocTgsjJem6/5qomzJuKDmbJNu9Qxw3rAotXau8Qe+MBcJl/U
hhy1KHVpCGl9fueQ2s6IL0CaO/buycU1CiYQk40KNHCcHfNiZbdlx1E9rpUp7bnF
lRa2v1ntMX3caRVDdbtPEWmdxSCYsYFDk4mZrOLBA4GEAAKBgEbmeve5f8LIE/Gf
MNmP9CM5eovQOGx5ho8WqD+aTebs+k2tn92BBPqeZqpWRa5P/+jrdKml1qx4llHW
MXrs3IgIb6+hUIB+S8dz8/mmO0bpr76RoZVCXYab2CZedFut7qc3WUH9+EUAH5mw
vSeDCOUMYQR7R9LINYwouHIziqQYMAkGByqGSM44BAMDLwAwLAIUWXBlk40xTwSw
7HX32MxXYruse9ACFBNGmdX2ZBrVNGrN9N2f6ROk0k9K
-----END CERTIFICATE-----
# https://stackoverflow.com/a/60840416/109102
sudo apt-get install build-essential libssl-dev swig python3-dev
pip3 install M2Crypto
# Thanks to:
# https://darthnull.org/security/2012/02/21/verifying-a-detatched-smime-signature-in-python/
# https://tools.ietf.org/doc/python-m2crypto/howto.smime.html#VERIFY
from M2Crypto import SMIME, X509, BIO
import requests
# Instantiate an SMIME object
s = SMIME.SMIME()
# Load the signer's cert.
# certificate from https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/verify-pkcs7.html
x509 = X509.load_cert('certificate')
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)
# Load the signer's CA cert. In this case, because the signer's
# cert is self-signed, it is the signer's cert itself.
st = X509.X509_Store()
st.load_info('certificate')
s.set_x509_store(st)
# Load the data, verify it.
r = requests.get("http://169.254.169.254/latest/dynamic/instance-identity/pkcs7")
pkcs7 = """-----BEGIN PKCS7-----
%s
-----END PKCS7-----""" % r.text
buf = BIO.MemoryBuffer(pkcs7.encode())
p7 = SMIME.load_pkcs7_bio(buf)
v = s.verify(p7)
print(v.decode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment