Instantly share code, notes, and snippets.

@zmanian /keyping.go
Last active Feb 10, 2019

Embed
What would you like to do?
Key Pinning in #Golang
package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"log"
"net"
"net/http"
)
type Dialer func(network, addr string) (net.Conn, error)
func makeDialer(fingerprint []byte, skipCAVerification bool) Dialer {
return func(network, addr string) (net.Conn, error) {
c, err := tls.Dial(network, addr, &tls.Config{InsecureSkipVerify: skipCAVerification})
if err != nil {
return c, err
}
connstate := c.ConnectionState()
keyPinValid := false
for _, peercert := range connstate.PeerCertificates {
der, err := x509.MarshalPKIXPublicKey(peercert.PublicKey)
hash := sha256.Sum256(der)
// log.Println(peercert.Issuer)
// log.Printf("%#v", hash)
if err != nil {
log.Fatal(err)
}
if bytes.Compare(hash[0:], fingerprint) == 0 {
log.Println("Pinned Key found")
keyPinValid = true
}
}
if keyPinValid == false {
}
return c, nil
}
}
func main() {
fingerprint := []byte{0x53, 0x8d, 0xe6, 0x6e, 0x1d, 0xaf, 0xf6, 0x25, 0xd6, 0x78, 0xb0, 0xb3, 0x71, 0x4, 0xe5, 0x41, 0xd8, 0xc9, 0x68, 0x1f, 0xa6, 0x6, 0x24, 0x6a, 0xf, 0xf9, 0xea, 0xa0, 0x36, 0x55, 0xdc, 0xc1}
client := &http.Client{}
client.Transport = &http.Transport{
DialTLS: makeDialer(fingerprint, false),
}
req, err := http.NewRequest("GET", "https://www.google.com", nil)
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
log.Println(resp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment