- note_kerb_auth_failure() renamed to set_kerb_auth_headers()
[mod_auth_kerb.cvs/.git] / src / mod_auth_kerb.c
index 9263f82..eb7e084 100644 (file)
  *   Ludek Sulak <xsulak@fi.muni.cz>
  */
 
-/* ====================================================================
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
+/*
+ * Copyright (c) 2004 Masarykova universita
+ * (Masaryk University, Brno, Czech Republic)
+ * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * modification, are permitted provided that the following conditions are met:
  *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
+ * 1. Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
  *
  * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
+ * 3. Neither the name of the University nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
  */
 
 #ident "$Id$"
 
 #include "config.h"
 
-#define MODAUTHKERB_VERSION "5.0-rc3"
+#define MODAUTHKERB_VERSION "5.0-rc4"
 
 #ifndef APXS1
 #include "ap_compat.h"
@@ -123,6 +97,7 @@ module AP_MODULE_DECLARE_DATA auth_kerb_module;
 #define MK_TABLE_GET ap_table_get
 #define MK_USER r->connection->user
 #define MK_AUTH_TYPE r->connection->ap_auth_type
+#define PROXYREQ_PROXY STD_PROXY
 #else
 #define MK_POOL apr_pool_t
 #define MK_TABLE_GET apr_table_get
@@ -151,6 +126,10 @@ typedef struct {
 #endif
 } kerb_auth_config;
 
+static void
+set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
+                      int use_krb4, int use_krb5pwd, char *negotiate_ret_value);
+
 static const char*
 krb5_save_realms(cmd_parms *cmd, kerb_auth_config *sec, char *arg);
 
@@ -192,7 +171,7 @@ static const command_rec kerb_auth_cmds[] = {
    command("KrbMethodNegotiate", ap_set_flag_slot, krb_method_gssapi,
      FLAG, "Enable Negotiate authentication method."),
 
-   command("KrbMethodK5Pass", ap_set_flag_slot, krb_method_k5pass,
+   command("KrbMethodK5Passwd", ap_set_flag_slot, krb_method_k5pass,
      FLAG, "Enable Kerberos V5 password authentication."),
 #endif 
 
@@ -200,7 +179,7 @@ static const command_rec kerb_auth_cmds[] = {
    command("Krb4Srvtab", ap_set_file_slot, krb_4_srvtab,
      TAKE1, "Location of Kerberos V4 srvtab file."),
 
-   command("KrbMethodK4Pass", ap_set_flag_slot, krb_method_k4pass,
+   command("KrbMethodK4Passwd", ap_set_flag_slot, krb_method_k4pass,
      FLAG, "Enable Kerberos V4 password authentication."),
 #endif
 
@@ -226,7 +205,7 @@ static void *kerb_dir_create_config(MK_POOL *p, char *d)
 
        rec = (kerb_auth_config *) ap_pcalloc(p, sizeof(kerb_auth_config));
         ((kerb_auth_config *)rec)->krb_verify_kdc = 1;
-       ((kerb_auth_config *)rec)->krb_service_name = "khttp";
+       ((kerb_auth_config *)rec)->krb_service_name = "HTTP";
        ((kerb_auth_config *)rec)->krb_authoritative = 1;
 #ifdef KRB5
        ((kerb_auth_config *)rec)->krb_method_k5pass = 1;
@@ -249,23 +228,17 @@ void log_rerror(const char *file, int line, int level, int status,
                 const request_rec *r, const char *fmt, ...)
 {
    char errstr[1024];
-   char errnostr[1024];
    va_list ap;
 
    va_start(ap, fmt);
    vsnprintf(errstr, sizeof(errstr), fmt, ap);
    va_end(ap);
 
-   errnostr[0] = '\0';
-   if (errno)
-      snprintf(errnostr, sizeof(errnostr), "%s: (%s)", errstr, strerror(errno));
-   else
-      snprintf(errnostr, sizeof(errnostr), "%s", errstr);
    
 #ifdef APXS1
-   ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errnostr);
+   ap_log_rerror(file, line, level | APLOG_NOERRNO, r, "%s", errstr);
 #else
-   ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errnostr);
+   ap_log_rerror(file, line, level | APLOG_NOERRNO, status, r, "%s", errstr);
 #endif
 }
 
@@ -467,30 +440,58 @@ verify_krb5_user(request_rec *r, krb5_context context, krb5_principal principal,
    krb5_error_code ret;
    krb5_verify_init_creds_opt opt;
 
+   /* XXX error messages shouldn't be logged here (and in the while() loop in
+    * authenticate_user_krb5pwd() as weell), in order to avoid confusing log
+    * entries when using multiple realms */
+
    memset(&creds, 0, sizeof(creds));
 
    ret = krb5_get_init_creds_password(context, &creds, principal, 
-                                     (char *)password, krb5_prompter_posix,
+                                     (char *)password, NULL,
                                      NULL, 0, NULL, NULL);
-   if (ret)
+   if (ret) {
+      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                "krb5_get_init_creds_password() failed: %s",
+                krb5_get_err_text(context, ret));
       return ret;
+   }
 
    ret = krb5_sname_to_principal(context, ap_get_server_name(r), service, 
-                                KRB5_NT_SRV_HST, &server);
-   if (ret)
+                                KRB5_NT_UNKNOWN, &server);
+   if (ret) {
+      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                "krb5_sname_to_principal() failed: %s",
+                krb5_get_err_text(context, ret));
       goto end;
+   }
 
    krb5_verify_init_creds_opt_init(&opt);
    krb5_verify_init_creds_opt_set_ap_req_nofail(&opt, krb_verify_kdc);
 
    ret = krb5_verify_init_creds(context, &creds, server, keytab, NULL, &opt);
-   if (ret)
+   if (ret) {
+      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                "krb5_verify_init_creds() failed: %s",
+                krb5_get_err_text(context, ret));
       goto end;
-
+   }
+                
    if (ccache) {
       ret = krb5_cc_initialize(context, ccache, principal);
-      if (ret == 0)
-        ret = krb5_cc_store_cred(context, ccache, &creds);
+      if (ret) {
+        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                   "krb5_cc_initialize() failed: %s",
+                   krb5_get_err_text(context, ret));
+        goto end;
+      }
+
+      ret = krb5_cc_store_cred(context, ccache, &creds);
+      if (ret) {
+        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                   "krb5_cc_store_cred() failed: %s",
+                   krb5_get_err_text(context, ret));
+        goto end;
+      }
    }
 
 end:
@@ -663,21 +664,17 @@ int authenticate_user_krb5pwd(request_rec *r,
       goto end;
    }
 
-   /* XXX Heimdal allows to use the MEMORY: type with empty argument ? */
-   ccname = ap_psprintf(r->pool, "MEMORY:%s/krb5cc_apache_XXXXXX", P_tmpdir);
-   fd = mkstemp(ccname + strlen("MEMORY:"));
-   if (fd < 0) {
+   if (sent_pw == NULL || *sent_pw == '\0') {
       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
-                 "mkstemp() failed: %s", strerror(errno));
-      ret = HTTP_INTERNAL_SERVER_ERROR;
+                "empty passwords are not accepted");
+      ret = HTTP_UNAUTHORIZED;
       goto end;
    }
-   close(fd);
 
-   code = krb5_cc_resolve(kcontext, ccname, &ccache);
+   code = krb5_cc_resolve(kcontext, "MEMORY:", &ccache);
    if (code) {
       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
-                 "krb5_cc_resolve() failed: %s",
+                "generating new memory ccache failed: %s",
                  krb5_get_err_text(kcontext, code));
       ret = HTTP_INTERNAL_SERVER_ERROR;
       unlink(ccname);
@@ -691,16 +688,24 @@ int authenticate_user_krb5pwd(request_rec *r,
    realms = conf->krb_auth_realms;
    do {
       if (realms && (code = krb5_set_default_realm(kcontext,
-                                          ap_getword_white(r->pool, &realms))))
+                                          ap_getword_white(r->pool, &realms)))){
+        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                   "krb5_set_default_realm() failed: %s",
+                   krb5_get_err_text(kcontext, code));
         continue;
+      }
 
       if (client) {
         krb5_free_principal(kcontext, client);
         client = NULL;
       }
       code = krb5_parse_name(kcontext, sent_name, &client);
-      if (code)
+      if (code) {
+        log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                   "krb5_parse_name() failed: %s",
+                   krb5_get_err_text(kcontext, code));
         continue;
+      }
 
       code = verify_krb5_user(r, kcontext, client, ccache, sent_pw, 
                              conf->krb_service_name, 
@@ -722,10 +727,6 @@ int authenticate_user_krb5pwd(request_rec *r,
    memset((char *)sent_pw, 0, strlen(sent_pw));
 
    if (code) {
-      /* XXX log only in the verify_krb5_user() call */
-      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
-                "Verifying krb5 password failed: %s",
-                krb5_get_err_text(kcontext, code));
       if (!conf->krb_authoritative && all_principals_unkown == 1 && code == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN)
         ret = DECLINED;
       else
@@ -783,20 +784,22 @@ get_gss_error(MK_POOL *p, OM_uint32 err_maj, OM_uint32 err_min, char *prefix)
                                     GSS_C_NO_OID,
                                     &msg_ctx,
                                     &status_string);
+      if (GSS_ERROR(maj_stat))
+        break;
       err_msg = ap_pstrcat(p, err_msg, ": ", (char*) status_string.value, NULL);
       gss_release_buffer(&min_stat, &status_string);
       
-      if (GSS_ERROR(maj_stat) || msg_ctx == 0)
-        break;
-
       maj_stat = gss_display_status (&min_stat,
                                     err_min,
                                     GSS_C_MECH_CODE,
                                     GSS_C_NULL_OID,
                                     &msg_ctx,
                                     &status_string);
-      err_msg = ap_pstrcat(p, err_msg, ": ", (char*) status_string.value, NULL);
-      gss_release_buffer(&min_stat, &status_string);
+      if (!GSS_ERROR(maj_stat)) {
+        err_msg = ap_pstrcat(p, err_msg,
+                             " (", (char*) status_string.value, ")", NULL);
+        gss_release_buffer(&min_stat, &status_string);
+      }
    } while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
 
    return err_msg;
@@ -883,13 +886,21 @@ get_gss_creds(request_rec *r,
    gss_name_t server_name = GSS_C_NO_NAME;
    char buf[1024];
 
-   snprintf(buf, sizeof(buf), "%s/%s", conf->krb_service_name, ap_get_server_name(r));
+#if 0
+   /* Don't specify service name. This makes MIT 1.3 not to use replay caches,
+    * which causes large problems with the Microsoft krb5 implementation. MS
+    * obviously uses a format of the krb5 authenticator that is considered by
+    * the MIT as replay (Two valid MS authenticators may contain the same time
+    * and utime fields and only differ in the sequential numbers).
+    */
+   snprintf(buf, sizeof(buf), "%s@%s", conf->krb_service_name,
+        ap_get_server_name(r));
 
    input_token.value = buf;
    input_token.length = strlen(buf) + 1;
 
    major_status = gss_import_name(&minor_status, &input_token,
-                                 GSS_C_NT_USER_NAME,
+                                 GSS_C_NT_HOSTBASED_SERVICE,
                                  &server_name);
    if (GSS_ERROR(major_status)) {
       log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
@@ -897,6 +908,7 @@ get_gss_creds(request_rec *r,
                 "gss_import_name() failed"));
       return HTTP_INTERNAL_SERVER_ERROR;
    }
+#endif
    
    major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
                                   GSS_C_NO_OID_SET, GSS_C_ACCEPT,
@@ -940,9 +952,8 @@ cmp_gss_type(gss_buffer_t token, gss_OID oid)
 }
 
 static int
-authenticate_user_gss(request_rec *r,
-                     kerb_auth_config *conf,
-                     const char *auth_line)
+authenticate_user_gss(request_rec *r, kerb_auth_config *conf,
+                     const char *auth_line, char **negotiate_ret_value)
 {
   OM_uint32 major_status, minor_status, minor_status2;
   gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
@@ -954,6 +965,8 @@ authenticate_user_gss(request_rec *r,
   OM_uint32 (*accept_sec_token)();
   gss_OID_desc spnego_oid;
 
+  *negotiate_ret_value = "\0";
+
   spnego_oid.length = 6;
   spnego_oid.elements = (void *)"\x2b\x06\x01\x05\x05\x02";
 
@@ -1038,8 +1051,7 @@ authenticate_user_gss(request_rec *r,
      }
      ap_base64encode(token, output_token.value, output_token.length);
      token[len] = '\0';
-     ap_table_set(r->err_headers_out, "WWW-Authenticate",
-                 ap_pstrcat(r->pool, "Negotiate ", token, NULL));
+     *negotiate_ret_value = token;
      gss_release_buffer(&minor_status2, &output_token);
   }
 
@@ -1047,6 +1059,8 @@ authenticate_user_gss(request_rec *r,
      log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                "%s", get_gss_error(r->pool, major_status, minor_status,
                                    "gss_accept_sec_context() failed"));
+     /* Don't offer the Negotiate method again if call to GSS layer failed */
+     *negotiate_ret_value = NULL;
      ret = HTTP_UNAUTHORIZED;
      goto end;
   }
@@ -1074,6 +1088,9 @@ authenticate_user_gss(request_rec *r,
   if (conf->krb_save_credentials && delegated_cred != GSS_C_NO_CREDENTIAL)
      store_gss_creds(r, conf, (char *)output_token.value, delegated_cred);
 
+  if (*negotiate_ret_value)
+     set_kerb_auth_headers(r, conf, 0, 0, *negotiate_ret_value);
+
   gss_release_buffer(&minor_status, &output_token);
 
   ret = OK;
@@ -1088,7 +1105,8 @@ end:
   if (client_name != GSS_C_NO_NAME)
      gss_release_name(&minor_status, &client_name);
 
-  cleanup_gss_connection(gss_connection);
+  if (! major_status & GSS_S_CONTINUE_NEEDED)
+     cleanup_gss_connection(gss_connection);
 
   return ret;
 }
@@ -1106,30 +1124,36 @@ already_succeeded(request_rec *r)
 }
 
 static void
-note_kerb_auth_failure(request_rec *r, const kerb_auth_config *conf,
-                      int use_krb4, int use_krb5)
+set_kerb_auth_headers(request_rec *r, const kerb_auth_config *conf,
+                     int use_krb4, int use_krb5pwd, char *negotiate_ret_value)
 {
    const char *auth_name = NULL;
    int set_basic = 0;
+   char *negoauth_param;
+   const char *header_name = 
+      (r->proxyreq == PROXYREQ_PROXY) ? "Proxy-Authenticate" : "WWW-Authenticate";
 
    /* get the user realm specified in .htaccess */
    auth_name = ap_auth_name(r);
 
    /* XXX should the WWW-Authenticate header be cleared first? */
 #ifdef KRB5
-   if (use_krb5 && conf->krb_method_gssapi)
-      ap_table_add(r->err_headers_out, "WWW-Authenticate", "Negotiate");
-   if (use_krb5 && conf->krb_method_k5pass) {
-      ap_table_add(r->err_headers_out, "WWW-Authenticate",
-                   ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
+   if (negotiate_ret_value != NULL && conf->krb_method_gssapi) {
+      negoauth_param = (*negotiate_ret_value == '\0') ? "Negotiate" :
+                 ap_pstrcat(r->pool, "Negotiate ", negotiate_ret_value, NULL);
+      ap_table_add(r->err_headers_out, header_name, negoauth_param);
+   }
+   if (use_krb5pwd && conf->krb_method_k5pass) {
+      ap_table_add(r->err_headers_out, header_name,
+                  ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
       set_basic = 1;
    }
 #endif
 
 #ifdef KRB4
    if (use_krb4 && conf->krb_method_k4pass && !set_basic)
-      ap_table_add(r->err_headers_out, "WWW-Authenticate",
-                  ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
+      ap_table_add(r->err_headers_out, header_name,
+                 ap_pstrcat(r->pool, "Basic realm=\"", auth_name, "\"", NULL));
 #endif
 }
 
@@ -1144,6 +1168,7 @@ int kerb_authenticate_user(request_rec *r)
    int use_krb5 = 0, use_krb4 = 0;
    int ret;
    static int last_return = HTTP_UNAUTHORIZED;
+   char *negotiate_ret_value = NULL;
 
    /* get the type specified in .htaccess */
    type = ap_auth_type(r);
@@ -1160,8 +1185,12 @@ int kerb_authenticate_user(request_rec *r)
    /* get what the user sent us in the HTTP header */
    auth_line = MK_TABLE_GET(r->headers_in, "Authorization");
    if (!auth_line) {
-      note_kerb_auth_failure(r, conf, use_krb4, use_krb5);
-      return HTTP_UNAUTHORIZED;
+       auth_line = MK_TABLE_GET(r->headers_in, "Proxy-Authorization");
+       if (!auth_line) {
+               set_kerb_auth_headers(r, conf, use_krb4, use_krb5,
+                                    (use_krb5) ? "\0" : NULL);
+               return HTTP_UNAUTHORIZED;
+       }
    }
    auth_type = ap_getword_white(r->pool, &auth_line);
 
@@ -1173,7 +1202,7 @@ int kerb_authenticate_user(request_rec *r)
 #ifdef KRB5
    if (use_krb5 && conf->krb_method_gssapi &&
        strcasecmp(auth_type, "Negotiate") == 0) {
-      ret = authenticate_user_gss(r, conf, auth_line);
+      ret = authenticate_user_gss(r, conf, auth_line, &negotiate_ret_value);
    } else if (use_krb5 && conf->krb_method_k5pass &&
              strcasecmp(auth_type, "Basic") == 0) {
        ret = authenticate_user_krb5pwd(r, conf, auth_line);
@@ -1187,7 +1216,7 @@ int kerb_authenticate_user(request_rec *r)
 #endif
 
    if (ret == HTTP_UNAUTHORIZED)
-      note_kerb_auth_failure(r, conf, use_krb4, use_krb5);
+      set_kerb_auth_headers(r, conf, use_krb4, use_krb5, negotiate_ret_value);
 
    last_return = ret;
    return ret;