Olaf Stüben fixed a bug that caused Digest authentication with md5-sess to
[platform/upstream/curl.git] / lib / http_digest.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2006, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23 #include "setup.h"
24
25 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
26 /* -- WIN32 approved -- */
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <stdlib.h>
31 #include <ctype.h>
32
33 #include "urldata.h"
34 #include "sendf.h"
35 #include "strequal.h"
36 #include "base64.h"
37 #include "md5.h"
38 #include "http_digest.h"
39 #include "strtok.h"
40 #include "url.h" /* for Curl_safefree() */
41 #include "memory.h"
42
43 #define _MPRINTF_REPLACE /* use our functions only */
44 #include <curl/mprintf.h>
45
46 /* The last #include file should be: */
47 #include "memdebug.h"
48
49 /* Test example headers:
50
51 WWW-Authenticate: Digest realm="testrealm", nonce="1053604598"
52 Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598"
53
54 */
55
56 CURLdigest Curl_input_digest(struct connectdata *conn,
57                              bool proxy,
58                              char *header) /* rest of the *-authenticate:
59                                               header */
60 {
61   bool more = TRUE;
62   char *token = NULL;
63   char *tmp = NULL;
64   bool foundAuth = FALSE;
65   bool foundAuthInt = FALSE;
66   struct SessionHandle *data=conn->data;
67   bool before = FALSE; /* got a nonce before */
68   struct digestdata *d;
69
70   if(proxy) {
71     d = &data->state.proxydigest;
72   }
73   else {
74     d = &data->state.digest;
75   }
76
77   /* skip initial whitespaces */
78   while(*header && isspace((int)*header))
79     header++;
80
81   if(checkprefix("Digest", header)) {
82     header += strlen("Digest");
83
84     /* If we already have received a nonce, keep that in mind */
85     if(d->nonce)
86       before = TRUE;
87
88     /* clear off any former leftovers and init to defaults */
89     Curl_digest_cleanup_one(d);
90
91     while(more) {
92       char value[32];
93       char content[128];
94       size_t totlen=0;
95
96       while(*header && isspace((int)*header))
97         header++;
98
99       /* how big can these strings be? */
100       if((2 == sscanf(header, "%31[^=]=\"%127[^\"]\"",
101                       value, content)) ||
102          /* try the same scan but without quotes around the content but don't
103             include the possibly trailing comma */
104          (2 ==  sscanf(header, "%31[^=]=%127[^,]",
105                        value, content)) ) {
106         if(strequal(value, "nonce")) {
107           d->nonce = strdup(content);
108           if(!d->nonce)
109             return CURLDIGEST_NOMEM;
110         }
111         else if(strequal(value, "stale")) {
112           if(strequal(content, "true")) {
113             d->stale = TRUE;
114             d->nc = 1; /* we make a new nonce now */
115           }
116         }
117         else if(strequal(value, "realm")) {
118           d->realm = strdup(content);
119           if(!d->realm)
120             return CURLDIGEST_NOMEM;
121         }
122         else if(strequal(value, "opaque")) {
123           d->opaque = strdup(content);
124           if(!d->opaque)
125             return CURLDIGEST_NOMEM;
126         }
127         else if(strequal(value, "qop")) {
128           char *tok_buf;
129           /* tokenize the list and choose auth if possible, use a temporary
130              clone of the buffer since strtok_r() ruins it */
131           tmp = strdup(content);
132           if(!tmp)
133             return CURLDIGEST_NOMEM;
134           token = strtok_r(tmp, ",", &tok_buf);
135           while (token != NULL) {
136             if (strequal(token, "auth")) {
137               foundAuth = TRUE;
138             }
139             else if (strequal(token, "auth-int")) {
140               foundAuthInt = TRUE;
141             }
142             token = strtok_r(NULL, ",", &tok_buf);
143           }
144           free(tmp);
145           /*select only auth o auth-int. Otherwise, ignore*/
146           if (foundAuth) {
147             d->qop = strdup("auth");
148             if(!d->qop)
149               return CURLDIGEST_NOMEM;
150           }
151           else if (foundAuthInt) {
152             d->qop = strdup("auth-int");
153             if(!d->qop)
154               return CURLDIGEST_NOMEM;
155           }
156         }
157         else if(strequal(value, "algorithm")) {
158           d->algorithm = strdup(content);
159           if(!d->algorithm)
160             return CURLDIGEST_NOMEM;
161           if(strequal(content, "MD5-sess"))
162             d->algo = CURLDIGESTALGO_MD5SESS;
163           else if(strequal(content, "MD5"))
164             d->algo = CURLDIGESTALGO_MD5;
165           else
166             return CURLDIGEST_BADALGO;
167         }
168         else {
169           /* unknown specifier, ignore it! */
170         }
171         totlen = strlen(value)+strlen(content)+1;
172
173         if(header[strlen(value)+1] == '\"')
174           /* the contents were within quotes, then add 2 for them to the
175              length */
176           totlen += 2;
177       }
178       else
179         break; /* we're done here */
180
181       header += totlen;
182       if(',' == *header)
183         /* allow the list to be comma-separated */
184         header++;
185     }
186     /* We had a nonce since before, and we got another one now without
187        'stale=true'. This means we provided bad credentials in the previous
188        request */
189     if(before && !d->stale)
190       return CURLDIGEST_BAD;
191
192     /* We got this header without a nonce, that's a bad Digest line! */
193     if(!d->nonce)
194       return CURLDIGEST_BAD;
195   }
196   else
197     /* else not a digest, get out */
198     return CURLDIGEST_NONE;
199
200   return CURLDIGEST_FINE;
201 }
202
203 /* convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/
204 static void md5_to_ascii(unsigned char *source, /* 16 bytes */
205                          unsigned char *dest) /* 33 bytes */
206 {
207   int i;
208   for(i=0; i<16; i++)
209     snprintf((char *)&dest[i*2], 3, "%02x", source[i]);
210 }
211
212 CURLcode Curl_output_digest(struct connectdata *conn,
213                             bool proxy,
214                             unsigned char *request,
215                             unsigned char *uripath)
216 {
217   /* We have a Digest setup for this, use it!  Now, to get all the details for
218      this sorted out, I must urge you dear friend to read up on the RFC2617
219      section 3.2.2, */
220   unsigned char md5buf[16]; /* 16 bytes/128 bits */
221   unsigned char request_digest[33];
222   unsigned char *md5this;
223   unsigned char *ha1;
224   unsigned char ha2[33];/* 32 digits and 1 zero byte */
225   char cnoncebuf[7];
226   char *cnonce;
227   char *tmp = NULL;
228   struct timeval now;
229
230   char **allocuserpwd;
231   char *userp;
232   char *passwdp;
233   struct auth *authp;
234
235   struct SessionHandle *data = conn->data;
236   struct digestdata *d;
237
238   if(proxy) {
239     d = &data->state.proxydigest;
240     allocuserpwd = &conn->allocptr.proxyuserpwd;
241     userp = conn->proxyuser;
242     passwdp = conn->proxypasswd;
243     authp = &data->state.authproxy;
244   }
245   else {
246     d = &data->state.digest;
247     allocuserpwd = &conn->allocptr.userpwd;
248     userp = conn->user;
249     passwdp = conn->passwd;
250     authp = &data->state.authhost;
251   }
252
253   /* not set means empty */
254   if(!userp)
255     userp=(char *)"";
256
257   if(!passwdp)
258     passwdp=(char *)"";
259
260   if(!d->nonce) {
261     authp->done = FALSE;
262     return CURLE_OK;
263   }
264   authp->done = TRUE;
265
266   if(!d->nc)
267     d->nc = 1;
268
269   if(!d->cnonce) {
270     /* Generate a cnonce */
271     now = Curl_tvnow();
272     snprintf(cnoncebuf, sizeof(cnoncebuf), "%06ld", now.tv_sec);
273     if(Curl_base64_encode(cnoncebuf, strlen(cnoncebuf), &cnonce))
274       d->cnonce = cnonce;
275     else
276       return CURLE_OUT_OF_MEMORY;
277   }
278
279   /*
280     if the algorithm is "MD5" or unspecified (which then defaults to MD5):
281
282     A1 = unq(username-value) ":" unq(realm-value) ":" passwd
283
284     if the algorithm is "MD5-sess" then:
285
286     A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
287          ":" unq(nonce-value) ":" unq(cnonce-value)
288   */
289
290   md5this = (unsigned char *)
291     aprintf("%s:%s:%s", userp, d->realm, passwdp);
292   if(!md5this)
293     return CURLE_OUT_OF_MEMORY;
294   Curl_md5it(md5buf, md5this);
295   free(md5this); /* free this again */
296
297   ha1 = (unsigned char *)malloc(33); /* 32 digits and 1 zero byte */
298   if(!ha1)
299     return CURLE_OUT_OF_MEMORY;
300
301   md5_to_ascii(md5buf, ha1);
302
303   if(d->algo == CURLDIGESTALGO_MD5SESS) {
304     /* nonce and cnonce are OUTSIDE the hash */
305     tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce);
306     if(!tmp)
307       return CURLE_OUT_OF_MEMORY;
308     Curl_md5it(md5buf, (unsigned char *)tmp);
309     free(tmp); /* free this again */
310     md5_to_ascii(md5buf, ha1);
311   }
312
313   /*
314     If the "qop" directive's value is "auth" or is unspecified, then A2 is:
315
316       A2       = Method ":" digest-uri-value
317
318           If the "qop" value is "auth-int", then A2 is:
319
320       A2       = Method ":" digest-uri-value ":" H(entity-body)
321
322     (The "Method" value is the HTTP request method as specified in section
323     5.1.1 of RFC 2616)
324   */
325
326   md5this = (unsigned char *)aprintf("%s:%s", request, uripath);
327   if(!md5this) {
328     free(ha1);
329     return CURLE_OUT_OF_MEMORY;
330   }
331
332   if (d->qop && strequal(d->qop, "auth-int")) {
333     /* We don't support auth-int at the moment. I can't see a easy way to get
334        entity-body here */
335     /* TODO: Append H(entity-body)*/
336   }
337   Curl_md5it(md5buf, md5this);
338   free(md5this); /* free this again */
339   md5_to_ascii(md5buf, ha2);
340
341   if (d->qop) {
342     md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s",
343                                        ha1,
344                                        d->nonce,
345                                        d->nc,
346                                        d->cnonce,
347                                        d->qop,
348                                        ha2);
349   }
350   else {
351     md5this = (unsigned char *)aprintf("%s:%s:%s",
352                                        ha1,
353                                        d->nonce,
354                                        ha2);
355   }
356   free(ha1);
357   if(!md5this)
358     return CURLE_OUT_OF_MEMORY;
359
360   Curl_md5it(md5buf, md5this);
361   free(md5this); /* free this again */
362   md5_to_ascii(md5buf, request_digest);
363
364   /* for test case 64 (snooped from a Mozilla 1.3a request)
365
366     Authorization: Digest username="testuser", realm="testrealm", \
367     nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca"
368   */
369
370   Curl_safefree(*allocuserpwd);
371
372   if (d->qop) {
373     *allocuserpwd =
374       aprintf( "%sAuthorization: Digest "
375                "username=\"%s\", "
376                "realm=\"%s\", "
377                "nonce=\"%s\", "
378                "uri=\"%s\", "
379                "cnonce=\"%s\", "
380                "nc=%08x, "
381                "qop=\"%s\", "
382                "response=\"%s\"",
383                proxy?"Proxy-":"",
384                userp,
385                d->realm,
386                d->nonce,
387                uripath, /* this is the PATH part of the URL */
388                d->cnonce,
389                d->nc,
390                d->qop,
391                request_digest);
392
393     if(strequal(d->qop, "auth"))
394       d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded
395                   which tells to the server how many times you are using the
396                   same nonce in the qop=auth mode. */
397   }
398   else {
399     *allocuserpwd =
400       aprintf( "%sAuthorization: Digest "
401                "username=\"%s\", "
402                "realm=\"%s\", "
403                "nonce=\"%s\", "
404                "uri=\"%s\", "
405                "response=\"%s\"",
406                proxy?"Proxy-":"",
407                userp,
408                d->realm,
409                d->nonce,
410                uripath, /* this is the PATH part of the URL */
411                request_digest);
412   }
413   if(!*allocuserpwd)
414     return CURLE_OUT_OF_MEMORY;
415
416   /* Add optional fields */
417   if(d->opaque) {
418     /* append opaque */
419     tmp = aprintf("%s, opaque=\"%s\"", *allocuserpwd, d->opaque);
420     if(!tmp)
421       return CURLE_OUT_OF_MEMORY;
422     free(*allocuserpwd);
423     *allocuserpwd = tmp;
424   }
425
426   if(d->algorithm) {
427     /* append algorithm */
428     tmp = aprintf("%s, algorithm=\"%s\"", *allocuserpwd, d->algorithm);
429     if(!tmp)
430       return CURLE_OUT_OF_MEMORY;
431     free(*allocuserpwd);
432     *allocuserpwd = tmp;
433   }
434
435   /* append CRLF to the userpwd header */
436   tmp = (char*) realloc(*allocuserpwd, strlen(*allocuserpwd) + 3 + 1);
437   if(!tmp)
438     return CURLE_OUT_OF_MEMORY;
439   strcat(tmp, "\r\n");
440   *allocuserpwd = tmp;
441
442   return CURLE_OK;
443 }
444
445 void Curl_digest_cleanup_one(struct digestdata *d)
446 {
447   if(d->nonce)
448     free(d->nonce);
449   d->nonce = NULL;
450
451   if(d->cnonce)
452     free(d->cnonce);
453   d->cnonce = NULL;
454
455   if(d->realm)
456     free(d->realm);
457   d->realm = NULL;
458
459   if(d->opaque)
460     free(d->opaque);
461   d->opaque = NULL;
462
463   if(d->qop)
464     free(d->qop);
465   d->qop = NULL;
466
467   if(d->algorithm)
468     free(d->algorithm);
469   d->algorithm = NULL;
470
471   d->nc = 0;
472   d->algo = CURLDIGESTALGO_MD5; /* default algorithm */
473   d->stale = FALSE; /* default means normal, not stale */
474 }
475
476
477 void Curl_digest_cleanup(struct SessionHandle *data)
478 {
479   Curl_digest_cleanup_one(&data->state.digest);
480   Curl_digest_cleanup_one(&data->state.proxydigest);
481 }
482
483 #endif