Skip to content

Instantly share code, notes, and snippets.

@bradfitz
Created June 1, 2022 19:52
Show Gist options
  • Save bradfitz/aceec67d0105b261500ab18abaf8caed to your computer and use it in GitHub Desktop.
Save bradfitz/aceec67d0105b261500ab18abaf8caed to your computer and use it in GitHub Desktop.
OCSP verification tinkering
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"io/ioutil"
"log"
"net/http"
"golang.org/x/crypto/ocsp"
)
func main() {
c, err := tls.Dial("tcp", "bradfitz.com:443", &tls.Config{})
if err != nil {
log.Fatalf("Dial: %v", err)
}
if err := c.Handshake(); err != nil {
log.Fatalf("Handshake: %v", err)
}
st := c.ConnectionState()
var leafCert *x509.Certificate
var issuerCert *x509.Certificate
var leafAuthorityKeyID string
for i, cert := range st.PeerCertificates {
if i == 0 {
leafCert = cert
leafAuthorityKeyID = string(cert.AuthorityKeyId)
}
if i > 0 {
if leafAuthorityKeyID == string(cert.SubjectKeyId) {
issuerCert = cert
}
}
}
if leafCert == nil {
log.Fatalf("nil leaf")
}
if issuerCert == nil {
log.Fatalf("nil issuer")
}
if len(leafCert.OCSPServer) == 0 {
log.Fatalf("no OCSP server")
}
log.Printf("OCSP server = %q", leafCert.OCSPServer)
reqb, err := ocsp.CreateRequest(leafCert, issuerCert, nil)
if err != nil {
log.Fatalf("CreateRequest: %v", err)
}
log.Printf("req: %q", reqb)
hreq, err := http.NewRequest("POST", leafCert.OCSPServer[0], bytes.NewReader(reqb))
if err != nil {
log.Fatal(err)
}
hreq.Header.Add("Content-Type", "application/ocsp-request")
hreq.Header.Add("Accept", "application/ocsp-response")
hres, err := http.DefaultClient.Do(hreq)
if err != nil {
log.Fatal(err)
}
defer hres.Body.Close()
if hres.StatusCode != 200 {
log.Fatal(hres.Status)
}
ocspRawRes, err := ioutil.ReadAll(hres.Body)
if err != nil {
log.Fatal(err)
}
ores, err := ocsp.ParseResponse(ocspRawRes, issuerCert)
if err != nil {
log.Fatalf("ocsp.ParseResponse: %v", err)
}
log.Printf("Got: %+v", ores)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment