Skip to content

Instantly share code, notes, and snippets.

@olekukonko
Created September 8, 2017 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olekukonko/6e864ba3ba84f19070a03627fe8052a5 to your computer and use it in GitHub Desktop.
Save olekukonko/6e864ba3ba84f19070a03627fe8052a5 to your computer and use it in GitHub Desktop.
Trusting Local Certificate
package main
import (
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
const (
localCertFile = "/usr/local/internal-ca/ca.crt"
)
func main() {
insecure := flag.Bool("insecure-ssl", false, "Accept/Ignore all server SSL certificates")
flag.Parse()
// Get the SystemCertPool, continue with an empty pool on error
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
// Read in the cert file
certs, err := ioutil.ReadFile(localCertFile)
if err != nil {
log.Fatalf("Failed to append %q to RootCAs: %v", localCertFile, err)
}
// Append our cert to the system pool
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
log.Println("No certs appended, using system certs only")
}
// Trust the augmented cert pool in our client
config := &tls.Config{
InsecureSkipVerify: *insecure,
RootCAs: rootCAs,
}
tr := &http.Transport{TLSClientConfig: config}
client := &http.Client{Transport: tr}
// Uses local self-signed cert
req := http.NewRequest(http.MethodGet, "https://localhost/api/version", nil)
resp, err := client.Do(req)
// Handle resp and err
// Still works with host-trusted CAs!
req = http.NewRequest(http.MethodGet, "https://example.com/", nil)
resp, err = client.Do(req)
// Handle resp and err
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment