Base code merged to SPIN 2.4
[platform/upstream/curl.git] / lib / http_digest.c
index 35ba171..ba59e5d 100644 (file)
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2004, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  * KIND, either express or implied.
  *
- * $Id$
  ***************************************************************************/
-#include "setup.h"
 
-#ifndef CURL_DISABLE_HTTP
-/* -- WIN32 approved -- */
-#include <stdio.h>
-#include <string.h>
-#include <stdarg.h>
-#include <stdlib.h>
-#include <ctype.h>
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
 
 #include "urldata.h"
-#include "sendf.h"
-#include "strequal.h"
-#include "base64.h"
-#include "md5.h"
+#include "rawstr.h"
+#include "curl_sasl.h"
 #include "http_digest.h"
-#include "strtok.h"
-#include "url.h" /* for Curl_safefree() */
+#include "curl_memory.h"
 
 #define _MPRINTF_REPLACE /* use our functions only */
 #include <curl/mprintf.h>
 
 /* The last #include file should be: */
-#ifdef CURLDEBUG
 #include "memdebug.h"
-#endif
 
 /* Test example headers:
 
@@ -54,375 +43,139 @@ Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598"
 
 */
 
-CURLdigest Curl_input_digest(struct connectdata *conn,
-                             bool proxy,
-                             char *header) /* rest of the *-authenticate:
-                                              header */
+CURLcode Curl_input_digest(struct connectdata *conn,
+                           bool proxy,
+                           const char *header) /* rest of the *-authenticate:
+                                                  header */
 {
-  bool more = TRUE;
-  char *token = NULL;
-  char *tmp = NULL;
-  bool foundAuth = FALSE;
-  bool foundAuthInt = FALSE;
-  struct SessionHandle *data=conn->data;
-  bool before = FALSE; /* got a nonce before */
-  struct digestdata *d;
-  
+  struct SessionHandle *data = conn->data;
+
+  /* Point to the correct struct with this */
+  struct digestdata *digest;
+
   if(proxy) {
-    d = &data->state.proxydigest;
+    digest = &data->state.proxydigest;
   }
   else {
-    d = &data->state.digest;
+    digest = &data->state.digest;
   }
 
-  /* skip initial whitespaces */
-  while(*header && isspace((int)*header))
-    header++;
+  if(!checkprefix("Digest", header))
+    return CURLE_BAD_CONTENT_ENCODING;
 
-  if(checkprefix("Digest", header)) {
-    header += strlen("Digest");
-
-    /* If we already have received a nonce, keep that in mind */
-    if(d->nonce)
-      before = TRUE;
-
-    /* clear off any former leftovers and init to defaults */
-    Curl_digest_cleanup_one(d);
-
-    while(more) {
-      char value[32];
-      char content[128];
-      size_t totlen=0;
-
-      while(*header && isspace((int)*header))
-        header++;
-
-      /* how big can these strings be? */
-      if((2 == sscanf(header, "%31[^=]=\"%127[^\"]\"",
-                      value, content)) ||
-         /* try the same scan but without quotes around the content but don't
-            include the possibly trailing comma */
-         (2 ==  sscanf(header, "%31[^=]=%127[^,]",
-                       value, content)) ) {
-        if(strequal(value, "nonce")) {
-          d->nonce = strdup(content);
-        }
-        else if(strequal(value, "stale")) {
-          if(strequal(content, "true")) {
-            d->stale = TRUE;
-            d->nc = 1; /* we make a new nonce now */
-          }
-        }
-        else if(strequal(value, "realm")) {
-          d->realm = strdup(content);
-        }
-        else if(strequal(value, "opaque")) {
-          d->opaque = strdup(content);
-        }
-        else if(strequal(value, "qop")) {
-          char *tok_buf;
-          /* tokenize the list and choose auth if possible, use a temporary
-             clone of the buffer since strtok_r() ruins it */
-          tmp = strdup(content);
-          token = strtok_r(tmp, ",", &tok_buf);
-          while (token != NULL) {
-            if (strequal(token, "auth")) {
-              foundAuth = TRUE;
-            }
-            else if (strequal(token, "auth-int")) {
-              foundAuthInt = TRUE;
-            }
-            token = strtok_r(NULL, ",", &tok_buf);
-          }
-          free(tmp);
-          /*select only auth o auth-int. Otherwise, ignore*/
-          if (foundAuth) {
-            d->qop = strdup("auth");
-          }
-          else if (foundAuthInt) {
-            d->qop = strdup("auth-int");
-          }
-        }
-        else if(strequal(value, "algorithm")) {
-          d->algorithm = strdup(content);
-          if(strequal(content, "MD5-sess"))
-            d->algo = CURLDIGESTALGO_MD5SESS;
-          else if(strequal(content, "MD5"))
-            d->algo = CURLDIGESTALGO_MD5;
-          else
-            return CURLDIGEST_BADALGO;
-        }
-        else {
-          /* unknown specifier, ignore it! */
-        }
-        totlen = strlen(value)+strlen(content)+3;
-      }
-      else
-        break; /* we're done here */
-
-      header += totlen;
-      if(',' == *header)
-        /* allow the list to be comma-separated */
-        header++;
-    }
-    /* We had a nonce since before, and we got another one now without
-       'stale=true'. This means we provided bad credentials in the previous
-       request */
-    if(before && !d->stale)
-      return CURLDIGEST_BAD;
-
-    /* We got this header without a nonce, that's a bad Digest line! */
-    if(!d->nonce)
-      return CURLDIGEST_BAD;
-  }
-  else
-    /* else not a digest, get out */
-    return CURLDIGEST_NONE;
-
-  return CURLDIGEST_FINE;
-}
+  header += strlen("Digest");
+  while(*header && ISSPACE(*header))
+    header++;
 
-/* convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/
-static void md5_to_ascii(unsigned char *source, /* 16 bytes */
-                         unsigned char *dest) /* 33 bytes */
-{
-  int i;
-  for(i=0; i<16; i++)
-    sprintf((char *)&dest[i*2], "%02x", source[i]);
+  return Curl_sasl_decode_digest_http_message(header, digest);
 }
 
 CURLcode Curl_output_digest(struct connectdata *conn,
                             bool proxy,
-                            unsigned char *request,
-                            unsigned char *uripath)
+                            const unsigned char *request,
+                            const unsigned char *uripath)
 {
-  /* We have a Digest setup for this, use it!  Now, to get all the details for
-     this sorted out, I must urge you dear friend to read up on the RFC2617
-     section 3.2.2, */
-  unsigned char md5buf[16]; /* 16 bytes/128 bits */
-  unsigned char request_digest[33];
-  unsigned char *md5this;
-  unsigned char *ha1;
-  unsigned char ha2[33];/* 32 digits and 1 zero byte */
-  char cnoncebuf[7];
-  char *cnonce;
-  char *tmp = NULL;
-  struct timeval now;
-  struct auth *authp;
-  char **userp;
-
+  CURLcode result;
   struct SessionHandle *data = conn->data;
-  struct digestdata *d;
+  unsigned char *path;
+  char *tmp;
+  char *response;
+  size_t len;
+  bool have_chlg;
+
+  /* Point to the address of the pointer that holds the string to send to the
+     server, which is for a plain host or for a HTTP proxy */
+  char **allocuserpwd;
+
+  /* Point to the name and password for this */
+  const char *userp;
+  const char *passwdp;
+
+  /* Point to the correct struct with this */
+  struct digestdata *digest;
+  struct auth *authp;
 
   if(proxy) {
-    d = &data->state.proxydigest;
+    digest = &data->state.proxydigest;
+    allocuserpwd = &conn->allocptr.proxyuserpwd;
+    userp = conn->proxyuser;
+    passwdp = conn->proxypasswd;
     authp = &data->state.authproxy;
-    userp = &conn->allocptr.proxyuserpwd;
   }
   else {
-    d = &data->state.digest;
+    digest = &data->state.digest;
+    allocuserpwd = &conn->allocptr.userpwd;
+    userp = conn->user;
+    passwdp = conn->passwd;
     authp = &data->state.authhost;
-    userp = &conn->allocptr.userpwd;
   }
 
-  if(!d->nonce) {
-    authp->done = FALSE;
-    return CURLE_OK;
-  }
-  authp->done = TRUE;
-
-  ha1 = (unsigned char *)malloc(33); /* 32 digits and 1 zero byte */
-
-  if(!d->nc)
-    d->nc = 1;
-
-  if(!d->cnonce) {
-    /* Generate a cnonce */
-    now = Curl_tvnow();
-    snprintf(cnoncebuf, sizeof(cnoncebuf), "%06d", now.tv_sec);
-    Curl_base64_encode(cnoncebuf, strlen(cnoncebuf), &cnonce);
-    d->cnonce = cnonce;
-  }
-
-  /*
-    if the algorithm is "MD5" or unspecified (which then defaults to MD5):
+  Curl_safefree(*allocuserpwd);
 
-    A1 = unq(username-value) ":" unq(realm-value) ":" passwd
+  /* not set means empty */
+  if(!userp)
+    userp = "";
 
-    if the algorithm is "MD5-sess" then:
-
-    A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
-         ":" unq(nonce-value) ":" unq(cnonce-value)
-  */
+  if(!passwdp)
+    passwdp = "";
 
-  md5this = (unsigned char *)
-    aprintf("%s:%s:%s", conn->user, d->realm, conn->passwd);
-  Curl_md5it(md5buf, md5this);
-  free(md5this); /* free this again */
-  md5_to_ascii(md5buf, ha1);
-
-  if(d->algo == CURLDIGESTALGO_MD5SESS) {
-    /* nonce and cnonce are OUTSIDE the hash */
-    tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce);
-
-    free(ha1);
-    ha1 = (unsigned char *)tmp;
-  }
-
-  /*
-    If the "qop" directive's value is "auth" or is unspecified, then A2 is:
-
-      A2       = Method ":" digest-uri-value
-
-         If the "qop" value is "auth-int", then A2 is:
-
-      A2       = Method ":" digest-uri-value ":" H(entity-body)
-
-    (The "Method" value is the HTTP request method as specified in section
-    5.1.1 of RFC 2616)
-  */
+#if defined(USE_WINDOWS_SSPI)
+  have_chlg = digest->input_token ? TRUE : FALSE;
+#else
+  have_chlg = digest->nonce ? TRUE : FALSE;
+#endif
 
-  md5this = (unsigned char *)aprintf("%s:%s", request, uripath);
-  if (d->qop && strequal(d->qop, "auth-int")) {
-    /* We don't support auth-int at the moment. I can't see a easy way to get
-       entity-body here */
-    /* TODO: Append H(entity-body)*/
-  }
-  Curl_md5it(md5buf, md5this);
-  free(md5this); /* free this again */
-  md5_to_ascii(md5buf, ha2);
-
-  if (d->qop) {
-    md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
-                                       ha1,
-                                       d->nonce,
-                                       d->nc,
-                                       d->cnonce,
-                                       d->qop,
-                                       ha2);
-  }
-  else {
-    md5this = (unsigned char *)aprintf("%s:%s:%s",
-                                       ha1,
-                                       d->nonce,
-                                       ha2);
+  if(!have_chlg) {
+    authp->done = FALSE;
+    return CURLE_OK;
   }
-  free(ha1);
 
-  Curl_md5it(md5buf, md5this);
-  free(md5this); /* free this again */
-  md5_to_ascii(md5buf, request_digest);
+  /* So IE browsers < v7 cut off the URI part at the query part when they
+     evaluate the MD5 and some (IIS?) servers work with them so we may need to
+     do the Digest IE-style. Note that the different ways cause different MD5
+     sums to get sent.
 
-  /* for test case 64 (snooped from a Mozilla 1.3a request)
+     Apache servers can be set to do the Digest IE-style automatically using
+     the BrowserMatch feature:
+     http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie
 
-    Authorization: Digest username="testuser", realm="testrealm", \
-    nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
+     Further details on Digest implementation differences:
+     http://www.fngtps.com/2006/09/http-authentication
   */
 
-  Curl_safefree(conn->allocptr.userpwd);
-
-  if (d->qop) {
-    *userp =
-      aprintf( "%sAuthorization: Digest "
-               "username=\"%s\", "
-               "realm=\"%s\", "
-               "nonce=\"%s\", "
-               "uri=\"%s\", "
-               "cnonce=\"%s\", "
-               "nc=\"%08x\", "
-               "qop=\"%s\", "
-               "response=\"%s\"",
-               proxy?"Proxy-":"",
-               conn->user,
-               d->realm,
-               d->nonce,
-               uripath, /* this is the PATH part of the URL */
-               d->cnonce,
-               d->nc,
-               d->qop,
-               request_digest);
-
-    if(strequal(d->qop, "auth"))
-      d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded
-                  which tells to the server how many times you are using the
-                  same nonce in the qop=auth mode. */
-  }
-  else {
-    *userp =
-      aprintf( "%sAuthorization: Digest "
-               "username=\"%s\", "
-               "realm=\"%s\", "
-               "nonce=\"%s\", "
-               "uri=\"%s\", "
-               "response=\"%s\"",
-               proxy?"Proxy-":"",
-               conn->user,
-               d->realm,
-               d->nonce,
-               uripath, /* this is the PATH part of the URL */
-               request_digest);
-  }
-
-  /* Add optional fields */
-  if(d->opaque) {
-    /* append opaque */
-    tmp = aprintf(", opaque=\"%s\"", d->opaque);
-    *userp = (char*) realloc(*userp, strlen(*userp) + strlen(tmp) + 1);
-    strcat(*userp, tmp);
-    free(tmp);
-  }
+  if(authp->iestyle && ((tmp = strchr((char *)uripath, '?')) != NULL)) {
+    size_t urilen = tmp - (char *)uripath;
 
-  if(d->algorithm) {
-    /* append algorithm */
-    tmp = aprintf(", algorithm=\"%s\"", d->algorithm);
-    *userp = (char*) realloc(*userp, strlen(*userp) + strlen(tmp) + 1);
-    strcat(conn->allocptr.userpwd, tmp);
-    free(tmp);
+    path = (unsigned char *) aprintf("%.*s", urilen, uripath);
   }
+  else
+    path = (unsigned char *) strdup((char *) uripath);
 
-  /* append CRLF to the userpwd header */
-  *userp = (char*) realloc(*userp, strlen(*userp) + 3 + 1);
-  strcat(*userp, "\r\n");
-
-  return CURLE_OK;
-}
-
-void Curl_digest_cleanup_one(struct digestdata *d)
-{
-  if(d->nonce)
-    free(d->nonce);
-  d->nonce = NULL;
-
-  if(d->cnonce)
-    free(d->cnonce);
-  d->cnonce = NULL;
-
-  if(d->realm)
-    free(d->realm);
-  d->realm = NULL;
+  if(!path)
+    return CURLE_OUT_OF_MEMORY;
 
-  if(d->opaque)
-    free(d->opaque);
-  d->opaque = NULL;
+  result = Curl_sasl_create_digest_http_message(data, userp, passwdp, request,
+                                                path, digest, &response, &len);
+  free(path);
+  if(result)
+    return result;
 
-  if(d->qop)
-    free(d->qop);
-  d->qop = NULL;
+  *allocuserpwd = aprintf("%sAuthorization: Digest %s\r\n",
+                          proxy ? "Proxy-" : "",
+                          response);
+  free(response);
+  if(!*allocuserpwd)
+    return CURLE_OUT_OF_MEMORY;
 
-  if(d->algorithm)
-    free(d->algorithm);
-  d->algorithm = NULL;
+  authp->done = TRUE;
 
-  d->nc = 0;
-  d->algo = CURLDIGESTALGO_MD5; /* default algorithm */
-  d->stale = FALSE; /* default means normal, not stale */
+  return CURLE_OK;
 }
 
-
 void Curl_digest_cleanup(struct SessionHandle *data)
 {
-  Curl_digest_cleanup_one(&data->state.digest);
-  Curl_digest_cleanup_one(&data->state.proxydigest);
+  Curl_sasl_digest_cleanup(&data->state.digest);
+  Curl_sasl_digest_cleanup(&data->state.proxydigest);
 }
 
 #endif