1 /* Copyright 2009 Justin Erenkrantz and Greg Stein
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 #include "auth_spnego.h"
18 #ifdef SERF_HAVE_SPNEGO
20 /** These functions implement SPNEGO-based Kerberos and NTLM authentication,
21 * using either GSS-API (RFC 2743) or SSPI on Windows.
22 * The HTTP message exchange is documented in RFC 4559.
26 #include <serf_private.h>
27 #include <auth/auth.h>
30 #include <apr_base64.h>
31 #include <apr_strings.h>
34 ** - send session key directly on new connections where we already know
35 ** the server requires Kerberos authn.
36 ** - Add a way for serf to give detailed error information back to the
40 /* Authentication over HTTP using Kerberos
42 * Kerberos involves three servers:
43 * - Authentication Server (AS): verifies users during login
44 * - Ticket-Granting Server (TGS): issues proof of identity tickets
48 * 0. User logs in to the AS and receives a TGS ticket. On workstations
49 * where the login program doesn't support Kerberos, the user can use
54 * C <-- S: 401 Authentication Required
55 * WWW-Authenticate: Negotiate
57 * -> app contacts the TGS to request a session key for the HTTP service
58 * @ target host. The returned session key is encrypted with the HTTP
59 * service's secret key, so we can safely send it to the server.
62 * Authorization: Negotiate <Base64 encoded session key>
63 * gss_api_ctx->state = gss_api_auth_in_progress;
66 * WWW-Authenticate: Negotiate <Base64 encoded server
67 * authentication data>
69 * -> The server returned an (optional) key to proof itself to us. We check this
70 * key with the TGS again. If it checks out, we can return the response
71 * body to the application.
73 * Note: It's possible that the server returns 401 again in step 2, if the
74 * Kerberos context isn't complete yet. This means there is 3rd step
75 * where we'll send a request with an Authorization header to the
76 * server. Some (simple) tests with mod_auth_kerb and MIT Kerberos 5 show
79 * Depending on the type of HTTP server, this handshake is required for either
80 * every new connection, or for every new request! For more info see the next
81 * comment on authn_persistence_state_t.
83 * Note: Step 1 of the handshake will only happen on the first connection, once
84 * we know the server requires Kerberos authentication, the initial requests
85 * on the other connections will include a session key, so we start at
86 * step 2 in the handshake.
87 * ### TODO: Not implemented yet!
90 /* Current state of the authentication of the current request. */
92 gss_api_auth_not_started,
93 gss_api_auth_in_progress,
94 gss_api_auth_completed,
98 authn_persistence_state_t: state that indicates if we are talking with a
99 server that requires authentication only of the first request (stateful),
100 or of each request (stateless).
102 INIT: Begin state. Authenticating the first request on this connection.
103 UNDECIDED: we haven't identified the server yet, assume STATEFUL for now.
104 Pipeline mode disabled, requests are sent only after the response off the
105 previous request arrived.
106 STATELESS: we know the server requires authentication for each request.
107 On all new requests add the Authorization header with an initial SPNEGO
108 token (created per request).
109 To keep things simple, keep the connection in one by one mode.
110 (otherwise we'd have to keep a queue of gssapi context objects to match
111 the Negotiate header of the response with the session initiated by the
113 This state is an final state.
114 STATEFUL: alright, we have authenticated the connection and for the server
115 that is enough. Don't add an Authorization header to new requests.
116 Serf will switch to pipelined mode.
117 This state is not a final state, although in practical scenario's it will
118 be. When we receive a 40x response from the server switch to STATELESS
121 We start in state init for the first request until it is authenticated.
123 The rest of the state machine starts with the arrival of the response to the
124 second request, and then goes on with each response:
127 | INIT | C --> S: GET request in response to 40x of the server
128 -------- add [Proxy]-Authorization header
132 | UNDECIDED| C --> S: GET request, assume stateful,
133 ------------ no [Proxy]-Authorization header
136 |------------------------------------------------
138 | C <-- S: 40x Authentication | C <-- S: 200 OK
142 ------------- ------------
143 ->| STATELESS |<------------------------------| STATEFUL |<--
144 | ------------- C <-- S: 40x ------------ |
145 * | | Authentication | | 200 OK
155 } authn_persistence_state_t;
158 /* HTTP Service name, used to get the session key. */
159 #define KRB_HTTP_SERVICE "HTTP"
161 /* Stores the context information related to Kerberos authentication. */
167 serf__spnego_context_t *gss_ctx;
169 /* Current state of the authentication cycle. */
170 gss_api_auth_state state;
172 /* Current persistence state. */
173 authn_persistence_state_t pstate;
179 /* On the initial 401 response of the server, request a session key from
180 the Kerberos KDC to pass to the server, proving that we are who we
181 claim to be. The session key can only be used with the HTTP service
182 on the target host. */
184 gss_api_get_credentials(serf_connection_t *conn,
185 char *token, apr_size_t token_len,
186 const char *hostname,
187 const char **buf, apr_size_t *buf_len,
188 gss_authn_info_t *gss_info)
190 serf__spnego_buffer_t input_buf;
191 serf__spnego_buffer_t output_buf;
192 apr_status_t status = APR_SUCCESS;
194 /* If the server sent us a token, pass it to gss_init_sec_token for
197 input_buf.value = token;
198 input_buf.length = token_len;
201 input_buf.length = 0;
204 /* Establish a security context to the server. */
205 status = serf__spnego_init_sec_context(
208 KRB_HTTP_SERVICE, hostname,
217 if (output_buf.length == 0) {
218 gss_info->state = gss_api_auth_completed;
220 gss_info->state = gss_api_auth_in_progress;
224 gss_info->state = gss_api_auth_in_progress;
225 status = APR_SUCCESS;
231 /* Return the session key to our caller. */
232 *buf = output_buf.value;
233 *buf_len = output_buf.length;
238 /* do_auth is invoked in two situations:
239 - when a response from a server is received that contains an authn header
240 (either from a 40x or 2xx response)
241 - when a request is prepared on a connection with stateless authentication.
243 Read the header sent by the server (if any), invoke the gssapi authn
244 code and use the resulting Server Ticket on the next request to the
249 gss_authn_info_t *gss_info,
250 serf_connection_t *conn,
251 serf_request_t *request,
252 const char *auth_hdr,
255 serf_context_t *ctx = conn->ctx;
256 serf__authn_info_t *authn_info;
257 const char *tmp = NULL;
259 apr_size_t tmp_len = 0, token_len = 0;
263 authn_info = serf__get_authn_info_for_server(conn);
265 authn_info = &ctx->proxy_authn_info;
268 /* Is this a response from a host/proxy? auth_hdr should always be set. */
269 if (code && auth_hdr) {
270 const char *space = NULL;
271 /* The server will return a token as attribute to the Negotiate key.
272 Negotiate YGwGCSqGSIb3EgECAgIAb10wW6ADAgEFoQMCAQ+iTzBNoAMCARCiRgREa6
273 mouMBAMFqKVdTGtfpZNXKzyw4Yo1paphJdIA3VOgncaoIlXxZLnkHiIHS2v65pVvrp
274 bRIyjF8xve9HxpnNIucCY9c=
276 Read this base64 value, decode it and validate it so we're sure the
277 server is who we expect it to be. */
278 space = strchr(auth_hdr, ' ');
281 token = apr_palloc(pool, apr_base64_decode_len(space + 1));
282 token_len = apr_base64_decode(token, space + 1);
285 /* This is a new request, not a retry in response to a 40x of the
287 Only add the Authorization header if we know the server requires
288 per-request authentication (stateless). */
289 if (gss_info->pstate != pstate_stateless)
293 switch(gss_info->pstate) {
295 /* Nothing to do here */
297 case pstate_undecided: /* Fall through */
298 case pstate_stateful:
300 /* Switch to stateless mode, from now on handle authentication
301 of each request with a new gss context. This is easiest to
302 manage when sending requests one by one. */
303 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
304 "Server requires per-request SPNEGO authn, "
305 "switching to stateless mode.\n");
307 gss_info->pstate = pstate_stateless;
308 serf_connection_set_max_outstanding_requests(conn, 1);
311 case pstate_stateless:
312 /* Nothing to do here */
316 if (request->auth_baton && !token) {
317 /* We provided token with this request, but server responded with empty
318 authentication header. This means server rejected our credentials.
319 XXX: Probably we need separate error code for this case like
320 SERF_ERROR_AUTHN_CREDS_REJECTED? */
321 return SERF_ERROR_AUTHN_FAILED;
324 /* If the server didn't provide us with a token, start with a new initial
325 step in the SPNEGO authentication. */
327 serf__spnego_reset_sec_context(gss_info->gss_ctx);
328 gss_info->state = gss_api_auth_not_started;
332 status = gss_api_get_credentials(conn,
334 conn->host_info.hostname,
338 char *proxy_host = conn->ctx->proxy_address->hostname;
339 status = gss_api_get_credentials(conn,
340 token, token_len, proxy_host,
347 /* On the next request, add an Authorization header. */
349 serf__encode_auth_header(&gss_info->value, authn_info->scheme->name,
353 gss_info->header = (peer == HOST) ?
354 "Authorization" : "Proxy-Authorization";
361 serf__init_spnego(int code,
368 /* A new connection is created to a server that's known to use
371 serf__init_spnego_connection(const serf__authn_scheme_t *scheme,
373 serf_connection_t *conn,
376 serf_context_t *ctx = conn->ctx;
377 serf__authn_info_t *authn_info;
378 gss_authn_info_t *gss_info = NULL;
380 /* For proxy authentication, reuse the gss context for all connections.
381 For server authentication, create a new gss context per connection. */
383 authn_info = &conn->authn_info;
385 authn_info = &ctx->proxy_authn_info;
387 gss_info = authn_info->baton;
392 gss_info = apr_pcalloc(conn->pool, sizeof(*gss_info));
393 gss_info->pool = conn->pool;
394 gss_info->state = gss_api_auth_not_started;
395 gss_info->pstate = pstate_init;
396 status = serf__spnego_create_sec_context(&gss_info->gss_ctx, scheme,
397 gss_info->pool, pool);
401 authn_info->baton = gss_info;
404 /* Make serf send the initial requests one by one */
405 serf_connection_set_max_outstanding_requests(conn, 1);
407 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
408 "Initialized Kerberos context for this connection.\n");
413 /* A 40x response was received, handle the authentication. */
415 serf__handle_spnego_auth(int code,
416 serf_request_t *request,
417 serf_bucket_t *response,
418 const char *auth_hdr,
419 const char *auth_attr,
423 serf_connection_t *conn = request->conn;
424 serf_context_t *ctx = conn->ctx;
425 gss_authn_info_t *gss_info = (code == 401) ? conn->authn_info.baton :
426 ctx->proxy_authn_info.baton;
428 return do_auth(code == 401 ? HOST : PROXY,
437 /* Setup the authn headers on this request message. */
439 serf__setup_request_spnego_auth(peer_t peer,
441 serf_connection_t *conn,
442 serf_request_t *request,
445 serf_bucket_t *hdrs_bkt)
447 serf_context_t *ctx = conn->ctx;
448 gss_authn_info_t *gss_info = (peer == HOST) ? conn->authn_info.baton :
449 ctx->proxy_authn_info.baton;
451 /* If we have an ongoing authentication handshake, the handler of the
452 previous response will have created the authn headers for this request
454 if (gss_info && gss_info->header && gss_info->value) {
455 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
456 "Set Negotiate authn header on retried request.\n");
458 serf_bucket_headers_setn(hdrs_bkt, gss_info->header,
461 /* Remember that we're using this request for authentication
463 request->auth_baton = (void*) TRUE;
465 /* We should send each token only once. */
466 gss_info->header = NULL;
467 gss_info->value = NULL;
472 switch (gss_info->pstate) {
474 /* We shouldn't normally arrive here, do nothing. */
476 case pstate_undecided: /* fall through */
477 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
478 "Assume for now that the server supports persistent "
479 "SPNEGO authentication.\n");
480 /* Nothing to do here. */
482 case pstate_stateful:
483 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
484 "SPNEGO on this connection is persistent, "
485 "don't set authn header on next request.\n");
486 /* Nothing to do here. */
488 case pstate_stateless:
492 /* Authentication on this connection is known to be stateless.
493 Add an initial Negotiate token for the server, to bypass the
494 40x response we know we'll otherwise receive.
495 (RFC 4559 section 4.2) */
496 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
497 "Add initial Negotiate header to request.\n");
499 status = do_auth(peer,
504 0l, /* no response authn header */
509 serf_bucket_headers_setn(hdrs_bkt, gss_info->header,
512 /* Remember that we're using this request for authentication
514 request->auth_baton = (void*) TRUE;
516 /* We should send each token only once. */
517 gss_info->header = NULL;
518 gss_info->value = NULL;
527 * Baton passed to the get_auth_header callback function.
530 const char *hdr_name;
531 const char *auth_name;
532 const char *hdr_value;
534 } get_auth_header_baton_t;
537 get_auth_header_cb(void *baton,
541 get_auth_header_baton_t *b = baton;
543 /* We're only interested in xxxx-Authenticate headers. */
544 if (strcasecmp(key, b->hdr_name) != 0)
547 /* Check if header value starts with interesting auth name. */
548 if (strncmp(header, b->auth_name, strlen(b->auth_name)) == 0) {
549 /* Save interesting header value and stop iteration. */
550 b->hdr_value = apr_pstrdup(b->pool, header);
558 get_auth_header(serf_bucket_t *hdrs,
559 const char *hdr_name,
560 const char *auth_name,
563 get_auth_header_baton_t b;
565 b.auth_name = hdr_name;
566 b.hdr_name = auth_name;
570 serf_bucket_headers_do(hdrs, get_auth_header_cb, &b);
575 /* Function is called when 2xx responses are received. Normally we don't
576 * have to do anything, except for the first response after the
577 * authentication handshake. This specific response includes authentication
578 * data which should be validated by the client (mutual authentication).
581 serf__validate_response_spnego_auth(const serf__authn_scheme_t *scheme,
584 serf_connection_t *conn,
585 serf_request_t *request,
586 serf_bucket_t *response,
589 serf_context_t *ctx = conn->ctx;
590 gss_authn_info_t *gss_info;
591 const char *auth_hdr_name;
593 /* TODO: currently this function is only called when a response includes
594 an Authenticate header. This header is optional. If the server does
595 not provide this header on the first 2xx response, we will not promote
596 the connection from undecided to stateful. This won't break anything,
597 but means we stay in non-pipelining mode. */
598 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
599 "Validate Negotiate response header.\n");
602 gss_info = conn->authn_info.baton;
603 auth_hdr_name = "WWW-Authenticate";
605 gss_info = ctx->proxy_authn_info.baton;
606 auth_hdr_name = "Proxy-Authenticate";
609 if (gss_info->state != gss_api_auth_completed) {
611 const char *auth_hdr_val;
614 hdrs = serf_bucket_response_get_headers(response);
615 auth_hdr_val = get_auth_header(hdrs, auth_hdr_name, scheme->name,
619 status = do_auth(peer, code, gss_info, conn, request, auth_hdr_val,
625 /* No Authenticate headers, nothing to validate: authentication
627 gss_info->state = gss_api_auth_completed;
629 serf__log_skt(AUTH_VERBOSE, __FILE__, conn->skt,
630 "SPNEGO handshake completed.\n");
634 if (gss_info->state == gss_api_auth_completed) {
635 switch(gss_info->pstate) {
637 /* Authentication of the first request is done. */
638 gss_info->pstate = pstate_undecided;
640 case pstate_undecided:
641 /* The server didn't request for authentication even though
642 we didn't add an Authorization header to previous
643 request. That means it supports persistent authentication. */
644 gss_info->pstate = pstate_stateful;
645 serf_connection_set_max_outstanding_requests(conn, 0);
648 /* Nothing to do here. */
656 #endif /* SERF_HAVE_SPNEGO */