summaryrefslogtreecommitdiff
path: root/tls-getcerts.go
blob: b0d45333206e23cead0a3b4cc9eb09e9c9e4fb57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"os"
	"encoding/pem"
)

func getcert(server string) (*x509.Certificate, error){
	conn, err := tls.Dial("tcp", fmt.Sprintf("%s:443", server), &tls.Config{ServerName: server})
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	chain := conn.ConnectionState().PeerCertificates
	return chain[len(chain)-2], nil
}

func main() {
	for _, server := range os.Args[1:] {
		cert, err := getcert(server)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not get certificate from server %q: %q\n", server, err)
			os.Exit(1)
		}
		block := pem.Block{
			Type: "CERTIFICATE",
			Headers: nil,
			Bytes: cert.Raw,
		}
		pem.Encode(os.Stdout, &block)
	}
}