Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TOOLS-2598 Fix client certificate chain bug #429

Merged
merged 3 commits into from
Apr 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 16 additions & 8 deletions common/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,8 @@ func addClientCertFromSeparateFiles(cfg *tls.Config, keyFile, certFile, keyPassw
// containing file and returns the certificate's subject name.
func addClientCertFromBytes(cfg *tls.Config, data []byte, keyPasswd string) (string, error) {
var currentBlock *pem.Block
var certBlock, certDecodedBlock, keyBlock []byte
var certDecodedBlock []byte
var certBlocks, keyBlocks [][]byte

remaining := data
start := 0
Expand All @@ -176,9 +177,14 @@ func addClientCertFromBytes(cfg *tls.Config, data []byte, keyPasswd string) (str
}

if currentBlock.Type == "CERTIFICATE" {
certBlock = data[start : len(data)-len(remaining)]
certDecodedBlock = currentBlock.Bytes
certBlock := data[start : len(data)-len(remaining)]
certBlocks = append(certBlocks, certBlock)
start += len(certBlock)

// Use the first cert block for the returned Subject string at the end.
if len(certDecodedBlock) == 0 {
certDecodedBlock = currentBlock.Bytes
}
} else if strings.HasSuffix(currentBlock.Type, "PRIVATE KEY") {
isEncrypted := x509.IsEncryptedPEMBlock(currentBlock) || strings.Contains(currentBlock.Type, "ENCRYPTED PRIVATE KEY")
if isEncrypted {
Expand Down Expand Up @@ -209,23 +215,25 @@ func addClientCertFromBytes(cfg *tls.Config, data []byte, keyPasswd string) (str

var encoded bytes.Buffer
pem.Encode(&encoded, &pem.Block{Type: currentBlock.Type, Bytes: keyBytes})
keyBlock = encoded.Bytes()
keyBlock := encoded.Bytes()
keyBlocks = append(keyBlocks, keyBlock)
start = len(data) - len(remaining)
} else {
keyBlock = data[start : len(data)-len(remaining)]
keyBlock := data[start : len(data)-len(remaining)]
keyBlocks = append(keyBlocks, keyBlock)
start += len(keyBlock)
}
}
}

if len(certBlock) == 0 {
if len(certBlocks) == 0 {
return "", fmt.Errorf("failed to find CERTIFICATE")
}
if len(keyBlock) == 0 {
if len(keyBlocks) == 0 {
return "", fmt.Errorf("failed to find PRIVATE KEY")
}

cert, err := tls.X509KeyPair(certBlock, keyBlock)
cert, err := tls.X509KeyPair(bytes.Join(certBlocks, []byte("\n")), bytes.Join(keyBlocks, []byte("\n")))
if err != nil {
return "", err
}
Expand Down