Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"crypto/sha256"
"encoding/pem"
"flag"
"fmt"
"os"
Expand Down Expand Up @@ -80,6 +82,28 @@ func readCertificate() ([]byte, error) {
panic("thou shalt not reach hear")
}

func calculatePEMCertChainHash(certContent []byte) ([]byte, error) {
var hashValue []byte
for {
block, remain := pem.Decode(certContent)
if block == nil {
break
}
out := sha256.Sum256(block.Bytes)
if hashValue == nil {
hashValue = out[:]
} else {
newHashValue := sha256.Sum256(append(hashValue, out[:]...))
hashValue = newHashValue[:]
}
certContent = remain
}
if hashValue == nil {
return nil, newError("no certificate found")
}
return hashValue, nil
}

func logConfig(logLevel string) *vlog.Config {
config := &vlog.Config{
Error: &vlog.LogSpecification{Type: vlog.LogType_Console, Level: clog.Severity_Warning},
Expand Down Expand Up @@ -189,6 +213,12 @@ func generateConfig() (*core.Config, error) {
if err != nil {
return nil, newError("failed to read cert").Base(err)
}
certHash, err := calculatePEMCertChainHash(certificate.Certificate)
if err != nil {
return nil, newError("failed to parse cert").Base(err)
}
tlsConfig.AllowInsecureIfPinnedPeerCertificate = true
tlsConfig.PinnedPeerCertificateChainSha256 = [][]byte{certHash}
tlsConfig.Certificate = []*tls.Certificate{&certificate}
}
streamConfig.SecurityType = serial.GetMessageType(&tlsConfig)
Expand Down
35 changes: 35 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"bytes"
"crypto/sha256"
"encoding/pem"
"testing"
)

func TestCalculatePEMCertChainHash(t *testing.T) {
leaf := []byte("leaf certificate")
issuer := []byte("issuer certificate")
pemChain := bytes.Join([][]byte{
pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leaf}),
pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: issuer}),
}, nil)

hash, err := calculatePEMCertChainHash(pemChain)
if err != nil {
t.Fatal(err)
}

leafHash := sha256.Sum256(leaf)
issuerHash := sha256.Sum256(issuer)
expected := sha256.Sum256(append(leafHash[:], issuerHash[:]...))
if !bytes.Equal(hash, expected[:]) {
t.Fatalf("unexpected hash: got %x, want %x", hash, expected)
}
}

func TestCalculatePEMCertChainHashRejectsInvalidPEM(t *testing.T) {
if _, err := calculatePEMCertChainHash([]byte("not a certificate")); err == nil {
t.Fatal("expected invalid PEM to fail")
}
}