-
Notifications
You must be signed in to change notification settings - Fork 1
/
vault-token-issuer.go
302 lines (240 loc) · 9.02 KB
/
vault-token-issuer.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//go:generate ./build-spa.sh
//go:generate go run build_spa_vfsgen.go
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"time"
"github.com/asaskevich/govalidator"
"github.com/bitsofinfo/vault-token-issuer/auth"
"github.com/bitsofinfo/vault-token-issuer/util"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/gorilla/mux"
)
var (
vaultUrl string // vault URL (flag opt)
vaultAuthenticator string // string vault auth plugin name (flag opt)
enableSpa bool // enable the SPA (flag opt)
tlsCertPath string // path to TLS certificate (flag opt)
tlsKeyPath string // path to TLS private key (flag opt)
listenPort int // port to listen on (flag opt)
authenticator auth.VaultAuthenticator // the vault auth plugin
)
// the JSON payload we both consume
// from callers and relay to Vault
type createTokenPayload struct {
Renewable bool `json:"renewable"` // valid:required doesn't work on 'false' @see https://github.com/asaskevich/govalidator/issues/256
Period string `valid:"alphanum,required" json:"period"`
Policies []string `valid:"ascii,required" json:"policies"`
}
// Struct for JSON we retun to caller
type createTokenResponse struct {
Code string `json:"code"`
Token string `json:"token"`
Msg string `json:"msg"`
}
func init() {
// cmd line args
flag.StringVar(&vaultUrl, "vault-url", "", "Vault url where token API calls will be made. i.e. http(s)://<vault>[:port]")
flag.StringVar(&vaultAuthenticator, "vault-authenticator", "", "The vault authenticator plugin to use: valid options: 'ldap'")
flag.BoolVar(&enableSpa, "enable-spa", true, "Serve the SPA at /ui, default enabled")
flag.StringVar(&tlsKeyPath, "tls-key-path", "", "Optional, path to a PEM encoded TLS private key. If omitted a self-signed cert will be auto generated in memory")
flag.StringVar(&tlsCertPath, "tls-cert-path", "", "Optional: path to a PEM encoded TLS certificate. If omitted a self-signed cert will be auto generated in memory")
flag.IntVar(&listenPort, "listen-port", 8443, "Optional, port to listen on, default 8443")
// logging options
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(log.DebugLevel)
}
func main() {
flag.Parse()
// load our plugin for the authentication backend
if vaultAuthenticator == "ldap" {
authenticator = &auth.LdapPlugin{VaultURL: vaultUrl}
log.Info("VaultAuthenticator 'ldap' loaded")
} else {
log.Fatal("Invalid --vault-authenticator specified. Supported values: 'ldap'")
}
// setup our REST routes
router := mux.NewRouter()
router.Path("/token/create-orphan").
Methods("POST").
Schemes("https").
Headers("Content-Type", "application/json").
HandlerFunc(CreateOrphanTokenHandler)
router.Path("/token/create-orphan").
Methods("OPTIONS").
Schemes("https").
HandlerFunc(corsHandler)
if enableSpa == true {
log.Info("SPA enabled and available at /ui, disable w/ -enable-spa=false")
// spaAssets are generated by vfsgen and stored in spaAssets_vfsdata.go
spaFileServer := http.FileServer(spaAssets)
router.Path("/ui").
Methods("GET").
Schemes("https").
Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ui/", http.StatusSeeOther)
}))
router.PathPrefix("/ui/").
Methods("GET").
Schemes("https").
Handler(http.StripPrefix("/ui/",
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
r.URL.Path = "/index.html"
}
spaFileServer.ServeHTTP(w, r)
})))
}
// fire up the http server
srv := &http.Server{
Handler: router,
Addr: (":" + strconv.Itoa(listenPort)),
// https://golang.org/doc/go1.6#http2 needed to disable 128b ciphers below which are required by h2
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{getTLSCertificate()},
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
}},
WriteTimeout: 20 * time.Second,
ReadTimeout: 20 * time.Second,
}
log.Fatal(srv.ListenAndServeTLS("", ""))
}
func getTLSCertificate() tls.Certificate {
// load from disk
if len(tlsCertPath) > 0 && len(tlsKeyPath) > 0 {
cert, err := tls.LoadX509KeyPair(tlsCertPath, tlsKeyPath)
if err != nil {
log.Fatal("Unexpected error loading cert/key", err)
}
log.Info("Loaded TLS cert/key from " + tlsCertPath + " " + tlsKeyPath)
return cert
}
// generate a self signed cert & key
pemCert, pemKey := util.Generate(4096)
// get cert from keypair
cert, err := tls.X509KeyPair(pemCert, pemKey)
if err != nil {
log.Fatal("Unexpected error generating self signed cert", err)
}
log.Info("Successfully generated self-signed TLS cert/key")
return cert
}
// writes an HTTP response w/ code + json result
func writeHTTPResponse(resWriter http.ResponseWriter, code string, token string, msg string, httpStatus int) {
resWriter.Header().Set("Content-Type", "application/json")
resWriter.WriteHeader(httpStatus)
json.NewEncoder(resWriter).Encode(&createTokenResponse{Code: code, Token: token, Msg: msg})
}
// writes CORS response headers
func corsHandler(resWriter http.ResponseWriter, req *http.Request) {
resWriter.Header().Set("Access-Control-Allow-Origin", "*")
resWriter.Header().Set("Access-Control-Allow-Headers", "content-type,authorization")
resWriter.Header().Set("Access-Control-Allow-Methods", "OPTIONS,POST")
}
// CreateOrphanTokenHandler ... http handler for creating vault orphan tokens
func CreateOrphanTokenHandler(resWriter http.ResponseWriter, req *http.Request) {
corsHandler(resWriter, req)
// first lets get the credentials off the request
vaultCredentials, err := authenticator.GetCredentials(req)
if err != nil {
writeHTTPResponse(resWriter, "error", "", "Bad Request: auth required", http.StatusBadRequest)
return
}
// lets get our createTokenPayload struct
payload, err := extractCreateTokenPayload(&resWriter, req)
if err != nil {
log.Error("Invalid payload: " + err.Error())
writeHTTPResponse(resWriter, "error", "", err.Error(), http.StatusUnauthorized)
return
}
// must have at least one policy
if len(payload.Policies) == 0 {
writeHTTPResponse(resWriter, "error", "", "one or more vault 'policies' are required", http.StatusBadRequest)
return
}
// auth the actual user against value and get
// the client access/auth token which we can then
// use to create the actual orphan token
userToken, err := authenticator.Auth(vaultCredentials)
if err != nil {
log.Error("Failed to authenticated againsg vault w/ VaultCredentials: " + err.Error())
writeHTTPResponse(resWriter, "error", "", err.Error(), http.StatusUnauthorized)
return
}
token, err := createOrphanToken(userToken, payload)
if err != nil {
log.Error("Failed to create orphan token: " + err.Error())
writeHTTPResponse(resWriter, "error", "", err.Error(), http.StatusInternalServerError)
return
}
writeHTTPResponse(resWriter, "ok", token,
fmt.Sprintf("renewable:%v period:%v policies:%v",
payload.Renewable,
payload.Period,
payload.Policies), http.StatusOK)
}
// Extracts the createTokenPayload JSON payload from the Request
func extractCreateTokenPayload(resWriter *http.ResponseWriter, req *http.Request) (*createTokenPayload, error) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
return nil, errors.New("failed to read request body json")
}
var payload createTokenPayload
json.Unmarshal(body, &payload)
x, err := json.Marshal(&payload)
log.Info(string(x))
// validate
_, err = govalidator.ValidateStruct(&payload)
if err != nil {
return nil, errors.New("JSON payload failed validation: " + err.Error())
}
return &payload, nil
}
func createOrphanToken(userToken string, payload *createTokenPayload) (string, error) {
jsonData, err := json.Marshal(payload)
jsonBytes := bytes.NewBuffer(jsonData)
url := (vaultUrl + "/v1/auth/token/create-orphan")
log.Info(url)
req, err := http.NewRequest("POST", url, jsonBytes)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Vault-Token", userToken)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var clientToken string
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
//log.Info(bodyString)
clientToken = gjson.Get(bodyString, "auth.client_token").String()
//fmt.Print(clientToken)
return clientToken, nil
}
return "", errors.New("failed to get token")
}