Debian Codegraph @

service/http.go

raw symbols SCIP
1 package service
2
3 import (
4 "context"
5 "encoding/base64"
6 "fmt"
7 "log"
8 "net/http"
9 "strings"
10
11 "gopkg.in/jcmturner/gokrb5.v5/gssapi"
12 "gopkg.in/jcmturner/gokrb5.v5/keytab"
13 )
14
15 // POTENTIAL BREAKING CHANGE notice. Context keys used will change to a name-spaced strings to avoid clashes.
16 // If you are using the constants service.CTXKeyAuthenticated and service.CTXKeyCredentials
17 // defined below when retrieving data from the request context your code will be unaffected.
18 // However if, for example, you are retrieving context like this: r.Context().Value(1) then
19 // you will need to update to replace the 1 with service.CTXKeyCredentials.
20 type ctxKey int
21
22 const (
23 // spnegoNegTokenRespKRBAcceptCompleted - The response on successful authentication always has this header. Capturing as const so we don't have marshaling and encoding overhead.
24 spnegoNegTokenRespKRBAcceptCompleted = "Negotiate oRQwEqADCgEAoQsGCSqGSIb3EgECAg=="
25 // spnegoNegTokenRespReject - The response on a failed authentication always has this rejection header. Capturing as const so we don't have marshaling and encoding overhead.
26 spnegoNegTokenRespReject = "Negotiate oQcwBaADCgEC"
27 // CTXKeyAuthenticated is the request context key holding a boolean indicating if the request has been authenticated.
28 CTXKeyAuthenticated ctxKey = 0
29 // CTXKeyCredentials is the request context key holding the credentials gopkg.in/jcmturner/goidentity.v2/Identity object.
30 CTXKeyCredentials ctxKey = 1
31 // HTTPHeaderAuthRequest is the header that will hold authn/z information.
32 HTTPHeaderAuthRequest = "Authorization"
33 // HTTPHeaderAuthResponse is the header that will hold SPNEGO data from the server.
34 HTTPHeaderAuthResponse = "WWW-Authenticate"
35 // HTTPHeaderAuthResponseValueKey is the key in the auth header for SPNEGO.
36 HTTPHeaderAuthResponseValueKey = "Negotiate"
37 // UnauthorizedMsg is the message returned in the body when authentication fails.
38 UnauthorizedMsg = "Unauthorised.\n"
39 )
40
41 // SPNEGOKRB5Authenticate is a Kerberos SPNEGO authentication HTTP handler wrapper.
42 //
43 // kt - keytab for the service user
44 //
45 // ktprinc - keytab principal override for the service.
46 // The service looks for this principal in the keytab to use to decrypt tickets.
47 // If "" is passed as ktprinc then the principal will be automatically derived
48 // from the service name (SName) and realm in the ticket the service is trying to decrypt.
49 // This is often sufficient if you create the SPN in MIT KDC with: /usr/sbin/kadmin.local -q "add_principal HTTP/<fqdn>"
50 // When Active Directory is used for the KDC this may need to be the account name you have set the SPN against
51 // (setspn.exe -a "HTTP/<fqdn>" <account name>)
52 // If you are unsure run:
53 //
54 // klist -k <service's keytab file>
55 //
56 // and use the value from the Principal column for the keytab entry the service should use.
57 func SPNEGOKRB5Authenticate(f http.Handler, kt keytab.Keytab, ktprinc string, requireHostAddr bool, l *log.Logger) http.Handler {
58 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
59 s := strings.SplitN(r.Header.Get(HTTPHeaderAuthRequest), " ", 2)
60 if len(s) != 2 || s[0] != HTTPHeaderAuthResponseValueKey {
61 w.Header().Set(HTTPHeaderAuthResponse, HTTPHeaderAuthResponseValueKey)
62 w.WriteHeader(401)
63 w.Write([]byte(UnauthorizedMsg))
64 return
65 }
66 b, err := base64.StdEncoding.DecodeString(s[1])
67 if err != nil {
68 rejectSPNEGO(w, l, fmt.Sprintf("%v - SPNEGO error in base64 decoding negotiation header: %v", r.RemoteAddr, err))
69 return
70 }
71 var spnego gssapi.SPNEGO
72 err = spnego.Unmarshal(b)
73 if !spnego.Init {
74 rejectSPNEGO(w, l, fmt.Sprintf("%v - SPNEGO negotiation token is not a NegTokenInit: %v", r.RemoteAddr, err))
75 return
76 }
77 if !spnego.NegTokenInit.MechTypes[0].Equal(gssapi.MechTypeOIDKRB5) && !spnego.NegTokenInit.MechTypes[0].Equal(gssapi.MechTypeOIDMSLegacyKRB5) {
78 rejectSPNEGO(w, l, fmt.Sprintf("%v - SPNEGO OID of MechToken is not of type KRB5", r.RemoteAddr))
79 return
80 }
81 var mt gssapi.MechToken
82 err = mt.Unmarshal(spnego.NegTokenInit.MechToken)
83 if err != nil {
84 rejectSPNEGO(w, l, fmt.Sprintf("%v - SPNEGO error unmarshaling MechToken: %v", r.RemoteAddr, err))
85 return
86 }
87 if !mt.IsAPReq() {
88 rejectSPNEGO(w, l, fmt.Sprintf("%v - MechToken does not contain an AP_REQ - KRB_AP_ERR_MSG_TYPE", r.RemoteAddr))
89 return
90 }
91
92 if ok, creds, err := ValidateAPREQ(mt.APReq, kt, ktprinc, r.RemoteAddr, requireHostAddr); ok {
93 ctx := r.Context()
94 ctx = context.WithValue(ctx, CTXKeyCredentials, creds)
95 ctx = context.WithValue(ctx, CTXKeyAuthenticated, true)
96 if l != nil {
97 l.Printf("%v %s@%s - SPNEGO authentication succeeded", r.RemoteAddr, creds.Username, creds.Realm)
98 }
99 spnegoResponseAcceptCompleted(w)
100 f.ServeHTTP(w, r.WithContext(ctx))
101 } else {
102 rejectSPNEGO(w, l, fmt.Sprintf("%v - SPNEGO Kerberos authentication failed: %v", r.RemoteAddr, err))
103 return
104 }
105 })
106 }
107
108 // Set the headers for a rejected SPNEGO negotiation and return an unauthorized status code.
109 func rejectSPNEGO(w http.ResponseWriter, l *log.Logger, logMsg string) {
110 if l != nil {
111 l.Println(logMsg)
112 }
113 spnegoResponseReject(w)
114 }
115
116 func spnegoResponseReject(w http.ResponseWriter) {
117 w.Header().Set(HTTPHeaderAuthResponse, spnegoNegTokenRespReject)
118 w.WriteHeader(http.StatusUnauthorized)
119 w.Write([]byte(UnauthorizedMsg))
120 }
121
122 func spnegoResponseAcceptCompleted(w http.ResponseWriter) {
123 w.Header().Set(HTTPHeaderAuthResponse, spnegoNegTokenRespKRBAcceptCompleted)
124 }