forked from mumble-voip/grumble
/
tlsserver.go
89 lines (76 loc) · 1.94 KB
/
tlsserver.go
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"log"
"time"
"net"
"crypto/tls"
"crypto/rand"
"encoding/pem"
"crypto/x509"
"io/ioutil"
)
func NewTLSListener(port int) (rl *tls.Listener) {
rl = nil
// Load the certificate
pemBytes, err := ioutil.ReadFile("grumble.crt")
if err != nil {
log.Printf("Failed to read server.crt: %s", err)
return
}
// Decode the certificate
cert, _ := pem.Decode(pemBytes)
if cert == nil {
log.Printf("Failed to parse server.crt")
return
}
// Load the private key
keyBytes, err := ioutil.ReadFile("grumble.key")
if err != nil {
log.Printf("Failed to read server.key.insecure: %s", err)
return
}
// Decode the private key
pkPEM, _ := pem.Decode(keyBytes)
if pkPEM == nil {
log.Printf("Failed to parse server.key.insecure: %s", err)
return
}
// Determine if we are an RSA private key
if pkPEM.Type != "RSA PRIVATE KEY" {
log.Printf("server.key.insecure is not an RSA private key. Found '%s'",
pkPEM.Type)
return
}
// Check if the PEM file has headers. This will typically
// mean that it requires a passphrase to decrypt it. For now,
// let us just assume that people will decrypt them for us, so
// we can use them without too much work.
if len(pkPEM.Headers) != 0 {
log.Printf("server.key.insecure has headers and is probably encrypted.")
return
}
// Parse the PKCS12 private key.
priv, err := x509.ParsePKCS1PrivateKey(pkPEM.Bytes)
if err != nil {
log.Printf("Invalid key in server.key.insecure: %s", err)
return
}
// Create a new TLS config.
config := new(tls.Config)
config.Rand = rand.Reader
config.Time = time.Seconds
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0].Certificate = [][]byte{cert.Bytes}
config.Certificates[0].PrivateKey = priv
config.AuthenticateClient = true
l, err := net.ListenTCP("tcp", &net.TCPAddr{
net.ParseIP("0.0.0.0"),
port,
})
if err != nil {
log.Printf("Cannot bind: %s\n", err)
return
}
rl = tls.NewListener(l, config)
return
}