this is my quickfix branch and i will use to do my quickfixes

This commit is contained in:
2025-05-14 15:00:45 -04:00
parent bcd0c19ead
commit 0ff36d6890
7 changed files with 98 additions and 255 deletions

View File

@@ -39,7 +39,6 @@ import (
"errors"
"fmt"
"io"
"log"
"os"
"runtime"
"strconv"
@@ -47,13 +46,12 @@ import (
"unsafe"
"github.com/miekg/pkcs11"
pkcs11uri "github.com/stefanberger/go-pkcs11uri"
"github.com/stefanberger/go-pkcs11uri"
)
var PKCS11_TEST_VERSION int16 = 1
var MAX_OBJECT_LIMIT int = 1000
var Pkcs11TestVersion int16 = 1
var MaxObjectLimit int = 1000
// In our list of certs, we want to remember the CKA_ID/CKA_LABEL too.
type CertObjInfo struct {
id []byte
label []byte
@@ -61,14 +59,12 @@ type CertObjInfo struct {
certObject pkcs11.ObjectHandle
}
// In our list of keys, we want to remember the CKA_ID/CKA_LABEL too.
type KeyObjInfo struct {
id []byte
label []byte
keyObject pkcs11.ObjectHandle
}
// Used to enumerate slots with all token/slot info for matching.
type SlotIdInfo struct {
id uint
info pkcs11.SlotInfo
@@ -114,7 +110,7 @@ func initializePKCS11Module(lib string) (module *pkcs11.Ctx, err error) {
fail:
if module != nil {
module.Finalize()
_ = module.Finalize()
module.Destroy()
}
return nil, err
@@ -137,18 +133,10 @@ func enumerateSlotsInPKCS11Module(module *pkcs11.Ctx) (slots []SlotIdInfo, err e
slotIdInfo.id = slotId
slotIdInfo.info, slotErr = module.GetSlotInfo(slotId)
if slotErr != nil {
if Debug {
log.Printf("unable to get slot info for slot %d"+
" (%s)\n", slotId, slotErr)
}
continue
}
slotIdInfo.tokInfo, slotErr = module.GetTokenInfo(slotId)
if slotErr != nil {
if Debug {
log.Printf("unable to get token info for slot %d"+
" (%s)\n", slotId, slotErr)
}
continue
}
@@ -230,7 +218,7 @@ func getFindTemplate(uri *pkcs11uri.Pkcs11URI, class uint) (template []*pkcs11.A
// Gets certificate(s) within the PKCS#11 session (i.e. a given token) that
// matches the given URI.
func getCertsInSession(module *pkcs11.Ctx, slotId uint, session pkcs11.SessionHandle, uri *pkcs11uri.Pkcs11URI) (certs []CertObjInfo, err error) {
func getCertsInSession(module *pkcs11.Ctx, _ uint, session pkcs11.SessionHandle, uri *pkcs11uri.Pkcs11URI) (certs []CertObjInfo, err error) {
var (
sessionCertObjects []pkcs11.ObjectHandle
certObjects []pkcs11.ObjectHandle
@@ -245,7 +233,7 @@ func getCertsInSession(module *pkcs11.Ctx, slotId uint, session pkcs11.SessionHa
}
for true {
sessionCertObjects, _, err = module.FindObjects(session, MAX_OBJECT_LIMIT)
sessionCertObjects, _, err = module.FindObjects(session, MaxObjectLimit)
if err != nil {
return nil, err
}
@@ -253,7 +241,7 @@ func getCertsInSession(module *pkcs11.Ctx, slotId uint, session pkcs11.SessionHa
break
}
certObjects = append(certObjects, sessionCertObjects...)
if len(sessionCertObjects) < MAX_OBJECT_LIMIT {
if len(sessionCertObjects) < MaxObjectLimit {
break
}
}
@@ -335,11 +323,7 @@ func getMatchingCerts(module *pkcs11.Ctx, slots []SlotIdInfo, uri *pkcs11uri.Pkc
for _, slot := range slots {
curSession, err := module.OpenSession(slot.id, pkcs11.CKF_SERIAL_SESSION|pkcs11.CKS_RO_PUBLIC_SESSION)
if err != nil {
if Debug {
log.Printf("unable to open session in slot %d"+
" (%s)\n", slot.id, err)
}
module.CloseSession(curSession)
_ = module.CloseSession(curSession)
continue
}
@@ -354,7 +338,7 @@ func getMatchingCerts(module *pkcs11.Ctx, slots []SlotIdInfo, uri *pkcs11uri.Pkc
goto skipCloseSession
}
}
module.CloseSession(curSession)
_ = module.CloseSession(curSession)
skipCloseSession:
}
@@ -422,86 +406,12 @@ foundCert:
fail:
if session != 0 {
module.Logout(session)
module.CloseSession(session)
_ = module.Logout(session)
_ = module.CloseSession(session)
}
return SlotIdInfo{}, session, false, nil, err
}
// Used to implement a cut-down version of `p11tool --list-certificates`.
func GetMatchingPKCSCerts(uriStr string, lib string) (matchingCerts []CertificateContainer, err error) {
var (
slots []SlotIdInfo
module *pkcs11.Ctx
uri *pkcs11uri.Pkcs11URI
userPin string
certObjs []CertObjInfo
session pkcs11.SessionHandle
loggedIn bool
slot SlotIdInfo
)
uri = pkcs11uri.New()
err = uri.Parse(uriStr)
if err != nil {
return nil, err
}
userPin, _ = uri.GetQueryAttribute("pin-value", false)
module, err = initializePKCS11Module(lib)
if err != nil {
goto cleanUp
}
slots, err = enumerateSlotsInPKCS11Module(module)
if err != nil {
goto cleanUp
}
slot, session, loggedIn, certObjs, err = getMatchingCerts(module, slots, uri, userPin, false)
if err != nil {
goto cleanUp
}
for _, obj := range certObjs {
curUri := pkcs11uri.New()
curUri.AddPathAttribute("model", slot.tokInfo.Model)
curUri.AddPathAttribute("manufacturer", slot.tokInfo.ManufacturerID)
curUri.AddPathAttribute("serial", slot.tokInfo.SerialNumber)
curUri.AddPathAttribute("slot-description", slot.info.SlotDescription)
curUri.AddPathAttribute("slot-manufacturer", slot.info.ManufacturerID)
if obj.id != nil {
curUri.AddPathAttribute("id", string(obj.id[:]))
}
if obj.label != nil {
curUri.AddPathAttribute("object", string(obj.label[:]))
}
curUri.AddPathAttribute("type", "cert")
curUriStr, err := curUri.Format() // nosemgrep
if err != nil {
curUriStr = ""
}
matchingCerts = append(matchingCerts, CertificateContainer{-1, obj.cert, curUriStr})
}
// Note that this clean up should happen regardless of failure.
cleanUp:
if module != nil {
if session != 0 {
if loggedIn {
module.Logout(session)
}
module.CloseSession(session)
}
module.Finalize()
module.Destroy()
}
return matchingCerts, err
}
// Returns the public key associated with this PKCS11Signer.
func (pkcs11Signer *PKCS11Signer) Public() crypto.PublicKey {
var (
cert *x509.Certificate
@@ -522,14 +432,13 @@ func (pkcs11Signer *PKCS11Signer) Public() crypto.PublicKey {
return nil
}
// Closes this PKCS11Signer.
func (pkcs11Signer *PKCS11Signer) Close() {
var module *pkcs11.Ctx
module = pkcs11Signer.module
if module != nil {
module.Finalize()
_ = module.Finalize()
module.Destroy()
}
@@ -565,13 +474,17 @@ func pkcs11PasswordPrompt(module *pkcs11.Ctx, session pkcs11.SessionHandle, user
if err != nil {
return "", errors.New(parseErrMsg)
}
defer ttyReadFile.Close()
defer func(ttyReadFile *os.File) {
_ = ttyReadFile.Close()
}(ttyReadFile)
ttyWriteFile, err = os.OpenFile(ttyWritePath, os.O_WRONLY, 0)
if err != nil {
return "", errors.New(parseErrMsg)
}
defer ttyWriteFile.Close()
defer func(ttyWriteFile *os.File) {
_ = ttyWriteFile.Close()
}(ttyWriteFile)
for true {
pin, err = GetPassword(ttyReadFile, ttyWriteFile, prompt, parseErrMsg)
@@ -654,28 +567,24 @@ func signHelper(module *pkcs11.Ctx, session pkcs11.SessionHandle, privateKeyObj
err = module.Login(session, pkcs11.CKU_CONTEXT_SPECIFIC, contextSpecificPin)
if err == nil {
goto afterContextSpecificLogin
} else {
if Debug {
log.Printf("user re-authentication attempt failed (%s)\n", err.Error())
}
}
}
// If the context-specific PIN couldn't be derived, prompt the user for
// the context-specific PIN for this object.
keyUri = pkcs11uri.New()
keyUri.AddPathAttribute("model", slot.tokInfo.Model)
keyUri.AddPathAttribute("manufacturer", slot.tokInfo.ManufacturerID)
keyUri.AddPathAttribute("serial", slot.tokInfo.SerialNumber)
keyUri.AddPathAttribute("slot-description", slot.info.SlotDescription)
keyUri.AddPathAttribute("slot-manufacturer", slot.info.ManufacturerID)
_ = keyUri.AddPathAttribute("model", slot.tokInfo.Model)
_ = keyUri.AddPathAttribute("manufacturer", slot.tokInfo.ManufacturerID)
_ = keyUri.AddPathAttribute("serial", slot.tokInfo.SerialNumber)
_ = keyUri.AddPathAttribute("slot-description", slot.info.SlotDescription)
_ = keyUri.AddPathAttribute("slot-manufacturer", slot.info.ManufacturerID)
if privateKeyObj.id != nil {
keyUri.AddPathAttribute("id", string(privateKeyObj.id[:]))
_ = keyUri.AddPathAttribute("id", string(privateKeyObj.id[:]))
}
if privateKeyObj.label != nil {
keyUri.AddPathAttribute("object", string(privateKeyObj.label[:]))
_ = keyUri.AddPathAttribute("object", string(privateKeyObj.label[:]))
}
keyUri.AddPathAttribute("type", "private")
_ = keyUri.AddPathAttribute("type", "private")
keyUriStr, err = keyUri.Format() // nosemgrep
if err != nil {
keyUriStr = ""
@@ -737,17 +646,14 @@ func getPKCS11Key(module *pkcs11.Ctx, session pkcs11.SessionHandle, loggedIn boo
manufacturerId = slots[0].info.ManufacturerID
if session != 0 {
if loggedIn {
module.Logout(session)
module.CloseSession(session)
_ = module.Logout(session)
_ = module.CloseSession(session)
}
}
loggedIn = false
session = 0
}
} else {
if Debug {
log.Printf("Found %d matching slots for the PKCS#11 key\n", len(slots))
}
// If the URI matched multiple slots *but* one of them is the
// one (certSlotNr) that the certificate was found in, then use
// that.
@@ -794,7 +700,7 @@ retry_search:
goto fail
}
for true {
sessionPrivateKeyObjects, _, err := module.FindObjects(session, MAX_OBJECT_LIMIT)
sessionPrivateKeyObjects, _, err := module.FindObjects(session, MaxObjectLimit)
if err != nil {
goto fail
}
@@ -802,7 +708,7 @@ retry_search:
break
}
privateKeyObjects = append(privateKeyObjects, sessionPrivateKeyObjects...)
if len(sessionPrivateKeyObjects) < MAX_OBJECT_LIMIT {
if len(sessionPrivateKeyObjects) < MaxObjectLimit {
break
}
}
@@ -894,13 +800,8 @@ retry_search:
if noKeyUri {
_, keyHadLabel := keyUri.GetPathAttribute("object", false)
if keyHadLabel {
if Debug {
log.Println("unable to find private key with CKA_LABEL;" +
" repeating the search using CKA_ID of the certificate" +
" without requiring a CKA_LABEL match")
}
keyUri.RemovePathAttribute("object")
keyUri.SetPathAttribute("id", escapeAll(certObj.id))
_ = keyUri.SetPathAttribute("id", escapeAll(certObj.id))
goto retry_search
}
}
@@ -913,10 +814,10 @@ retry_search:
// So that hunting for the key can be more efficient in the future,
// return a key URI that has CKA_ID and CKA_LABEL appropriately set.
if privateKeyObj.id != nil && len(privateKeyObj.id) != 0 {
keyUri.SetPathAttribute("id", escapeAll(privateKeyObj.id))
_ = keyUri.SetPathAttribute("id", escapeAll(privateKeyObj.id))
}
if privateKeyObj.label != nil && len(privateKeyObj.label) != 0 {
keyUri.SetPathAttribute("object", escapeAll(privateKeyObj.label))
_ = keyUri.SetPathAttribute("object", escapeAll(privateKeyObj.label))
}
return session, userPin, keyUri, keyType, privateKeyObj, keySlot, alwaysAuth, contextSpecificPin, nil
@@ -947,8 +848,7 @@ func getCertificate(module *pkcs11.Ctx, certUri *pkcs11uri.Pkcs11URI, userPin st
return certSlot, slots, session, loggedIn, matchingCerts[0], nil
}
// Implements the crypto.Signer interface and signs the passed in digest
func (pkcs11Signer *PKCS11Signer) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
func (pkcs11Signer *PKCS11Signer) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
var (
module *pkcs11.Ctx
session pkcs11.SessionHandle
@@ -1012,15 +912,14 @@ func (pkcs11Signer *PKCS11Signer) Sign(rand io.Reader, digest []byte, opts crypt
cleanUp:
if session != 0 {
if loggedIn {
module.Logout(session)
_ = module.Logout(session)
}
module.CloseSession(session)
_ = module.CloseSession(session)
}
return signature, err
}
// Gets the *x509.Certificate associated with this PKCS11Signer.
func (pkcs11Signer *PKCS11Signer) Certificate() (cert *x509.Certificate, err error) {
// If there was a certificate chain associated with this Signer, it
// should've been saved before.
@@ -1123,7 +1022,7 @@ func checkPrivateKeyMatchesCert(module *pkcs11.Ctx, session pkcs11.SessionHandle
// "AWS Roles Anywhere Credential Helper PKCS11 Test" || PKCS11_TEST_VERSION ||
// MANUFACTURER_ID || SHA256("IAM RA" || PUBLIC_KEY_BYTE_ARRAY)
digest := "AWS Roles Anywhere Credential Helper PKCS11 Test" +
strconv.Itoa(int(PKCS11_TEST_VERSION)) + manufacturerId + string(digestSuffix)
strconv.Itoa(int(Pkcs11TestVersion)) + manufacturerId + string(digestSuffix)
digestBytes := []byte(digest)
hash := sha256.Sum256(digestBytes)
@@ -1240,7 +1139,7 @@ func GetPKCS11Signer(libPkcs11 string, cert *x509.Certificate, certChain []*x509
}
crtAttributes, err = module.GetAttributeValue(session, certObj.certObject, crtAttributes)
if err == nil {
certUri.SetPathAttribute("id", escapeAll(crtAttributes[0].Value))
_ = certUri.SetPathAttribute("id", escapeAll(crtAttributes[0].Value))
}
crtAttributes = []*pkcs11.Attribute{
@@ -1248,7 +1147,7 @@ func GetPKCS11Signer(libPkcs11 string, cert *x509.Certificate, certChain []*x509
}
crtAttributes, err = module.GetAttributeValue(session, certObj.certObject, crtAttributes)
if err == nil {
certUri.SetPathAttribute("object", escapeAll(crtAttributes[0].Value))
_ = certUri.SetPathAttribute("object", escapeAll(crtAttributes[0].Value))
}
if certChain == nil {
@@ -1274,7 +1173,7 @@ func GetPKCS11Signer(libPkcs11 string, cert *x509.Certificate, certChain []*x509
} else {
certUriStr, _ := certUri.Format()
keyUri = pkcs11uri.New()
keyUri.Parse(certUriStr)
_ = keyUri.Parse(certUriStr)
noKeyUri = true
}
if _userPin, ok := keyUri.GetQueryAttribute("pin-value", false); ok {
@@ -1296,18 +1195,18 @@ func GetPKCS11Signer(libPkcs11 string, cert *x509.Certificate, certChain []*x509
switch keyType {
case pkcs11.CKK_EC:
signingAlgorithm = aws4_x509_ecdsa_sha256
signingAlgorithm = aws4X509EcdsaSha256
case pkcs11.CKK_RSA:
signingAlgorithm = aws4_x509_rsa_sha256
signingAlgorithm = aws4X509RsaSha256
default:
return nil, "", errors.New("unsupported algorithm")
}
if session != 0 {
if loggedIn {
module.Logout(session)
_ = module.Logout(session)
}
module.CloseSession(session)
_ = module.CloseSession(session)
}
return &PKCS11Signer{cert, certChain, module, userPin, alwaysAuth, contextSpecificPin, certUri, keyUri, reusePin}, signingAlgorithm, nil
@@ -1316,11 +1215,11 @@ fail:
if module != nil {
if session != 0 {
if loggedIn {
module.Logout(session)
_ = module.Logout(session)
}
module.CloseSession(session)
_ = module.CloseSession(session)
}
module.Finalize()
_ = module.Finalize()
module.Destroy()
}