Skip to content

Instantly share code, notes, and snippets.

@b4ldr
Created July 3, 2023 12:11
Show Gist options
  • Save b4ldr/6822facfe4454c9bf647723d2a44c5e6 to your computer and use it in GitHub Desktop.
Save b4ldr/6822facfe4454c9bf647723d2a44c5e6 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"github.com/davecgh/go-spew/spew"
"io/ioutil"
"log"
"net"
"os"
"strings"
"time"
)
var (
host = flag.String("host", "puppetdb1003.eqiad.wmnet", "A PEM eoncoded certificate file.")
target = flag.String("target", "pki.discovery.wmnet:443", "The end point to connect to")
certFile = flag.String("cert", "/var/lib/puppet/ssl/certs/puppetdb1003.eqiad.wmnet.pem", "A PEM eoncoded CA's certificate file.")
caFile = flag.String("CA", "/etc/ssl/certs/wmf-ca-certificates.crt", "A PEM eoncoded CA's certificate file.")
)
func main() {
flag.Parse()
ssl_path := "/var/lib/puppet/ssl"
// certFile := fmt.Sprintf("%s/certs/%s.pem", ssl_path, *host)
keyFile := fmt.Sprintf("%s/private_keys/%s.pem", ssl_path, *host)
hostname := strings.Split(*target, ":")[0]
println("using certfile: ", *certFile)
println("using keyfie: ", keyFile)
println("using CA: ", *caFile)
// Load client cert
cert, err := tls.LoadX509KeyPair(*certFile, keyFile)
if err != nil {
log.Fatal(err)
}
// Load CA cert
caCert, err := ioutil.ReadFile(*caFile)
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
dialer := &net.Dialer{
Timeout: 60 * time.Second,
}
rawConn, err := dialer.Dial("tcp", *target)
if err != nil {
fmt.Println("failed to dial: ", err.Error())
return
}
config := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
KeyLogWriter: os.Stdout,
ServerName: hostname,
VerifyConnection: func(cs tls.ConnectionState) error {
opts := x509.VerifyOptions{
DNSName: cs.ServerName,
Intermediates: x509.NewCertPool(),
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}
for _, cert := range cs.PeerCertificates[1:] {
opts.Intermediates.AddCert(cert)
}
_, err := cs.PeerCertificates[0].Verify(opts)
return err
},
}
conn := tls.Client(rawConn, config)
defer conn.Close()
conn.Handshake()
fmt.Printf("%s: handshake complete %t\n", *host, conn.ConnectionState().HandshakeComplete)
fmt.Printf("%s: protocol %s\n", *host, conn.ConnectionState().NegotiatedProtocol)
//spew.Dump(conn)
n, err := conn.Write([]byte("GET / HTTP/1.0\n\n"))
if err != nil {
log.Fatal(n, err)
}
spew.Dump(conn)
buf := make([]byte, 100)
n, err = conn.Read(buf)
if err != nil {
log.Fatal(n, err)
}
println(string(buf[:n]))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment