-
Notifications
You must be signed in to change notification settings - Fork 3
/
ssl.go
209 lines (191 loc) · 5.79 KB
/
ssl.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package ssl
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
nethttp "net/http"
"strings"
"github.com/github/orchestrator/go/config"
"github.com/go-martini/martini"
"github.com/howeyc/gopass"
"github.com/outbrain/golib/log"
)
var cipherSuites = []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
}
// Determine if a string element is in a string array
func HasString(elem string, arr []string) bool {
for _, s := range arr {
if s == elem {
return true
}
}
return false
}
// NewTLSConfig returns an initialized TLS configuration suitable for client
// authentication. If caFile is non-empty, it will be loaded.
func NewTLSConfig(caFile string, mutualTLS bool) (*tls.Config, error) {
var c tls.Config
// Set to TLS 1.2 as a minimum. This is overridden for mysql communication
c.MinVersion = tls.VersionTLS12
// Remove insecure ciphers from the list
c.CipherSuites = cipherSuites
c.PreferServerCipherSuites = true
if mutualTLS {
log.Info("MutualTLS requested, client certificates will be verified")
c.ClientAuth = tls.VerifyClientCertIfGiven
}
if caFile != "" {
data, err := ioutil.ReadFile(caFile)
if err != nil {
return &c, err
}
c.ClientCAs = x509.NewCertPool()
if !c.ClientCAs.AppendCertsFromPEM(data) {
return &c, errors.New("No certificates parsed")
}
log.Info("Read in CA file:", caFile)
}
c.BuildNameToCertificate()
return &c, nil
}
// Verify that the OU of the presented client certificate matches the list
// of Valid OUs
func Verify(r *nethttp.Request, validOUs []string) error {
if strings.Contains(r.URL.String(), config.Config.StatusEndpoint) && !config.Config.StatusOUVerify {
return nil
}
if r.TLS == nil {
return errors.New("No TLS")
}
for _, chain := range r.TLS.VerifiedChains {
s := chain[0].Subject.OrganizationalUnit
log.Debug("All OUs:", strings.Join(s, " "))
for _, ou := range s {
log.Debug("Client presented OU:", ou)
if HasString(ou, validOUs) {
log.Debug("Found valid OU:", ou)
return nil
}
}
}
log.Error("No valid OUs found")
return errors.New("Invalid OU")
}
// TODO: make this testable?
func VerifyOUs(validOUs []string) martini.Handler {
return func(res nethttp.ResponseWriter, req *nethttp.Request, c martini.Context) {
log.Debug("Verifying client OU")
if err := Verify(req, validOUs); err != nil {
nethttp.Error(res, err.Error(), nethttp.StatusUnauthorized)
}
}
}
// AppendKeyPair loads the given TLS key pair and appends it to
// tlsConfig.Certificates.
func AppendKeyPair(tlsConfig *tls.Config, certFile string, keyFile string) error {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
return nil
}
// Read in a keypair where the key is password protected
func AppendKeyPairWithPassword(tlsConfig *tls.Config, certFile string, keyFile string, pemPass []byte) error {
// Certificates aren't usually password protected, but we're kicking the password
// along just in case. It won't be used if the file isn't encrypted
certData, err := ReadPEMData(certFile, pemPass)
if err != nil {
return err
}
keyData, err := ReadPEMData(keyFile, pemPass)
if err != nil {
return err
}
cert, err := tls.X509KeyPair(certData, keyData)
if err != nil {
return err
}
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
return nil
}
// Read a PEM file and ask for a password to decrypt it if needed
func ReadPEMData(pemFile string, pemPass []byte) ([]byte, error) {
pemData, err := ioutil.ReadFile(pemFile)
if err != nil {
return pemData, err
}
// We should really just get the pem.Block back here, if there's other
// junk on the end, warn about it.
pemBlock, rest := pem.Decode(pemData)
if len(rest) > 0 {
log.Warning("Didn't parse all of", pemFile)
}
if x509.IsEncryptedPEMBlock(pemBlock) {
// Decrypt and get the ASN.1 DER bytes here
pemData, err = x509.DecryptPEMBlock(pemBlock, pemPass)
if err != nil {
return pemData, err
} else {
log.Info("Decrypted", pemFile, "successfully")
}
// Shove the decrypted DER bytes into a new pem Block with blank headers
var newBlock pem.Block
newBlock.Type = pemBlock.Type
newBlock.Bytes = pemData
// This is now like reading in an uncrypted key from a file and stuffing it
// into a byte stream
pemData = pem.EncodeToMemory(&newBlock)
}
return pemData, nil
}
// Print a password prompt on the terminal and collect a password
func GetPEMPassword(pemFile string) []byte {
fmt.Printf("Password for %s: ", pemFile)
pass, err := gopass.GetPasswd()
if err != nil {
// We'll error with an incorrect password at DecryptPEMBlock
return []byte("")
}
return pass
}
// Determine if PEM file is encrypted
func IsEncryptedPEM(pemFile string) bool {
pemData, err := ioutil.ReadFile(pemFile)
if err != nil {
return false
}
pemBlock, _ := pem.Decode(pemData)
if len(pemBlock.Bytes) == 0 {
return false
}
return x509.IsEncryptedPEMBlock(pemBlock)
}
// ListenAndServeTLS acts identically to http.ListenAndServeTLS, except that it
// expects TLS configuration.
// TODO: refactor so this is testable?
func ListenAndServeTLS(addr string, handler nethttp.Handler, tlsConfig *tls.Config) error {
if addr == "" {
// On unix Listen calls getaddrinfo to parse the port, so named ports are fine as long
// as they exist in /etc/services
addr = ":https"
}
l, err := tls.Listen("tcp", addr, tlsConfig)
if err != nil {
return err
}
return nethttp.Serve(l, handler)
}