xref: /curl/lib/vauth/krb5_sspi.c (revision cd2b4520)
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) Steve Holme, <steve_holme@hotmail.com>.
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 https://curl.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  * SPDX-License-Identifier: curl
22  *
23  * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
24  *
25  ***************************************************************************/
26 
27 #include "curl_setup.h"
28 
29 #if defined(USE_WINDOWS_SSPI) && defined(USE_KERBEROS5)
30 
31 #include <curl/curl.h>
32 
33 #include "vauth/vauth.h"
34 #include "urldata.h"
35 #include "warnless.h"
36 #include "curl_multibyte.h"
37 #include "sendf.h"
38 
39 /* The last #include files should be: */
40 #include "curl_memory.h"
41 #include "memdebug.h"
42 
43 /*
44  * Curl_auth_is_gssapi_supported()
45  *
46  * This is used to evaluate if GSSAPI (Kerberos V5) is supported.
47  *
48  * Parameters: None
49  *
50  * Returns TRUE if Kerberos V5 is supported by Windows SSPI.
51  */
Curl_auth_is_gssapi_supported(void)52 bool Curl_auth_is_gssapi_supported(void)
53 {
54   PSecPkgInfo SecurityPackage;
55   SECURITY_STATUS status;
56 
57   /* Query the security package for Kerberos */
58   status = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *)
59                                               TEXT(SP_NAME_KERBEROS),
60                                               &SecurityPackage);
61 
62   /* Release the package buffer as it is not required anymore */
63   if(status == SEC_E_OK) {
64     Curl_pSecFn->FreeContextBuffer(SecurityPackage);
65   }
66 
67   return (status == SEC_E_OK);
68 }
69 
70 /*
71  * Curl_auth_create_gssapi_user_message()
72  *
73  * This is used to generate an already encoded GSSAPI (Kerberos V5) user token
74  * message ready for sending to the recipient.
75  *
76  * Parameters:
77  *
78  * data        [in]     - The session handle.
79  * userp       [in]     - The username in the format User or Domain\User.
80  * passwdp     [in]     - The user's password.
81  * service     [in]     - The service type such as http, smtp, pop or imap.
82  * host        [in]     - The hostname.
83  * mutual_auth [in]     - Flag specifying whether or not mutual authentication
84  *                        is enabled.
85  * chlg        [in]     - Optional challenge message.
86  * krb5        [in/out] - The Kerberos 5 data struct being used and modified.
87  * out         [out]    - The result storage.
88  *
89  * Returns CURLE_OK on success.
90  */
Curl_auth_create_gssapi_user_message(struct Curl_easy * data,const char * userp,const char * passwdp,const char * service,const char * host,const bool mutual_auth,const struct bufref * chlg,struct kerberos5data * krb5,struct bufref * out)91 CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data,
92                                               const char *userp,
93                                               const char *passwdp,
94                                               const char *service,
95                                               const char *host,
96                                               const bool mutual_auth,
97                                               const struct bufref *chlg,
98                                               struct kerberos5data *krb5,
99                                               struct bufref *out)
100 {
101   CURLcode result = CURLE_OK;
102   CtxtHandle context;
103   PSecPkgInfo SecurityPackage;
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   if(!krb5->spn) {
113     /* Generate our SPN */
114     krb5->spn = Curl_auth_build_spn(service, host, NULL);
115     if(!krb5->spn)
116       return CURLE_OUT_OF_MEMORY;
117   }
118 
119   if(!krb5->output_token) {
120     /* Query the security package for Kerberos */
121     status = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *)
122                                                 TEXT(SP_NAME_KERBEROS),
123                                                 &SecurityPackage);
124     if(status != SEC_E_OK) {
125       failf(data, "SSPI: could not get auth info");
126       return CURLE_AUTH_ERROR;
127     }
128 
129     krb5->token_max = SecurityPackage->cbMaxToken;
130 
131     /* Release the package buffer as it is not required anymore */
132     Curl_pSecFn->FreeContextBuffer(SecurityPackage);
133 
134     /* Allocate our response buffer */
135     krb5->output_token = malloc(krb5->token_max);
136     if(!krb5->output_token)
137       return CURLE_OUT_OF_MEMORY;
138   }
139 
140   if(!krb5->credentials) {
141     /* Do we have credentials to use or are we using single sign-on? */
142     if(userp && *userp) {
143       /* Populate our identity structure */
144       result = Curl_create_sspi_identity(userp, passwdp, &krb5->identity);
145       if(result)
146         return result;
147 
148       /* Allow proper cleanup of the identity structure */
149       krb5->p_identity = &krb5->identity;
150     }
151     else
152       /* Use the current Windows user */
153       krb5->p_identity = NULL;
154 
155     /* Allocate our credentials handle */
156     krb5->credentials = calloc(1, sizeof(CredHandle));
157     if(!krb5->credentials)
158       return CURLE_OUT_OF_MEMORY;
159 
160     /* Acquire our credentials handle */
161     status = Curl_pSecFn->AcquireCredentialsHandle(NULL,
162                                                 (TCHAR *)
163                                                 TEXT(SP_NAME_KERBEROS),
164                                                 SECPKG_CRED_OUTBOUND, NULL,
165                                                 krb5->p_identity, NULL, NULL,
166                                                 krb5->credentials, &expiry);
167     if(status != SEC_E_OK)
168       return CURLE_LOGIN_DENIED;
169 
170     /* Allocate our new context handle */
171     krb5->context = calloc(1, sizeof(CtxtHandle));
172     if(!krb5->context)
173       return CURLE_OUT_OF_MEMORY;
174   }
175 
176   if(chlg) {
177     if(!Curl_bufref_len(chlg)) {
178       infof(data, "GSSAPI handshake failure (empty challenge message)");
179       return CURLE_BAD_CONTENT_ENCODING;
180     }
181 
182     /* Setup the challenge "input" security buffer */
183     chlg_desc.ulVersion = SECBUFFER_VERSION;
184     chlg_desc.cBuffers  = 1;
185     chlg_desc.pBuffers  = &chlg_buf;
186     chlg_buf.BufferType = SECBUFFER_TOKEN;
187     chlg_buf.pvBuffer   = (void *) Curl_bufref_ptr(chlg);
188     chlg_buf.cbBuffer   = curlx_uztoul(Curl_bufref_len(chlg));
189   }
190 
191   /* Setup the response "output" security buffer */
192   resp_desc.ulVersion = SECBUFFER_VERSION;
193   resp_desc.cBuffers  = 1;
194   resp_desc.pBuffers  = &resp_buf;
195   resp_buf.BufferType = SECBUFFER_TOKEN;
196   resp_buf.pvBuffer   = krb5->output_token;
197   resp_buf.cbBuffer   = curlx_uztoul(krb5->token_max);
198 
199   /* Generate our challenge-response message */
200   status = Curl_pSecFn->InitializeSecurityContext(krb5->credentials,
201                                                chlg ? krb5->context : NULL,
202                                                krb5->spn,
203                                                (mutual_auth ?
204                                                 ISC_REQ_MUTUAL_AUTH : 0),
205                                                0, SECURITY_NATIVE_DREP,
206                                                chlg ? &chlg_desc : NULL, 0,
207                                                &context,
208                                                &resp_desc, &attrs,
209                                                &expiry);
210 
211   if(status == SEC_E_INSUFFICIENT_MEMORY)
212     return CURLE_OUT_OF_MEMORY;
213 
214   if(status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED)
215     return CURLE_AUTH_ERROR;
216 
217   if(memcmp(&context, krb5->context, sizeof(context))) {
218     Curl_pSecFn->DeleteSecurityContext(krb5->context);
219 
220     memcpy(krb5->context, &context, sizeof(context));
221   }
222 
223   if(resp_buf.cbBuffer) {
224     result = Curl_bufref_memdup(out, resp_buf.pvBuffer, resp_buf.cbBuffer);
225   }
226   else if(mutual_auth)
227     Curl_bufref_set(out, "", 0, NULL);
228   else
229     Curl_bufref_set(out, NULL, 0, NULL);
230 
231   return result;
232 }
233 
234 /*
235  * Curl_auth_create_gssapi_security_message()
236  *
237  * This is used to generate an already encoded GSSAPI (Kerberos V5) security
238  * token message ready for sending to the recipient.
239  *
240  * Parameters:
241  *
242  * data    [in]     - The session handle.
243  * authzid [in]     - The authorization identity if some.
244  * chlg    [in]     - The optional challenge message.
245  * krb5    [in/out] - The Kerberos 5 data struct being used and modified.
246  * out     [out]    - The result storage.
247  *
248  * Returns CURLE_OK on success.
249  */
Curl_auth_create_gssapi_security_message(struct Curl_easy * data,const char * authzid,const struct bufref * chlg,struct kerberos5data * krb5,struct bufref * out)250 CURLcode Curl_auth_create_gssapi_security_message(struct Curl_easy *data,
251                                                   const char *authzid,
252                                                   const struct bufref *chlg,
253                                                   struct kerberos5data *krb5,
254                                                   struct bufref *out)
255 {
256   size_t offset = 0;
257   size_t messagelen = 0;
258   size_t appdatalen = 0;
259   unsigned char *trailer = NULL;
260   unsigned char *message = NULL;
261   unsigned char *padding = NULL;
262   unsigned char *appdata = NULL;
263   SecBuffer input_buf[2];
264   SecBuffer wrap_buf[3];
265   SecBufferDesc input_desc;
266   SecBufferDesc wrap_desc;
267   unsigned char *indata;
268   unsigned long qop = 0;
269   unsigned long sec_layer = 0;
270   unsigned long max_size = 0;
271   SecPkgContext_Sizes sizes;
272   SECURITY_STATUS status;
273 
274 #if defined(CURL_DISABLE_VERBOSE_STRINGS)
275   (void) data;
276 #endif
277 
278   /* Ensure we have a valid challenge message */
279   if(!Curl_bufref_len(chlg)) {
280     infof(data, "GSSAPI handshake failure (empty security message)");
281     return CURLE_BAD_CONTENT_ENCODING;
282   }
283 
284   /* Get our response size information */
285   status = Curl_pSecFn->QueryContextAttributes(krb5->context,
286                                             SECPKG_ATTR_SIZES,
287                                             &sizes);
288 
289   if(status == SEC_E_INSUFFICIENT_MEMORY)
290     return CURLE_OUT_OF_MEMORY;
291 
292   if(status != SEC_E_OK)
293     return CURLE_AUTH_ERROR;
294 
295   /* Setup the "input" security buffer */
296   input_desc.ulVersion = SECBUFFER_VERSION;
297   input_desc.cBuffers = 2;
298   input_desc.pBuffers = input_buf;
299   input_buf[0].BufferType = SECBUFFER_STREAM;
300   input_buf[0].pvBuffer = (void *) Curl_bufref_ptr(chlg);
301   input_buf[0].cbBuffer = curlx_uztoul(Curl_bufref_len(chlg));
302   input_buf[1].BufferType = SECBUFFER_DATA;
303   input_buf[1].pvBuffer = NULL;
304   input_buf[1].cbBuffer = 0;
305 
306   /* Decrypt the inbound challenge and obtain the qop */
307   status = Curl_pSecFn->DecryptMessage(krb5->context, &input_desc, 0, &qop);
308   if(status != SEC_E_OK) {
309     infof(data, "GSSAPI handshake failure (empty security message)");
310     return CURLE_BAD_CONTENT_ENCODING;
311   }
312 
313   /* Not 4 octets long so fail as per RFC4752 Section 3.1 */
314   if(input_buf[1].cbBuffer != 4) {
315     infof(data, "GSSAPI handshake failure (invalid security data)");
316     return CURLE_BAD_CONTENT_ENCODING;
317   }
318 
319   /* Extract the security layer and the maximum message size */
320   indata = input_buf[1].pvBuffer;
321   sec_layer = indata[0];
322   max_size = ((unsigned long)indata[1] << 16) |
323              ((unsigned long)indata[2] << 8) | indata[3];
324 
325   /* Free the challenge as it is not required anymore */
326   Curl_pSecFn->FreeContextBuffer(input_buf[1].pvBuffer);
327 
328   /* Process the security layer */
329   if(!(sec_layer & KERB_WRAP_NO_ENCRYPT)) {
330     infof(data, "GSSAPI handshake failure (invalid security layer)");
331     return CURLE_BAD_CONTENT_ENCODING;
332   }
333   sec_layer &= KERB_WRAP_NO_ENCRYPT;  /* We do not support a security layer */
334 
335   /* Process the maximum message size the server can receive */
336   if(max_size > 0) {
337     /* The server has told us it supports a maximum receive buffer, however, as
338        we do not require one unless we are encrypting data, we tell the server
339        our receive buffer is zero. */
340     max_size = 0;
341   }
342 
343   /* Allocate the trailer */
344   trailer = malloc(sizes.cbSecurityTrailer);
345   if(!trailer)
346     return CURLE_OUT_OF_MEMORY;
347 
348   /* Allocate our message */
349   messagelen = 4;
350   if(authzid)
351     messagelen += strlen(authzid);
352   message = malloc(messagelen);
353   if(!message) {
354     free(trailer);
355 
356     return CURLE_OUT_OF_MEMORY;
357   }
358 
359   /* Populate the message with the security layer and client supported receive
360      message size. */
361   message[0] = sec_layer & 0xFF;
362   message[1] = (max_size >> 16) & 0xFF;
363   message[2] = (max_size >> 8) & 0xFF;
364   message[3] = max_size & 0xFF;
365 
366   /* If given, append the authorization identity. */
367 
368   if(authzid && *authzid)
369     memcpy(message + 4, authzid, messagelen - 4);
370 
371   /* Allocate the padding */
372   padding = malloc(sizes.cbBlockSize);
373   if(!padding) {
374     free(message);
375     free(trailer);
376 
377     return CURLE_OUT_OF_MEMORY;
378   }
379 
380   /* Setup the "authentication data" security buffer */
381   wrap_desc.ulVersion    = SECBUFFER_VERSION;
382   wrap_desc.cBuffers     = 3;
383   wrap_desc.pBuffers     = wrap_buf;
384   wrap_buf[0].BufferType = SECBUFFER_TOKEN;
385   wrap_buf[0].pvBuffer   = trailer;
386   wrap_buf[0].cbBuffer   = sizes.cbSecurityTrailer;
387   wrap_buf[1].BufferType = SECBUFFER_DATA;
388   wrap_buf[1].pvBuffer   = message;
389   wrap_buf[1].cbBuffer   = curlx_uztoul(messagelen);
390   wrap_buf[2].BufferType = SECBUFFER_PADDING;
391   wrap_buf[2].pvBuffer   = padding;
392   wrap_buf[2].cbBuffer   = sizes.cbBlockSize;
393 
394   /* Encrypt the data */
395   status = Curl_pSecFn->EncryptMessage(krb5->context, KERB_WRAP_NO_ENCRYPT,
396                                     &wrap_desc, 0);
397   if(status != SEC_E_OK) {
398     free(padding);
399     free(message);
400     free(trailer);
401 
402     if(status == SEC_E_INSUFFICIENT_MEMORY)
403       return CURLE_OUT_OF_MEMORY;
404 
405     return CURLE_AUTH_ERROR;
406   }
407 
408   /* Allocate the encryption (wrap) buffer */
409   appdatalen = wrap_buf[0].cbBuffer + wrap_buf[1].cbBuffer +
410                wrap_buf[2].cbBuffer;
411   appdata = malloc(appdatalen);
412   if(!appdata) {
413     free(padding);
414     free(message);
415     free(trailer);
416 
417     return CURLE_OUT_OF_MEMORY;
418   }
419 
420   /* Populate the encryption buffer */
421   memcpy(appdata, wrap_buf[0].pvBuffer, wrap_buf[0].cbBuffer);
422   offset += wrap_buf[0].cbBuffer;
423   memcpy(appdata + offset, wrap_buf[1].pvBuffer, wrap_buf[1].cbBuffer);
424   offset += wrap_buf[1].cbBuffer;
425   memcpy(appdata + offset, wrap_buf[2].pvBuffer, wrap_buf[2].cbBuffer);
426 
427   /* Free all of our local buffers */
428   free(padding);
429   free(message);
430   free(trailer);
431 
432   /* Return the response. */
433   Curl_bufref_set(out, appdata, appdatalen, curl_free);
434   return CURLE_OK;
435 }
436 
437 /*
438  * Curl_auth_cleanup_gssapi()
439  *
440  * This is used to clean up the GSSAPI (Kerberos V5) specific data.
441  *
442  * Parameters:
443  *
444  * krb5     [in/out] - The Kerberos 5 data struct being cleaned up.
445  *
446  */
Curl_auth_cleanup_gssapi(struct kerberos5data * krb5)447 void Curl_auth_cleanup_gssapi(struct kerberos5data *krb5)
448 {
449   /* Free our security context */
450   if(krb5->context) {
451     Curl_pSecFn->DeleteSecurityContext(krb5->context);
452     free(krb5->context);
453     krb5->context = NULL;
454   }
455 
456   /* Free our credentials handle */
457   if(krb5->credentials) {
458     Curl_pSecFn->FreeCredentialsHandle(krb5->credentials);
459     free(krb5->credentials);
460     krb5->credentials = NULL;
461   }
462 
463   /* Free our identity */
464   Curl_sspi_free_identity(krb5->p_identity);
465   krb5->p_identity = NULL;
466 
467   /* Free the SPN and output token */
468   Curl_safefree(krb5->spn);
469   Curl_safefree(krb5->output_token);
470 
471   /* Reset any variables */
472   krb5->token_max = 0;
473 }
474 
475 #endif /* USE_WINDOWS_SSPI && USE_KERBEROS5 */
476