Skip to content

Instantly share code, notes, and snippets.

@rekby
Created August 7, 2015 13:03
Show Gist options
  • Save rekby/201588f226de4d00a35a to your computer and use it in GitHub Desktop.
Save rekby/201588f226de4d00a35a to your computer and use it in GitHub Desktop.
package main
import (
"crypto/tls"
"fmt"
"time"
"crypto/x509"
)
const rootCert = `-----BEGIN CERTIFICATE-----
MIIEMzCCAxugAwIBAgIBATANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJSVTEM
MAoGA1UECBMDdG1wMQwwCgYDVQQKEwN0bXAxDjAMBgNVBAMTBXRtcENBMCAXDTE1
MDgwNzExMzMwMFoYDzIzODAwODA3MTEzMzAwWjA5MQswCQYDVQQGEwJSVTEMMAoG
A1UECBMDdG1wMQwwCgYDVQQKEwN0bXAxDjAMBgNVBAMTBXRtcENBMIIBIjANBgkq
hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuOiU93evlvTLEoQSa2jxaYDGw7ZrRDu5
OlUSwIrz6yQJxWTdvtbhsj2gKOfE9umNQTZrW5l+T+4FwXwuvKOaiM+RP2vqH1Ly
TKsAagpU/yv27k3DPP/vVCuoRs8lEDVSedcw+WAOEuIZEdf9o1VHT+KvFTSDp1As
pmwNEJ+oSIqI4LFuFWC3yDakU3tzmo/e6l1thnQvmBNhhZCClzRkKyEbM41QsZOQ
ZrEbD1LPjij9tFqgDn0lmwl/Pn4MGQNcDhMB+SBpEnDVR5RH8eBKDyLmaeFiuDru
d/IEOXPmet7ABuTiswVNbKWsOf8U/p585pTqSkgHEmOcoVFZEqMrbwIDAQABo4IB
QjCCAT4wDAYDVR0TBAUwAwEB/zAMBgNVHQ8EBQMDB/+AMIHsBgNVHSUEgeQwgeEG
CCsGAQUFBwMBBggrBgEFBQcDAgYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEFBQcD
CAYKKwYBBAGCNwIBFQYKKwYBBAGCNwIBFgYKKwYBBAGCNwoDAQYKKwYBBAGCNwoD
AwYKKwYBBAGCNwoDBAYJYIZI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PGfM01lJVo7inKNtu7ncX258w4kjRy1Vrd
8mbAJJXjNSpgbTHXJRRL2kxWNUDYWQ86JmLxc62y9wKBgBN6XxoWXNYlHLRXJSc9
MfkUKVP7EwasuGvvaAuM6JDZlMVEi/17R00l3AWoQM3aw2I/8KmbOzxpww4XOwU3
pLRqn3AcVxmycriW0wW+9lVobZwFZIyH0UketiR9VI8j23epb2duTbVZzazvr/0o
KQVaqXkdTNbe+Enr5DekmN3B
-----END PRIVATE KEY-----`
func main(){
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM([]byte(rootCert)){
panic("Can't parse root cert")
}
cert, err := tls.X509KeyPair([]byte(serverCert), []byte(serverKey))
if err != nil {
panic(err)
}
tlsConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: roots,
}
tlsConfig.Certificates = make([]tls.Certificate, 0)
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
listener, err := tls.Listen("tcp", "0.0.0.0:1234", tlsConfig)
if err != nil {
panic(err)
}
fmt.Println("START")
for {
connection, err := listener.Accept()
if err != nil {
panic(err)
}
fmt.Println("OK ", connection.RemoteAddr())
connection.SetReadDeadline(time.Now().Add(time.Second))
tlsconn, ok := connection.(*tls.Conn)
if ! ok{
fmt.Println("It isn't tlsconn")
connection.Close()
continue
}
fmt.Println("TLS")
fmt.Println(tlsconn.ConnectionState().PeerCertificates)
nullBuf := []byte{1}
connection.Read(nullBuf)
fmt.Println(nullBuf)
fmt.Println("TLS")
fmt.Println(tlsconn.ConnectionState().PeerCertificates[0].Subject.CommonName)
connection.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment