-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
356 lines (333 loc) · 10.5 KB
/
main.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package main
import (
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/user"
"runtime"
"strconv"
"syscall"
"time"
"github.com/SermoDigital/jose/crypto"
"github.com/SermoDigital/jose/jws"
"github.com/golang/glog"
"github.com/msteinert/pam"
"golang.org/x/sys/unix"
)
type Config struct {
TokenExpiresIn int
SigningKey *string
Audience *string
ServerName *string
BindAddress *string
BindPort *string
TlsKeyFile *string
TlsCertFile *string
DisableMlock *bool
PAMServiceName *string
}
type User struct {
Username string `json:"username"`
Uid string `json:"uid"`
Groups []string `json:"groups"`
}
type Status struct {
Authenticated bool `json:"authenticated"`
User *User `json:"user,omitempty"`
}
type Response struct {
ApiVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Status *Status `json:"status"`
}
type Spec struct {
Token string `json:"token"`
}
type AuthRequest struct {
ApiVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Spec *Spec `json:"spec"`
}
func newConfig() *Config {
c := &Config{}
empty := ""
port := "8080" //default port
c.BindAddress = &empty
c.BindPort = &port
tokenExpiry, err := strconv.Atoi(os.Getenv("PAMHOOK_TOKEN_EXPIRES_IN"))
if err != nil {
tokenExpiry = 10 //default token expiry
}
c.TokenExpiresIn = tokenExpiry
signingKey := os.Getenv("PAMHOOK_SIGNING_KEY")
c.SigningKey = &signingKey
audience := os.Getenv("PAMHOOK_AUDIENCE")
c.Audience = &audience
serverName := os.Getenv("PAMHOOK_SERVERNAME")
c.ServerName = &serverName
tlsKeyFile := os.Getenv("PAMHOOK_TLS_KEY_FILE")
c.TlsKeyFile = &tlsKeyFile
tlsCertFile := os.Getenv("PAMHOOK_TLS_CERT_FILE")
c.TlsCertFile = &tlsCertFile
pamServiceName := os.Getenv("PAMHOOK_PAM_SERVICE_NAME")
c.PAMServiceName = &pamServiceName
// Have to take a pointer so we need a new var.
disableMlock := false
c.DisableMlock = &disableMlock
return c
}
func lookupGroups(username string) ([]string, error) {
userS, err := user.Lookup(username)
if err != nil {
return []string{}, err
}
groups, err := userS.GroupIds()
if err != nil {
return []string{}, err
}
for i, group := range groups {
group, err := user.LookupGroupId(group)
if err == nil {
groups[i] = group.Name
}
}
return groups, nil
}
func NewUser(username string) (*User, error) {
userStruct := User{}
userS, err := user.Lookup(username)
if err != nil {
return nil, err
}
groups, err := lookupGroups(username)
if err != nil {
return nil, err
}
userStruct.Username = userS.Username
userStruct.Uid = userS.Uid
userStruct.Groups = groups
return &userStruct, nil
}
func NewStatus(userS *User, authenticated bool) *Status {
status := Status{}
status.Authenticated = authenticated
status.User = userS
return &status
}
func NewResponse(status *Status) *Response {
response := Response{}
response.ApiVersion = "authentication.k8s.io/v1beta1"
response.Kind = "TokenReview"
response.Status = status
return &response
}
func userNameFromToken(token string, signingKey string) (string, error) {
w, err := jws.ParseJWT([]byte(token))
if err != nil {
return "", err
}
username := w.Claims().Get("username")
if err := w.Validate([]byte(signingKey), crypto.SigningMethodHS256); err != nil {
return "", err
}
return username.(string), nil
}
func authenticateUser(pamServiceName *string, username string, password string) error {
glog.V(3).Infof("Received request from user: %s", username)
tx, err := pam.StartFunc(*pamServiceName, username, func(s pam.Style, msg string) (string, error) {
return password, nil
})
if err != nil {
return err
}
err = tx.Authenticate(0)
if err != nil {
return err
}
err = tx.AcctMgmt(pam.Silent)
if err != nil {
return err
}
runtime.GC()
return nil
}
func createToken(username string, c *Config, tokenExpiresIn int) (string,
error) {
claims := jws.Claims{
"username": username,
}
now := time.Now().UTC()
claims.SetAudience(*c.Audience)
claims.SetIssuedAt(now)
claims.SetIssuer(*c.ServerName)
claims.SetExpiration(now.Add(time.Minute *
time.Duration(tokenExpiresIn)))
j := jws.NewJWT(claims, crypto.SigningMethodHS256)
b, err := j.Serialize([]byte(*c.SigningKey))
if err != nil {
return "", err
}
return string(b), nil
}
func createResponseFromToken(token string, signingKey string) []byte {
username, err := userNameFromToken(token, signingKey)
valid := true
if err != nil {
valid = false
glog.Errorf("Token supplied is invalid due to: %s", err)
}
uS, err := NewUser(username)
if err != nil {
valid = false
glog.Errorf("The user: %s details cannot be retrieved due to: %s", username, err)
}
status := NewStatus(uS, valid)
response := NewResponse(status)
json, err := json.Marshal(response)
if err == nil {
return json
} else {
return []byte("")
}
}
func heartbeatHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
status := http.StatusOK
glog.V(2).Infof("%s %s: %s, %d", r.Method, r.URL.Path, r.UserAgent(), status)
fmt.Fprintf(w, "ok\n")
}
}
func authenticateHandler(c *Config) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
status := http.StatusOK
glog.V(2).Infof("%s %s: %s, %d", r.Method, r.URL.Path, r.UserAgent(), status)
var a AuthRequest
if err != nil {
fmt.Fprintln(w, "invalid request")
return
}
err = json.Unmarshal(body, &a)
if err != nil {
fmt.Fprintln(w, "invalid request")
return
}
resp := createResponseFromToken(a.Spec.Token, *c.SigningKey)
fmt.Fprintf(w, "%s\n", resp)
}
}
func tokenHandler(c *Config) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
tokenExpiresIn := c.TokenExpiresIn
if v := r.URL.Query().Get("token-expires-in"); v != "" {
if t, err := strconv.Atoi(v); err != nil {
glog.Errorf("Got a non int token expiry: %s", v)
http.Error(w, fmt.Sprintf("'%s' is not a valid integer", v),
http.StatusBadRequest)
return
} else {
if t > tokenExpiresIn {
glog.V(2).Infof("Ignoring token expiry %d, which is greater than"+
"configured token expiry: ", tokenExpiresIn)
http.Error(w, fmt.Sprintf("%d is greater than the configured"+
" token-expiry", t), http.StatusBadRequest)
return
} else {
tokenExpiresIn = t
glog.V(3).Infof("Overriding configured token with: %d", tokenExpiresIn)
}
}
}
status := http.StatusOK
if !ok {
status = http.StatusNotFound
glog.V(2).Infof("%s %s: %s, %d", r.Method, r.URL.Path, r.UserAgent(), status)
http.Error(w, "Supply username and password", http.StatusNotFound)
return
}
if err := authenticateUser(c.PAMServiceName, username, password); err != nil {
status = http.StatusForbidden
glog.V(2).Infof("%s %s: %s, %s, %d", r.Method, r.URL.Path, r.UserAgent(),
r.URL.Query(), status)
glog.Errorf("Authenticating user failed with: %s", err)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
b, err := createToken(username, c, tokenExpiresIn)
if err != nil {
status = http.StatusInternalServerError
glog.V(2).Infof("%s %s: %s, %v, %d", r.Method, r.URL.Path, r.UserAgent(),
r.URL.Query(), status)
glog.Errorf("%s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
glog.V(2).Infof("%s %s: %s, %v, %d", r.Method, r.URL.Path, r.UserAgent(),
r.URL.Query(), status)
w.Header().Set("Authorization", fmt.Sprintf("Bearer %s", b))
fmt.Fprintf(w, "%s\n", b)
}
}
func main() {
u, _ := user.Current()
config := newConfig()
flag.IntVar(&config.TokenExpiresIn, "token-expires-in", config.TokenExpiresIn, "Specifies how long the token is valid for in minutes, configurable via PAMHOOK_TOKEN_EXPIRES_IN environment variable")
flag.StringVar(config.SigningKey, "signing-key", *config.SigningKey, "Key for signing the token (required), configurable via PAMHOOK_SIGNING_KEY environment variable")
flag.StringVar(config.Audience, "audience", *config.Audience, "Server that consumes the pam_hook endpoint, configurable via PAMHOOK_AUDIENCE environment variable")
flag.StringVar(config.ServerName, "server-name", *config.ServerName, "The domain name for pam-hook, configurable via PAMHOOK_SERVERNAME environment variable")
flag.StringVar(config.BindAddress, "bind-address", *config.BindAddress, "Address to bind pam_hook to")
flag.StringVar(config.BindPort, "bind-port", *config.BindPort, "")
flag.StringVar(config.TlsKeyFile, "key-file", *config.TlsKeyFile, "Absolute path to TLS private key file, configurable via PAMHOOK_TLS_KEY_FILE environment variable")
flag.StringVar(config.TlsCertFile, "cert-file", *config.TlsCertFile, "Absolute path to TLS CA certificate, configurable via PAMHOOK_TLS_CERT_FILE environment variable")
flag.StringVar(config.PAMServiceName, "pam-service-name", *config.PAMServiceName, "PAM service name against which to perform user authentication during token creation, configurable via PAMHOOK_PAM_SERVICE_NAME environment variable")
flag.BoolVar(config.DisableMlock, "disable-mlock", *config.DisableMlock, "Disable calling sys mlock")
flag.Set("logtostderr", "true")
flag.Set("v", "2")
flag.Parse()
defer glog.Flush()
if u.Uid != "0" {
fmt.Fprintln(os.Stderr, "run pam_hook as root")
os.Exit(1)
}
if *config.TlsKeyFile == "" {
fmt.Fprintln(os.Stderr, "Please provide a path to a tls private key file")
os.Exit(1)
}
if *config.TlsCertFile == "" {
fmt.Fprintln(os.Stderr, "Please provide a path to a tls CA certificate")
os.Exit(1)
}
if *(config.SigningKey) == "" {
fmt.Fprintln(os.Stderr, "Please provide a signing key")
os.Exit(1)
}
if config.TokenExpiresIn == 0 {
fmt.Fprintln(os.Stderr, "Please provide a token expiry")
os.Exit(1)
}
if !*config.DisableMlock {
if err := unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE); err != nil {
fmt.Fprintf(os.Stderr, "Unable to lock memory: %v", err)
os.Exit(1)
}
}
http.HandleFunc("/heartbeat", heartbeatHandler())
http.HandleFunc("/token", tokenHandler(config))
http.HandleFunc("/authenticate", authenticateHandler(config))
bind := *config.BindAddress + ":" + *config.BindPort
glog.Infof("Starting pam_hook on %s", bind)
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
}
server := &http.Server{Addr: bind, Handler: nil, TLSConfig: cfg}
err := server.ListenAndServeTLS(*config.TlsCertFile, *config.TlsKeyFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to start pamhook due to: %s", err)
os.Exit(1)
}
}