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