xref: /curl/lib/vauth/spnego_sspi.c (revision cd2b4520)
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 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 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  * RFC4178 Simple and Protected GSS-API Negotiation Mechanism
24  *
25  ***************************************************************************/
26 
27 #include "curl_setup.h"
28 
29 #if defined(USE_WINDOWS_SSPI) && defined(USE_SPNEGO)
30 
31 #include <curl/curl.h>
32 
33 #include "vauth/vauth.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 "strerror.h"
40 
41 /* The last #include files should be: */
42 #include "curl_memory.h"
43 #include "memdebug.h"
44 
45 /*
46  * Curl_auth_is_spnego_supported()
47  *
48  * This is used to evaluate if SPNEGO (Negotiate) is supported.
49  *
50  * Parameters: None
51  *
52  * Returns TRUE if Negotiate is supported by Windows SSPI.
53  */
Curl_auth_is_spnego_supported(void)54 bool Curl_auth_is_spnego_supported(void)
55 {
56   PSecPkgInfo SecurityPackage;
57   SECURITY_STATUS status;
58 
59   /* Query the security package for Negotiate */
60   status = Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *)
61                                               TEXT(SP_NAME_NEGOTIATE),
62                                               &SecurityPackage);
63 
64   /* Release the package buffer as it is not required anymore */
65   if(status == SEC_E_OK) {
66     Curl_pSecFn->FreeContextBuffer(SecurityPackage);
67   }
68 
69 
70   return (status == SEC_E_OK);
71 }
72 
73 /*
74  * Curl_auth_decode_spnego_message()
75  *
76  * This is used to decode an already encoded SPNEGO (Negotiate) challenge
77  * message.
78  *
79  * Parameters:
80  *
81  * data        [in]     - The session handle.
82  * user        [in]     - The username in the format User or Domain\User.
83  * password    [in]     - The user's password.
84  * service     [in]     - The service type such as http, smtp, pop or imap.
85  * host        [in]     - The hostname.
86  * chlg64      [in]     - The optional base64 encoded challenge message.
87  * nego        [in/out] - The Negotiate data struct being used and modified.
88  *
89  * Returns CURLE_OK on success.
90  */
Curl_auth_decode_spnego_message(struct Curl_easy * data,const char * user,const char * password,const char * service,const char * host,const char * chlg64,struct negotiatedata * nego)91 CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data,
92                                          const char *user,
93                                          const char *password,
94                                          const char *service,
95                                          const char *host,
96                                          const char *chlg64,
97                                          struct negotiatedata *nego)
98 {
99   CURLcode result = CURLE_OK;
100   size_t chlglen = 0;
101   unsigned char *chlg = NULL;
102   PSecPkgInfo SecurityPackage;
103   SecBuffer chlg_buf[2];
104   SecBuffer resp_buf;
105   SecBufferDesc chlg_desc;
106   SecBufferDesc resp_desc;
107   unsigned long attrs;
108   TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */
109 
110 #if defined(CURL_DISABLE_VERBOSE_STRINGS)
111   (void) data;
112 #endif
113 
114   if(nego->context && nego->status == SEC_E_OK) {
115     /* We finished successfully our part of authentication, but server
116      * rejected it (since we are again here). Exit with an error since we
117      * cannot invent anything better */
118     Curl_auth_cleanup_spnego(nego);
119     return CURLE_LOGIN_DENIED;
120   }
121 
122   if(!nego->spn) {
123     /* Generate our SPN */
124     nego->spn = Curl_auth_build_spn(service, host, NULL);
125     if(!nego->spn)
126       return CURLE_OUT_OF_MEMORY;
127   }
128 
129   if(!nego->output_token) {
130     /* Query the security package for Negotiate */
131     nego->status = (DWORD)Curl_pSecFn->QuerySecurityPackageInfo((TCHAR *)
132                                                        TEXT(SP_NAME_NEGOTIATE),
133                                                        &SecurityPackage);
134     if(nego->status != SEC_E_OK) {
135       failf(data, "SSPI: could not get auth info");
136       return CURLE_AUTH_ERROR;
137     }
138 
139     nego->token_max = SecurityPackage->cbMaxToken;
140 
141     /* Release the package buffer as it is not required anymore */
142     Curl_pSecFn->FreeContextBuffer(SecurityPackage);
143 
144     /* Allocate our output buffer */
145     nego->output_token = malloc(nego->token_max);
146     if(!nego->output_token)
147       return CURLE_OUT_OF_MEMORY;
148  }
149 
150   if(!nego->credentials) {
151     /* Do we have credentials to use or are we using single sign-on? */
152     if(user && *user) {
153       /* Populate our identity structure */
154       result = Curl_create_sspi_identity(user, password, &nego->identity);
155       if(result)
156         return result;
157 
158       /* Allow proper cleanup of the identity structure */
159       nego->p_identity = &nego->identity;
160     }
161     else
162       /* Use the current Windows user */
163       nego->p_identity = NULL;
164 
165     /* Allocate our credentials handle */
166     nego->credentials = calloc(1, sizeof(CredHandle));
167     if(!nego->credentials)
168       return CURLE_OUT_OF_MEMORY;
169 
170     /* Acquire our credentials handle */
171     nego->status = (DWORD)
172       Curl_pSecFn->AcquireCredentialsHandle(NULL,
173                                          (TCHAR *)TEXT(SP_NAME_NEGOTIATE),
174                                          SECPKG_CRED_OUTBOUND, NULL,
175                                          nego->p_identity, NULL, NULL,
176                                          nego->credentials, &expiry);
177     if(nego->status != SEC_E_OK)
178       return CURLE_AUTH_ERROR;
179 
180     /* Allocate our new context handle */
181     nego->context = calloc(1, sizeof(CtxtHandle));
182     if(!nego->context)
183       return CURLE_OUT_OF_MEMORY;
184   }
185 
186   if(chlg64 && *chlg64) {
187     /* Decode the base-64 encoded challenge message */
188     if(*chlg64 != '=') {
189       result = Curl_base64_decode(chlg64, &chlg, &chlglen);
190       if(result)
191         return result;
192     }
193 
194     /* Ensure we have a valid challenge message */
195     if(!chlg) {
196       infof(data, "SPNEGO handshake failure (empty challenge message)");
197       return CURLE_BAD_CONTENT_ENCODING;
198     }
199 
200     /* Setup the challenge "input" security buffer */
201     chlg_desc.ulVersion    = SECBUFFER_VERSION;
202     chlg_desc.cBuffers     = 1;
203     chlg_desc.pBuffers     = &chlg_buf[0];
204     chlg_buf[0].BufferType = SECBUFFER_TOKEN;
205     chlg_buf[0].pvBuffer   = chlg;
206     chlg_buf[0].cbBuffer   = curlx_uztoul(chlglen);
207 
208 #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS
209     /* ssl context comes from Schannel.
210     * When extended protection is used in IIS server,
211     * we have to pass a second SecBuffer to the SecBufferDesc
212     * otherwise IIS will not pass the authentication (401 response).
213     * Minimum supported version is Windows 7.
214     * https://docs.microsoft.com/en-us/security-updates
215     * /SecurityAdvisories/2009/973811
216     */
217     if(nego->sslContext) {
218       SEC_CHANNEL_BINDINGS channelBindings;
219       SecPkgContext_Bindings pkgBindings;
220       pkgBindings.Bindings = &channelBindings;
221       nego->status = (DWORD)Curl_pSecFn->QueryContextAttributes(
222           nego->sslContext,
223           SECPKG_ATTR_ENDPOINT_BINDINGS,
224           &pkgBindings
225       );
226       if(nego->status == SEC_E_OK) {
227         chlg_desc.cBuffers++;
228         chlg_buf[1].BufferType = SECBUFFER_CHANNEL_BINDINGS;
229         chlg_buf[1].cbBuffer   = pkgBindings.BindingsLength;
230         chlg_buf[1].pvBuffer   = pkgBindings.Bindings;
231       }
232     }
233 #endif
234   }
235 
236   /* Setup the response "output" security buffer */
237   resp_desc.ulVersion = SECBUFFER_VERSION;
238   resp_desc.cBuffers  = 1;
239   resp_desc.pBuffers  = &resp_buf;
240   resp_buf.BufferType = SECBUFFER_TOKEN;
241   resp_buf.pvBuffer   = nego->output_token;
242   resp_buf.cbBuffer   = curlx_uztoul(nego->token_max);
243 
244   /* Generate our challenge-response message */
245   nego->status =
246     (DWORD)Curl_pSecFn->InitializeSecurityContext(nego->credentials,
247                                                   chlg ? nego->context : NULL,
248                                                   nego->spn,
249                                                   ISC_REQ_CONFIDENTIALITY,
250                                                   0, SECURITY_NATIVE_DREP,
251                                                   chlg ? &chlg_desc : NULL,
252                                                   0, nego->context,
253                                                   &resp_desc, &attrs,
254                                                   &expiry);
255 
256   /* Free the decoded challenge as it is not required anymore */
257   free(chlg);
258 
259   if(GSS_ERROR(nego->status)) {
260     char buffer[STRERROR_LEN];
261     failf(data, "InitializeSecurityContext failed: %s",
262           Curl_sspi_strerror((int)nego->status, buffer, sizeof(buffer)));
263 
264     if(nego->status == (DWORD)SEC_E_INSUFFICIENT_MEMORY)
265       return CURLE_OUT_OF_MEMORY;
266 
267     return CURLE_AUTH_ERROR;
268   }
269 
270   if(nego->status == SEC_I_COMPLETE_NEEDED ||
271      nego->status == SEC_I_COMPLETE_AND_CONTINUE) {
272     nego->status = (DWORD)Curl_pSecFn->CompleteAuthToken(nego->context,
273                                                       &resp_desc);
274     if(GSS_ERROR(nego->status)) {
275       char buffer[STRERROR_LEN];
276       failf(data, "CompleteAuthToken failed: %s",
277             Curl_sspi_strerror((int)nego->status, buffer, sizeof(buffer)));
278 
279       if(nego->status == (DWORD)SEC_E_INSUFFICIENT_MEMORY)
280         return CURLE_OUT_OF_MEMORY;
281 
282       return CURLE_AUTH_ERROR;
283     }
284   }
285 
286   nego->output_token_length = resp_buf.cbBuffer;
287 
288   return result;
289 }
290 
291 /*
292  * Curl_auth_create_spnego_message()
293  *
294  * This is used to generate an already encoded SPNEGO (Negotiate) response
295  * message ready for sending to the recipient.
296  *
297  * Parameters:
298  *
299  * data        [in]     - The session handle.
300  * nego        [in/out] - The Negotiate data struct being used and modified.
301  * outptr      [in/out] - The address where a pointer to newly allocated memory
302  *                        holding the result will be stored upon completion.
303  * outlen      [out]    - The length of the output message.
304  *
305  * Returns CURLE_OK on success.
306  */
Curl_auth_create_spnego_message(struct negotiatedata * nego,char ** outptr,size_t * outlen)307 CURLcode Curl_auth_create_spnego_message(struct negotiatedata *nego,
308                                          char **outptr, size_t *outlen)
309 {
310   /* Base64 encode the already generated response */
311   CURLcode result = Curl_base64_encode((const char *) nego->output_token,
312                                        nego->output_token_length, outptr,
313                                        outlen);
314   if(!result && (!*outptr || !*outlen)) {
315     free(*outptr);
316     result = CURLE_REMOTE_ACCESS_DENIED;
317   }
318 
319   return result;
320 }
321 
322 /*
323  * Curl_auth_cleanup_spnego()
324  *
325  * This is used to clean up the SPNEGO (Negotiate) specific data.
326  *
327  * Parameters:
328  *
329  * nego     [in/out] - The Negotiate data struct being cleaned up.
330  *
331  */
Curl_auth_cleanup_spnego(struct negotiatedata * nego)332 void Curl_auth_cleanup_spnego(struct negotiatedata *nego)
333 {
334   /* Free our security context */
335   if(nego->context) {
336     Curl_pSecFn->DeleteSecurityContext(nego->context);
337     free(nego->context);
338     nego->context = NULL;
339   }
340 
341   /* Free our credentials handle */
342   if(nego->credentials) {
343     Curl_pSecFn->FreeCredentialsHandle(nego->credentials);
344     free(nego->credentials);
345     nego->credentials = NULL;
346   }
347 
348   /* Free our identity */
349   Curl_sspi_free_identity(nego->p_identity);
350   nego->p_identity = NULL;
351 
352   /* Free the SPN and output token */
353   Curl_safefree(nego->spn);
354   Curl_safefree(nego->output_token);
355 
356   /* Reset any variables */
357   nego->status = 0;
358   nego->token_max = 0;
359   nego->noauthpersist = FALSE;
360   nego->havenoauthpersist = FALSE;
361   nego->havenegdata = FALSE;
362   nego->havemultiplerequests = FALSE;
363 }
364 
365 #endif /* USE_WINDOWS_SSPI && USE_SPNEGO */
366