Debian Codegraph @

spnego/http.go

raw
1 package spnego
2
3 import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "errors"
8 "fmt"
9 "io"
10 "io/ioutil"
11 "net"
12 "net/http"
13 "net/http/cookiejar"
14 "net/url"
15 "strings"
16
17 "gopkg.in/jcmturner/goidentity.v3"
18 "gopkg.in/jcmturner/gokrb5.v7/client"
19 "gopkg.in/jcmturner/gokrb5.v7/gssapi"
20 "gopkg.in/jcmturner/gokrb5.v7/keytab"
21 "gopkg.in/jcmturner/gokrb5.v7/krberror"
22 "gopkg.in/jcmturner/gokrb5.v7/service"
23 "gopkg.in/jcmturner/gokrb5.v7/types"
24 )
25
26 // Client side functionality //
27
28 // Client will negotiate authentication with a server using SPNEGO.
29 type Client struct {
30 *http.Client
31 krb5Client *client.Client
32 spn string
33 reqs []*http.Request
34 }
35
36 type redirectErr struct {
37 reqTarget *http.Request
38 }
39
40 func (e redirectErr) Error() string {
41 return fmt.Sprintf("redirect to %v", e.reqTarget.URL)
42 }
43
44 type teeReadCloser struct {
45 io.Reader
46 io.Closer
47 }
48
49 // NewClient returns an SPNEGO enabled HTTP client.
50 func NewClient(krb5Cl *client.Client, httpCl *http.Client, spn string) *Client {
51 if httpCl == nil {
52 httpCl = http.DefaultClient
53 }
54 // Add a cookie jar if there isn't one
55 if httpCl.Jar == nil {
56 httpCl.Jar, _ = cookiejar.New(nil)
57 }
58 // Add a CheckRedirect function that will execute any functional already defined and then error with a redirectErr
59 f := httpCl.CheckRedirect
60 httpCl.CheckRedirect = func(req *http.Request, via []*http.Request) error {
61 if f != nil {
62 err := f(req, via)
63 if err != nil {
64 return err
65 }
66 }
67 return redirectErr{reqTarget: req}
68 }
69 return &Client{
70 Client: httpCl,
71 krb5Client: krb5Cl,
72 spn: spn,
73 }
74 }
75
76 // Do is the SPNEGO enabled HTTP client's equivalent of the http.Client's Do method.
77 func (c *Client) Do(req *http.Request) (resp *http.Response, err error) {
78 var body bytes.Buffer
79 if req.Body != nil {
80 // Use a tee reader to capture any body sent in case we have to replay it again
81 teeR := io.TeeReader(req.Body, &body)
82 teeRC := teeReadCloser{teeR, req.Body}
83 req.Body = teeRC
84 }
85 resp, err = c.Client.Do(req)
86 if err != nil {
87 if ue, ok := err.(*url.Error); ok {
88 if e, ok := ue.Err.(redirectErr); ok {
89 // Picked up a redirect
90 e.reqTarget.Header.Del(HTTPHeaderAuthRequest)
91 c.reqs = append(c.reqs, e.reqTarget)
92 if len(c.reqs) >= 10 {
93 return resp, errors.New("stopped after 10 redirects")
94 }
95 if req.Body != nil {
96 // Refresh the body reader so the body can be sent again
97 e.reqTarget.Body = ioutil.NopCloser(&body)
98 }
99 return c.Do(e.reqTarget)
100 }
101 }
102 return resp, err
103 }
104 if respUnauthorizedNegotiate(resp) {
105 err := SetSPNEGOHeader(c.krb5Client, req, c.spn)
106 if err != nil {
107 return resp, err
108 }
109 if req.Body != nil {
110 // Refresh the body reader so the body can be sent again
111 req.Body = ioutil.NopCloser(&body)
112 }
113 return c.Do(req)
114 }
115 return resp, err
116 }
117
118 // Get is the SPNEGO enabled HTTP client's equivalent of the http.Client's Get method.
119 func (c *Client) Get(url string) (resp *http.Response, err error) {
120 req, err := http.NewRequest("GET", url, nil)
121 if err != nil {
122 return nil, err
123 }
124 return c.Do(req)
125 }
126
127 // Post is the SPNEGO enabled HTTP client's equivalent of the http.Client's Post method.
128 func (c *Client) Post(url, contentType string, body io.Reader) (resp *http.Response, err error) {
129 req, err := http.NewRequest("POST", url, body)
130 if err != nil {
131 return nil, err
132 }
133 req.Header.Set("Content-Type", contentType)
134 return c.Do(req)
135 }
136
137 // PostForm is the SPNEGO enabled HTTP client's equivalent of the http.Client's PostForm method.
138 func (c *Client) PostForm(url string, data url.Values) (resp *http.Response, err error) {
139 return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
140 }
141
142 // Head is the SPNEGO enabled HTTP client's equivalent of the http.Client's Head method.
143 func (c *Client) Head(url string) (resp *http.Response, err error) {
144 req, err := http.NewRequest("HEAD", url, nil)
145 if err != nil {
146 return nil, err
147 }
148 return c.Do(req)
149 }
150
151 func respUnauthorizedNegotiate(resp *http.Response) bool {
152 if resp.StatusCode == http.StatusUnauthorized {
153 if resp.Header.Get(HTTPHeaderAuthResponse) == HTTPHeaderAuthResponseValueKey {
154 return true
155 }
156 }
157 return false
158 }
159
160 // SetSPNEGOHeader gets the service ticket and sets it as the SPNEGO authorization header on HTTP request object.
161 // To auto generate the SPN from the request object pass a null string "".
162 func SetSPNEGOHeader(cl *client.Client, r *http.Request, spn string) error {
163 if spn == "" {
164 h := strings.TrimSuffix(strings.SplitN(r.URL.Host, ":", 2)[0], ".")
165 name, err := net.LookupCNAME(h)
166 if err == nil {
167 // Underlyng canonical name should be used for SPN
168 h = strings.TrimSuffix(name, ".")
169 }
170 spn = "HTTP/" + h
171 r.Host = h
172 }
173 cl.Log("using SPN %s", spn)
174 s := SPNEGOClient(cl, spn)
175 err := s.AcquireCred()
176 if err != nil {
177 return fmt.Errorf("could not acquire client credential: %v", err)
178 }
179 st, err := s.InitSecContext()
180 if err != nil {
181 return fmt.Errorf("could not initialize context: %v", err)
182 }
183 nb, err := st.Marshal()
184 if err != nil {
185 return krberror.Errorf(err, krberror.EncodingError, "could not marshal SPNEGO")
186 }
187 hs := "Negotiate " + base64.StdEncoding.EncodeToString(nb)
188 r.Header.Set(HTTPHeaderAuthRequest, hs)
189 return nil
190 }
191
192 // Service side functionality //
193
194 type ctxKey string
195
196 const (
197 // spnegoNegTokenRespKRBAcceptCompleted - The response on successful authentication always has this header. Capturing as const so we don't have marshaling and encoding overhead.
198 spnegoNegTokenRespKRBAcceptCompleted = "Negotiate oRQwEqADCgEAoQsGCSqGSIb3EgECAg=="
199 // spnegoNegTokenRespReject - The response on a failed authentication always has this rejection header. Capturing as const so we don't have marshaling and encoding overhead.
200 spnegoNegTokenRespReject = "Negotiate oQcwBaADCgEC"
201 // spnegoNegTokenRespIncompleteKRB5 - Response token specifying incomplete context and KRB5 as the supported mechtype.
202 spnegoNegTokenRespIncompleteKRB5 = "Negotiate oRQwEqADCgEBoQsGCSqGSIb3EgECAg=="
203 // CTXKeyAuthenticated is the request context key holding a boolean indicating if the request has been authenticated.
204 CTXKeyAuthenticated ctxKey = "github.com/jcmturner/gokrb5/CTXKeyAuthenticated"
205 // CTXKeyCredentials is the request context key holding the credentials gopkg.in/jcmturner/goidentity.v2/Identity object.
206 CTXKeyCredentials ctxKey = "github.com/jcmturner/gokrb5/CTXKeyCredentials"
207 // HTTPHeaderAuthRequest is the header that will hold authn/z information.
208 HTTPHeaderAuthRequest = "Authorization"
209 // HTTPHeaderAuthResponse is the header that will hold SPNEGO data from the server.
210 HTTPHeaderAuthResponse = "WWW-Authenticate"
211 // HTTPHeaderAuthResponseValueKey is the key in the auth header for SPNEGO.
212 HTTPHeaderAuthResponseValueKey = "Negotiate"
213 // UnauthorizedMsg is the message returned in the body when authentication fails.
214 UnauthorizedMsg = "Unauthorised.\n"
215 )
216
217 // SPNEGOKRB5Authenticate is a Kerberos SPNEGO authentication HTTP handler wrapper.
218 func SPNEGOKRB5Authenticate(inner http.Handler, kt *keytab.Keytab, settings ...func(*service.Settings)) http.Handler {
219 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
220 // Get the auth header
221 s := strings.SplitN(r.Header.Get(HTTPHeaderAuthRequest), " ", 2)
222 if len(s) != 2 || s[0] != HTTPHeaderAuthResponseValueKey {
223 // No Authorization header set so return 401 with WWW-Authenticate Negotiate header
224 w.Header().Set(HTTPHeaderAuthResponse, HTTPHeaderAuthResponseValueKey)
225 http.Error(w, UnauthorizedMsg, http.StatusUnauthorized)
226 return
227 }
228
229 // Set up the SPNEGO GSS-API mechanism
230 var spnego *SPNEGO
231 h, err := types.GetHostAddress(r.RemoteAddr)
232 if err == nil {
233 // put in this order so that if the user provides a ClientAddress it will override the one here.
234 o := append([]func(*service.Settings){service.ClientAddress(h)}, settings...)
235 spnego = SPNEGOService(kt, o...)
236 } else {
237 spnego = SPNEGOService(kt, settings...)
238 spnego.Log("%s - SPNEGO could not parse client address: %v", r.RemoteAddr, err)
239 }
240
241 // Decode the header into an SPNEGO context token
242 b, err := base64.StdEncoding.DecodeString(s[1])
243 if err != nil {
244 spnegoNegotiateKRB5MechType(spnego, w, "%s - SPNEGO error in base64 decoding negotiation header: %v", r.RemoteAddr, err)
245 return
246 }
247 var st SPNEGOToken
248 err = st.Unmarshal(b)
249 if err != nil {
250 spnegoNegotiateKRB5MechType(spnego, w, "%s - SPNEGO error in unmarshaling SPNEGO token: %v", r.RemoteAddr, err)
251 return
252 }
253
254 // Validate the context token
255 authed, ctx, status := spnego.AcceptSecContext(&st)
256 if status.Code != gssapi.StatusComplete && status.Code != gssapi.StatusContinueNeeded {
257 spnegoResponseReject(spnego, w, "%s - SPNEGO validation error: %v", r.RemoteAddr, status)
258 return
259 }
260 if status.Code == gssapi.StatusContinueNeeded {
261 spnegoNegotiateKRB5MechType(spnego, w, "%s - SPNEGO GSS-API continue needed", r.RemoteAddr)
262 return
263 }
264 if authed {
265 id := ctx.Value(CTXKeyCredentials).(goidentity.Identity)
266 requestCtx := r.Context()
267 requestCtx = context.WithValue(requestCtx, CTXKeyCredentials, id)
268 requestCtx = context.WithValue(requestCtx, CTXKeyAuthenticated, ctx.Value(CTXKeyAuthenticated))
269 spnegoResponseAcceptCompleted(spnego, w, "%s %s@%s - SPNEGO authentication succeeded", r.RemoteAddr, id.UserName(), id.Domain())
270 inner.ServeHTTP(w, r.WithContext(requestCtx))
271 } else {
272 spnegoResponseReject(spnego, w, "%s - SPNEGO Kerberos authentication failed", r.RemoteAddr)
273 return
274 }
275 })
276 }
277
278 func spnegoNegotiateKRB5MechType(s *SPNEGO, w http.ResponseWriter, format string, v ...interface{}) {
279 s.Log(format, v...)
280 w.Header().Set(HTTPHeaderAuthResponse, spnegoNegTokenRespIncompleteKRB5)
281 http.Error(w, UnauthorizedMsg, http.StatusUnauthorized)
282 }
283
284 func spnegoResponseReject(s *SPNEGO, w http.ResponseWriter, format string, v ...interface{}) {
285 s.Log(format, v...)
286 w.Header().Set(HTTPHeaderAuthResponse, spnegoNegTokenRespReject)
287 http.Error(w, UnauthorizedMsg, http.StatusUnauthorized)
288 }
289
290 func spnegoResponseAcceptCompleted(s *SPNEGO, w http.ResponseWriter, format string, v ...interface{}) {
291 s.Log(format, v...)
292 w.Header().Set(HTTPHeaderAuthResponse, spnegoNegTokenRespKRBAcceptCompleted)
293 }