1cc704d5888d1633d49cb77a755ff02183cd3596
[platform/upstream/curl.git] / lib / vauth / digest_sspi.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>.
9  * Copyright (C) 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
10  *
11  * This software is licensed as described in the file COPYING, which
12  * you should have received as part of this distribution. The terms
13  * are also available at https://curl.haxx.se/docs/copyright.html.
14  *
15  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16  * copies of the Software, and permit persons to whom the Software is
17  * furnished to do so, under the terms of the COPYING file.
18  *
19  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20  * KIND, either express or implied.
21  *
22  * RFC2831 DIGEST-MD5 authentication
23  *
24  ***************************************************************************/
25
26 #include "curl_setup.h"
27
28 #if defined(USE_WINDOWS_SSPI) && !defined(CURL_DISABLE_CRYPTO_AUTH)
29
30 #include <curl/curl.h>
31
32 #include "vauth/vauth.h"
33 #include "vauth/digest.h"
34 #include "urldata.h"
35 #include "curl_base64.h"
36 #include "warnless.h"
37 #include "curl_multibyte.h"
38 #include "sendf.h"
39 #include "strdup.h"
40 #include "rawstr.h"
41
42 /* The last #include files should be: */
43 #include "curl_memory.h"
44 #include "memdebug.h"
45
46 /*
47 * Curl_auth_is_digest_supported()
48 *
49 * This is used to evaluate if DIGEST is supported.
50 *
51 * Parameters: None
52 *
53 * Returns TRUE if DIGEST is supported by Windows SSPI.
54 */
55 bool Curl_auth_is_digest_supported(void)
56 {
57   PSecPkgInfo SecurityPackage;
58   SECURITY_STATUS status;
59
60   /* Query the security package for Digest */
61   status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST),
62                                               &SecurityPackage);
63
64   return (status == SEC_E_OK ? TRUE : FALSE);
65 }
66
67 /*
68  * Curl_auth_create_digest_md5_message()
69  *
70  * This is used to generate an already encoded DIGEST-MD5 response message
71  * ready for sending to the recipient.
72  *
73  * Parameters:
74  *
75  * data    [in]     - The session handle.
76  * chlg64  [in]     - The base64 encoded challenge message.
77  * userp   [in]     - The user name in the format User or Domain\User.
78  * passdwp [in]     - The user's password.
79  * service [in]     - The service type such as http, smtp, pop or imap.
80  * outptr  [in/out] - The address where a pointer to newly allocated memory
81  *                    holding the result will be stored upon completion.
82  * outlen  [out]    - The length of the output message.
83  *
84  * Returns CURLE_OK on success.
85  */
86 CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data,
87                                              const char *chlg64,
88                                              const char *userp,
89                                              const char *passwdp,
90                                              const char *service,
91                                              char **outptr, size_t *outlen)
92 {
93   CURLcode result = CURLE_OK;
94   TCHAR *spn = NULL;
95   size_t chlglen = 0;
96   size_t token_max = 0;
97   unsigned char *input_token = NULL;
98   unsigned char *output_token = NULL;
99   CredHandle credentials;
100   CtxtHandle context;
101   PSecPkgInfo SecurityPackage;
102   SEC_WINNT_AUTH_IDENTITY identity;
103   SEC_WINNT_AUTH_IDENTITY *p_identity;
104   SecBuffer chlg_buf;
105   SecBuffer resp_buf;
106   SecBufferDesc chlg_desc;
107   SecBufferDesc resp_desc;
108   SECURITY_STATUS status;
109   unsigned long attrs;
110   TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */
111
112   /* Decode the base-64 encoded challenge message */
113   if(strlen(chlg64) && *chlg64 != '=') {
114     result = Curl_base64_decode(chlg64, &input_token, &chlglen);
115     if(result)
116       return result;
117   }
118
119   /* Ensure we have a valid challenge message */
120   if(!input_token) {
121     infof(data, "DIGEST-MD5 handshake failure (empty challenge message)\n");
122
123     return CURLE_BAD_CONTENT_ENCODING;
124   }
125
126   /* Query the security package for DigestSSP */
127   status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST),
128                                               &SecurityPackage);
129   if(status != SEC_E_OK) {
130     free(input_token);
131
132     return CURLE_NOT_BUILT_IN;
133   }
134
135   token_max = SecurityPackage->cbMaxToken;
136
137   /* Release the package buffer as it is not required anymore */
138   s_pSecFn->FreeContextBuffer(SecurityPackage);
139
140   /* Allocate our response buffer */
141   output_token = malloc(token_max);
142   if(!output_token) {
143     free(input_token);
144
145     return CURLE_OUT_OF_MEMORY;
146   }
147
148   /* Generate our SPN */
149   spn = Curl_auth_build_spn(service, data->easy_conn->host.name, NULL);
150   if(!spn) {
151     free(output_token);
152     free(input_token);
153
154     return CURLE_OUT_OF_MEMORY;
155   }
156
157   if(userp && *userp) {
158     /* Populate our identity structure */
159     result = Curl_create_sspi_identity(userp, passwdp, &identity);
160     if(result) {
161       free(spn);
162       free(output_token);
163       free(input_token);
164
165       return result;
166     }
167
168     /* Allow proper cleanup of the identity structure */
169     p_identity = &identity;
170   }
171   else
172     /* Use the current Windows user */
173     p_identity = NULL;
174
175   /* Acquire our credentials handle */
176   status = s_pSecFn->AcquireCredentialsHandle(NULL,
177                                               (TCHAR *) TEXT(SP_NAME_DIGEST),
178                                               SECPKG_CRED_OUTBOUND, NULL,
179                                               p_identity, NULL, NULL,
180                                               &credentials, &expiry);
181
182   if(status != SEC_E_OK) {
183     Curl_sspi_free_identity(p_identity);
184     free(spn);
185     free(output_token);
186     free(input_token);
187
188     return CURLE_LOGIN_DENIED;
189   }
190
191   /* Setup the challenge "input" security buffer */
192   chlg_desc.ulVersion = SECBUFFER_VERSION;
193   chlg_desc.cBuffers  = 1;
194   chlg_desc.pBuffers  = &chlg_buf;
195   chlg_buf.BufferType = SECBUFFER_TOKEN;
196   chlg_buf.pvBuffer   = input_token;
197   chlg_buf.cbBuffer   = curlx_uztoul(chlglen);
198
199   /* Setup the response "output" security buffer */
200   resp_desc.ulVersion = SECBUFFER_VERSION;
201   resp_desc.cBuffers  = 1;
202   resp_desc.pBuffers  = &resp_buf;
203   resp_buf.BufferType = SECBUFFER_TOKEN;
204   resp_buf.pvBuffer   = output_token;
205   resp_buf.cbBuffer   = curlx_uztoul(token_max);
206
207   /* Generate our response message */
208   status = s_pSecFn->InitializeSecurityContext(&credentials, NULL, spn,
209                                                0, 0, 0, &chlg_desc, 0,
210                                                &context, &resp_desc, &attrs,
211                                                &expiry);
212
213   if(status == SEC_I_COMPLETE_NEEDED ||
214      status == SEC_I_COMPLETE_AND_CONTINUE)
215     s_pSecFn->CompleteAuthToken(&credentials, &resp_desc);
216   else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) {
217     s_pSecFn->FreeCredentialsHandle(&credentials);
218     Curl_sspi_free_identity(p_identity);
219     free(spn);
220     free(output_token);
221     free(input_token);
222
223     return CURLE_RECV_ERROR;
224   }
225
226   /* Base64 encode the response */
227   result = Curl_base64_encode(data, (char *) output_token, resp_buf.cbBuffer,
228                               outptr, outlen);
229
230   /* Free our handles */
231   s_pSecFn->DeleteSecurityContext(&context);
232   s_pSecFn->FreeCredentialsHandle(&credentials);
233
234   /* Free the identity structure */
235   Curl_sspi_free_identity(p_identity);
236
237   /* Free the SPN */
238   free(spn);
239
240   /* Free the response buffer */
241   free(output_token);
242
243   /* Free the decoded challenge message */
244   free(input_token);
245
246   return result;
247 }
248
249 /*
250  * Curl_override_sspi_http_realm()
251  *
252  * This is used to populate the domain in a SSPI identity structure
253  * The realm is extracted from the challenge message and used as the
254  * domain if it is not already explicitly set.
255  *
256  * Parameters:
257  *
258  * chlg     [in]     - The challenge message.
259  * identity [in/out] - The identity structure.
260  *
261  * Returns CURLE_OK on success.
262  */
263 CURLcode Curl_override_sspi_http_realm(const char *chlg,
264                                        SEC_WINNT_AUTH_IDENTITY *identity)
265 {
266   xcharp_u domain, dup_domain;
267
268   /* If domain is blank or unset, check challenge message for realm */
269   if(!identity->Domain || !identity->DomainLength) {
270     for(;;) {
271       char value[DIGEST_MAX_VALUE_LENGTH];
272       char content[DIGEST_MAX_CONTENT_LENGTH];
273
274       /* Pass all additional spaces here */
275       while(*chlg && ISSPACE(*chlg))
276         chlg++;
277
278       /* Extract a value=content pair */
279       if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) {
280         if(Curl_raw_equal(value, "realm")) {
281
282           /* Setup identity's domain and length */
283           domain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *) content);
284           if(!domain.tchar_ptr)
285             return CURLE_OUT_OF_MEMORY;
286
287           dup_domain.tchar_ptr = _tcsdup(domain.tchar_ptr);
288           if(!dup_domain.tchar_ptr) {
289             Curl_unicodefree(domain.tchar_ptr);
290             return CURLE_OUT_OF_MEMORY;
291           }
292
293           free(identity->Domain);
294           identity->Domain = dup_domain.tbyte_ptr;
295           identity->DomainLength = curlx_uztoul(_tcslen(dup_domain.tchar_ptr));
296           dup_domain.tchar_ptr = NULL;
297
298           Curl_unicodefree(domain.tchar_ptr);
299         }
300         else {
301           /* Unknown specifier, ignore it! */
302         }
303       }
304       else
305         break; /* We're done here */
306
307       /* Pass all additional spaces here */
308       while(*chlg && ISSPACE(*chlg))
309         chlg++;
310
311       /* Allow the list to be comma-separated */
312       if(',' == *chlg)
313         chlg++;
314     }
315   }
316
317   return CURLE_OK;
318 }
319
320 /*
321  * Curl_auth_decode_digest_http_message()
322  *
323  * This is used to decode a HTTP DIGEST challenge message into the seperate
324  * attributes.
325  *
326  * Parameters:
327  *
328  * chlg    [in]     - The challenge message.
329  * digest  [in/out] - The digest data struct being used and modified.
330  *
331  * Returns CURLE_OK on success.
332  */
333 CURLcode Curl_auth_decode_digest_http_message(const char *chlg,
334                                               struct digestdata *digest)
335 {
336   size_t chlglen = strlen(chlg);
337
338   /* We had an input token before and we got another one now. This means we
339      provided bad credentials in the previous request. */
340   if(digest->input_token)
341     return CURLE_BAD_CONTENT_ENCODING;
342
343   /* Simply store the challenge for use later */
344   digest->input_token = (BYTE *) Curl_memdup(chlg, chlglen);
345   if(!digest->input_token)
346     return CURLE_OUT_OF_MEMORY;
347
348   digest->input_token_len = chlglen;
349
350   return CURLE_OK;
351 }
352
353 /*
354  * Curl_auth_create_digest_http_message()
355  *
356  * This is used to generate a HTTP DIGEST response message ready for sending
357  * to the recipient.
358  *
359  * Parameters:
360  *
361  * data    [in]     - The session handle.
362  * userp   [in]     - The user name in the format User or Domain\User.
363  * passdwp [in]     - The user's password.
364  * request [in]     - The HTTP request.
365  * uripath [in]     - The path of the HTTP uri.
366  * digest  [in/out] - The digest data struct being used and modified.
367  * outptr  [in/out] - The address where a pointer to newly allocated memory
368  *                    holding the result will be stored upon completion.
369  * outlen  [out]    - The length of the output message.
370  *
371  * Returns CURLE_OK on success.
372  */
373 CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data,
374                                               const char *userp,
375                                               const char *passwdp,
376                                               const unsigned char *request,
377                                               const unsigned char *uripath,
378                                               struct digestdata *digest,
379                                               char **outptr, size_t *outlen)
380 {
381   size_t token_max;
382   CredHandle credentials;
383   CtxtHandle context;
384   char *resp;
385   BYTE *output_token;
386   PSecPkgInfo SecurityPackage;
387   SEC_WINNT_AUTH_IDENTITY identity;
388   SEC_WINNT_AUTH_IDENTITY *p_identity;
389   SecBuffer chlg_buf[3];
390   SecBuffer resp_buf;
391   SecBufferDesc chlg_desc;
392   SecBufferDesc resp_desc;
393   SECURITY_STATUS status;
394   unsigned long attrs;
395   TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */
396   TCHAR *spn;
397
398   (void) data;
399
400   /* Query the security package for DigestSSP */
401   status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST),
402                                               &SecurityPackage);
403   if(status != SEC_E_OK)
404     return CURLE_NOT_BUILT_IN;
405
406   token_max = SecurityPackage->cbMaxToken;
407
408   /* Release the package buffer as it is not required anymore */
409   s_pSecFn->FreeContextBuffer(SecurityPackage);
410
411   if(userp && *userp) {
412     /* Populate our identity structure */
413     if(Curl_create_sspi_identity(userp, passwdp, &identity))
414       return CURLE_OUT_OF_MEMORY;
415
416     /* Populate our identity domain */
417     if(Curl_override_sspi_http_realm((const char*) digest->input_token,
418                                      &identity))
419       return CURLE_OUT_OF_MEMORY;
420
421     /* Allow proper cleanup of the identity structure */
422     p_identity = &identity;
423   }
424   else
425     /* Use the current Windows user */
426     p_identity = NULL;
427
428   /* Acquire our credentials handle */
429   status = s_pSecFn->AcquireCredentialsHandle(NULL,
430                                               (TCHAR *) TEXT(SP_NAME_DIGEST),
431                                               SECPKG_CRED_OUTBOUND, NULL,
432                                               p_identity, NULL, NULL,
433                                               &credentials, &expiry);
434   if(status != SEC_E_OK) {
435     Curl_sspi_free_identity(p_identity);
436
437     return CURLE_LOGIN_DENIED;
438   }
439
440   /* Allocate the output buffer according to the max token size as indicated
441      by the security package */
442   output_token = malloc(token_max);
443   if(!output_token) {
444     s_pSecFn->FreeCredentialsHandle(&credentials);
445
446     Curl_sspi_free_identity(p_identity);
447
448     return CURLE_OUT_OF_MEMORY;
449   }
450
451   /* Setup the challenge "input" security buffer if present */
452   chlg_desc.ulVersion    = SECBUFFER_VERSION;
453   chlg_desc.cBuffers     = 3;
454   chlg_desc.pBuffers     = chlg_buf;
455   chlg_buf[0].BufferType = SECBUFFER_TOKEN;
456   chlg_buf[0].pvBuffer   = digest->input_token;
457   chlg_buf[0].cbBuffer   = curlx_uztoul(digest->input_token_len);
458   chlg_buf[1].BufferType = SECBUFFER_PKG_PARAMS;
459   chlg_buf[1].pvBuffer   = (void *) request;
460   chlg_buf[1].cbBuffer   = curlx_uztoul(strlen((const char *) request));
461   chlg_buf[2].BufferType = SECBUFFER_PKG_PARAMS;
462   chlg_buf[2].pvBuffer   = NULL;
463   chlg_buf[2].cbBuffer   = 0;
464
465   /* Setup the response "output" security buffer */
466   resp_desc.ulVersion = SECBUFFER_VERSION;
467   resp_desc.cBuffers  = 1;
468   resp_desc.pBuffers  = &resp_buf;
469   resp_buf.BufferType = SECBUFFER_TOKEN;
470   resp_buf.pvBuffer   = output_token;
471   resp_buf.cbBuffer   = curlx_uztoul(token_max);
472
473   spn = Curl_convert_UTF8_to_tchar((char *) uripath);
474   if(!spn) {
475     s_pSecFn->FreeCredentialsHandle(&credentials);
476
477     Curl_sspi_free_identity(p_identity);
478     free(output_token);
479
480     return CURLE_OUT_OF_MEMORY;
481   }
482
483   /* Generate our reponse message */
484   status = s_pSecFn->InitializeSecurityContext(&credentials, NULL,
485                                                spn,
486                                                ISC_REQ_USE_HTTP_STYLE, 0, 0,
487                                                &chlg_desc, 0, &context,
488                                                &resp_desc, &attrs, &expiry);
489   Curl_unicodefree(spn);
490
491   if(status == SEC_I_COMPLETE_NEEDED ||
492      status == SEC_I_COMPLETE_AND_CONTINUE)
493     s_pSecFn->CompleteAuthToken(&credentials, &resp_desc);
494   else if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) {
495     s_pSecFn->FreeCredentialsHandle(&credentials);
496
497     Curl_sspi_free_identity(p_identity);
498     free(output_token);
499
500     return CURLE_OUT_OF_MEMORY;
501   }
502
503   resp = malloc(resp_buf.cbBuffer + 1);
504   if(!resp) {
505     s_pSecFn->DeleteSecurityContext(&context);
506     s_pSecFn->FreeCredentialsHandle(&credentials);
507
508     Curl_sspi_free_identity(p_identity);
509     free(output_token);
510
511     return CURLE_OUT_OF_MEMORY;
512   }
513
514   /* Copy the generated reponse */
515   memcpy(resp, resp_buf.pvBuffer, resp_buf.cbBuffer);
516   resp[resp_buf.cbBuffer] = 0x00;
517
518   /* Return the response */
519   *outptr = resp;
520   *outlen = resp_buf.cbBuffer;
521
522   /* Free our handles */
523   s_pSecFn->DeleteSecurityContext(&context);
524   s_pSecFn->FreeCredentialsHandle(&credentials);
525
526   /* Free the identity structure */
527   Curl_sspi_free_identity(p_identity);
528
529   /* Free the response buffer */
530   free(output_token);
531
532   return CURLE_OK;
533 }
534
535 /*
536  * Curl_auth_digest_cleanup()
537  *
538  * This is used to clean up the digest specific data.
539  *
540  * Parameters:
541  *
542  * digest    [in/out] - The digest data struct being cleaned up.
543  *
544  */
545 void Curl_auth_digest_cleanup(struct digestdata *digest)
546 {
547   /* Free the input token */
548   Curl_safefree(digest->input_token);
549
550   /* Reset any variables */
551   digest->input_token_len = 0;
552 }
553
554 #endif /* USE_WINDOWS_SSPI && !CURL_DISABLE_CRYPTO_AUTH */