1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // See "SSPI Sample Application" at
6 // http://msdn.microsoft.com/en-us/library/aa918273.aspx
7
8 #include "net/http/http_auth_sspi_win.h"
9
10 #include "base/base64.h"
11 #include "base/logging.h"
12 #include "base/strings/string_piece.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/values.h"
17 #include "net/base/net_errors.h"
18 #include "net/http/http_auth.h"
19 #include "net/http/http_auth_multi_round_parse.h"
20 #include "net/log/net_log.h"
21 #include "net/log/net_log_event_type.h"
22 #include "net/log/net_log_values.h"
23 #include "net/log/net_log_with_source.h"
24
25 namespace net {
26 using DelegationType = HttpAuth::DelegationType;
27
28 namespace {
29
SecurityStatusToValue(Error mapped_error,SECURITY_STATUS status)30 base::Value::Dict SecurityStatusToValue(Error mapped_error,
31 SECURITY_STATUS status) {
32 base::Value::Dict params;
33 params.Set("net_error", mapped_error);
34 params.Set("security_status", static_cast<int>(status));
35 return params;
36 }
37
AcquireCredentialsHandleParams(const std::u16string * domain,const std::u16string * user,Error result,SECURITY_STATUS status)38 base::Value::Dict AcquireCredentialsHandleParams(const std::u16string* domain,
39 const std::u16string* user,
40 Error result,
41 SECURITY_STATUS status) {
42 base::Value::Dict params;
43 if (domain && user) {
44 params.Set("domain", base::UTF16ToUTF8(*domain));
45 params.Set("user", base::UTF16ToUTF8(*user));
46 }
47 params.Set("status", SecurityStatusToValue(result, status));
48 return params;
49 }
50
ContextFlagsToValue(DWORD flags)51 base::Value::Dict ContextFlagsToValue(DWORD flags) {
52 base::Value::Dict params;
53 params.Set("value", base::StringPrintf("0x%08lx", flags));
54 params.Set("delegated", (flags & ISC_RET_DELEGATE) == ISC_RET_DELEGATE);
55 params.Set("mutual", (flags & ISC_RET_MUTUAL_AUTH) == ISC_RET_MUTUAL_AUTH);
56 return params;
57 }
58
ContextAttributesToValue(SSPILibrary * library,PCtxtHandle handle,DWORD attributes)59 base::Value::Dict ContextAttributesToValue(SSPILibrary* library,
60 PCtxtHandle handle,
61 DWORD attributes) {
62 base::Value::Dict params;
63
64 SecPkgContext_NativeNames native_names = {0};
65 auto qc_result = library->QueryContextAttributesEx(
66 handle, SECPKG_ATTR_NATIVE_NAMES, &native_names, sizeof(native_names));
67 if (qc_result == SEC_E_OK && native_names.sClientName &&
68 native_names.sServerName) {
69 params.Set("source", base::as_u16cstr(native_names.sClientName));
70 params.Set("target", base::as_u16cstr(native_names.sServerName));
71 }
72
73 SecPkgContext_NegotiationInfo negotiation_info = {0};
74 qc_result = library->QueryContextAttributesEx(
75 handle, SECPKG_ATTR_NEGOTIATION_INFO, &negotiation_info,
76 sizeof(negotiation_info));
77 if (qc_result == SEC_E_OK && negotiation_info.PackageInfo &&
78 negotiation_info.PackageInfo->Name) {
79 params.Set("mechanism",
80 base::as_u16cstr(negotiation_info.PackageInfo->Name));
81 params.Set("open", negotiation_info.NegotiationState !=
82 SECPKG_NEGOTIATION_COMPLETE);
83 }
84
85 SecPkgContext_Authority authority = {0};
86 qc_result = library->QueryContextAttributesEx(handle, SECPKG_ATTR_AUTHORITY,
87 &authority, sizeof(authority));
88 if (qc_result == SEC_E_OK && authority.sAuthorityName) {
89 params.Set("authority", base::as_u16cstr(authority.sAuthorityName));
90 }
91
92 params.Set("flags", ContextFlagsToValue(attributes));
93 return params;
94 }
95
InitializeSecurityContextParams(SSPILibrary * library,PCtxtHandle handle,Error result,SECURITY_STATUS status,DWORD attributes)96 base::Value::Dict InitializeSecurityContextParams(SSPILibrary* library,
97 PCtxtHandle handle,
98 Error result,
99 SECURITY_STATUS status,
100 DWORD attributes) {
101 base::Value::Dict params;
102 params.Set("status", SecurityStatusToValue(result, status));
103 if (result == OK) {
104 params.Set("context",
105 ContextAttributesToValue(library, handle, attributes));
106 }
107 return params;
108 }
109
MapAcquireCredentialsStatusToError(SECURITY_STATUS status)110 Error MapAcquireCredentialsStatusToError(SECURITY_STATUS status) {
111 switch (status) {
112 case SEC_E_OK:
113 return OK;
114 case SEC_E_INSUFFICIENT_MEMORY:
115 return ERR_OUT_OF_MEMORY;
116 case SEC_E_INTERNAL_ERROR:
117 return ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS;
118 case SEC_E_NO_CREDENTIALS:
119 case SEC_E_NOT_OWNER:
120 case SEC_E_UNKNOWN_CREDENTIALS:
121 return ERR_INVALID_AUTH_CREDENTIALS;
122 case SEC_E_SECPKG_NOT_FOUND:
123 // This indicates that the SSPI configuration does not match expectations
124 return ERR_UNSUPPORTED_AUTH_SCHEME;
125 default:
126 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
127 }
128 }
129
AcquireExplicitCredentials(SSPILibrary * library,const std::u16string & domain,const std::u16string & user,const std::u16string & password,const NetLogWithSource & net_log,CredHandle * cred)130 Error AcquireExplicitCredentials(SSPILibrary* library,
131 const std::u16string& domain,
132 const std::u16string& user,
133 const std::u16string& password,
134 const NetLogWithSource& net_log,
135 CredHandle* cred) {
136 SEC_WINNT_AUTH_IDENTITY identity;
137 identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
138 identity.User = reinterpret_cast<unsigned short*>(
139 const_cast<wchar_t*>(base::as_wcstr(user)));
140 identity.UserLength = user.size();
141 identity.Domain = reinterpret_cast<unsigned short*>(
142 const_cast<wchar_t*>(base::as_wcstr(domain)));
143 identity.DomainLength = domain.size();
144 identity.Password = reinterpret_cast<unsigned short*>(
145 const_cast<wchar_t*>(base::as_wcstr(password)));
146 identity.PasswordLength = password.size();
147
148 TimeStamp expiry;
149
150 net_log.BeginEvent(NetLogEventType::AUTH_LIBRARY_ACQUIRE_CREDS);
151
152 // Pass the username/password to get the credentials handle.
153 SECURITY_STATUS status = library->AcquireCredentialsHandle(
154 nullptr, // pszPrincipal
155 SECPKG_CRED_OUTBOUND, // fCredentialUse
156 nullptr, // pvLogonID
157 &identity, // pAuthData
158 nullptr, // pGetKeyFn (not used)
159 nullptr, // pvGetKeyArgument (not used)
160 cred, // phCredential
161 &expiry); // ptsExpiry
162
163 auto result = MapAcquireCredentialsStatusToError(status);
164 net_log.EndEvent(NetLogEventType::AUTH_LIBRARY_ACQUIRE_CREDS, [&] {
165 return AcquireCredentialsHandleParams(&domain, &user, result, status);
166 });
167 return result;
168 }
169
AcquireDefaultCredentials(SSPILibrary * library,const NetLogWithSource & net_log,CredHandle * cred)170 Error AcquireDefaultCredentials(SSPILibrary* library,
171 const NetLogWithSource& net_log,
172 CredHandle* cred) {
173 TimeStamp expiry;
174 net_log.BeginEvent(NetLogEventType::AUTH_LIBRARY_ACQUIRE_CREDS);
175
176 // Pass the username/password to get the credentials handle.
177 // Note: Since the 5th argument is nullptr, it uses the default
178 // cached credentials for the logged in user, which can be used
179 // for a single sign-on.
180 SECURITY_STATUS status = library->AcquireCredentialsHandle(
181 nullptr, // pszPrincipal
182 SECPKG_CRED_OUTBOUND, // fCredentialUse
183 nullptr, // pvLogonID
184 nullptr, // pAuthData
185 nullptr, // pGetKeyFn (not used)
186 nullptr, // pvGetKeyArgument (not used)
187 cred, // phCredential
188 &expiry); // ptsExpiry
189
190 auto result = MapAcquireCredentialsStatusToError(status);
191 net_log.EndEvent(NetLogEventType::AUTH_LIBRARY_ACQUIRE_CREDS, [&] {
192 return AcquireCredentialsHandleParams(nullptr, nullptr, result, status);
193 });
194 return result;
195 }
196
MapInitializeSecurityContextStatusToError(SECURITY_STATUS status)197 Error MapInitializeSecurityContextStatusToError(SECURITY_STATUS status) {
198 switch (status) {
199 case SEC_E_OK:
200 case SEC_I_CONTINUE_NEEDED:
201 return OK;
202 case SEC_I_COMPLETE_AND_CONTINUE:
203 case SEC_I_COMPLETE_NEEDED:
204 case SEC_I_INCOMPLETE_CREDENTIALS:
205 case SEC_E_INCOMPLETE_MESSAGE:
206 case SEC_E_INTERNAL_ERROR:
207 // These are return codes reported by InitializeSecurityContext
208 // but not expected by Chrome (for example, INCOMPLETE_CREDENTIALS
209 // and INCOMPLETE_MESSAGE are intended for schannel).
210 return ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS;
211 case SEC_E_INSUFFICIENT_MEMORY:
212 return ERR_OUT_OF_MEMORY;
213 case SEC_E_UNSUPPORTED_FUNCTION:
214 NOTREACHED();
215 return ERR_UNEXPECTED;
216 case SEC_E_INVALID_HANDLE:
217 NOTREACHED();
218 return ERR_INVALID_HANDLE;
219 case SEC_E_INVALID_TOKEN:
220 return ERR_INVALID_RESPONSE;
221 case SEC_E_LOGON_DENIED:
222 case SEC_E_NO_CREDENTIALS:
223 case SEC_E_WRONG_PRINCIPAL:
224 return ERR_INVALID_AUTH_CREDENTIALS;
225 case SEC_E_NO_AUTHENTICATING_AUTHORITY:
226 case SEC_E_TARGET_UNKNOWN:
227 return ERR_MISCONFIGURED_AUTH_ENVIRONMENT;
228 default:
229 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
230 }
231 }
232
MapQuerySecurityPackageInfoStatusToError(SECURITY_STATUS status)233 Error MapQuerySecurityPackageInfoStatusToError(SECURITY_STATUS status) {
234 switch (status) {
235 case SEC_E_OK:
236 return OK;
237 case SEC_E_SECPKG_NOT_FOUND:
238 // This isn't a documented return code, but has been encountered
239 // during testing.
240 return ERR_UNSUPPORTED_AUTH_SCHEME;
241 default:
242 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
243 }
244 }
245
MapFreeContextBufferStatusToError(SECURITY_STATUS status)246 Error MapFreeContextBufferStatusToError(SECURITY_STATUS status) {
247 switch (status) {
248 case SEC_E_OK:
249 return OK;
250 default:
251 // The documentation at
252 // http://msdn.microsoft.com/en-us/library/aa375416(VS.85).aspx
253 // only mentions that a non-zero (or non-SEC_E_OK) value is returned
254 // if the function fails, and does not indicate what the failure
255 // conditions are.
256 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
257 }
258 }
259
260 } // anonymous namespace
261
DetermineMaxTokenLength(ULONG * max_token_length)262 Error SSPILibrary::DetermineMaxTokenLength(ULONG* max_token_length) {
263 if (!is_supported_)
264 return ERR_UNSUPPORTED_AUTH_SCHEME;
265
266 if (max_token_length_ != 0) {
267 *max_token_length = max_token_length_;
268 return OK;
269 }
270
271 DCHECK(max_token_length);
272 PSecPkgInfo pkg_info = nullptr;
273 is_supported_ = false;
274
275 SECURITY_STATUS status = QuerySecurityPackageInfo(&pkg_info);
276 Error rv = MapQuerySecurityPackageInfoStatusToError(status);
277 if (rv != OK)
278 return rv;
279 int token_length = pkg_info->cbMaxToken;
280
281 status = FreeContextBuffer(pkg_info);
282 rv = MapFreeContextBufferStatusToError(status);
283 if (rv != OK)
284 return rv;
285 *max_token_length = max_token_length_ = token_length;
286 is_supported_ = true;
287 return OK;
288 }
289
AcquireCredentialsHandle(LPWSTR pszPrincipal,unsigned long fCredentialUse,void * pvLogonId,void * pvAuthData,SEC_GET_KEY_FN pGetKeyFn,void * pvGetKeyArgument,PCredHandle phCredential,PTimeStamp ptsExpiry)290 SECURITY_STATUS SSPILibraryDefault::AcquireCredentialsHandle(
291 LPWSTR pszPrincipal,
292 unsigned long fCredentialUse,
293 void* pvLogonId,
294 void* pvAuthData,
295 SEC_GET_KEY_FN pGetKeyFn,
296 void* pvGetKeyArgument,
297 PCredHandle phCredential,
298 PTimeStamp ptsExpiry) {
299 return ::AcquireCredentialsHandleW(
300 pszPrincipal, const_cast<LPWSTR>(package_name_.c_str()), fCredentialUse,
301 pvLogonId, pvAuthData, pGetKeyFn, pvGetKeyArgument, phCredential,
302 ptsExpiry);
303 }
304
InitializeSecurityContext(PCredHandle phCredential,PCtxtHandle phContext,SEC_WCHAR * pszTargetName,unsigned long fContextReq,unsigned long Reserved1,unsigned long TargetDataRep,PSecBufferDesc pInput,unsigned long Reserved2,PCtxtHandle phNewContext,PSecBufferDesc pOutput,unsigned long * contextAttr,PTimeStamp ptsExpiry)305 SECURITY_STATUS SSPILibraryDefault::InitializeSecurityContext(
306 PCredHandle phCredential,
307 PCtxtHandle phContext,
308 SEC_WCHAR* pszTargetName,
309 unsigned long fContextReq,
310 unsigned long Reserved1,
311 unsigned long TargetDataRep,
312 PSecBufferDesc pInput,
313 unsigned long Reserved2,
314 PCtxtHandle phNewContext,
315 PSecBufferDesc pOutput,
316 unsigned long* contextAttr,
317 PTimeStamp ptsExpiry) {
318 return ::InitializeSecurityContextW(phCredential, phContext, pszTargetName,
319 fContextReq, Reserved1, TargetDataRep,
320 pInput, Reserved2, phNewContext, pOutput,
321 contextAttr, ptsExpiry);
322 }
323
QueryContextAttributesEx(PCtxtHandle phContext,ULONG ulAttribute,PVOID pBuffer,ULONG cbBuffer)324 SECURITY_STATUS SSPILibraryDefault::QueryContextAttributesEx(
325 PCtxtHandle phContext,
326 ULONG ulAttribute,
327 PVOID pBuffer,
328 ULONG cbBuffer) {
329 // TODO(https://crbug.com/992779): QueryContextAttributesExW is not included
330 // in Secur32.Lib in 10.0.18362.0 SDK. This symbol requires switching to using
331 // Windows SDK API sets in mincore.lib or OneCore.Lib. Switch to using
332 // QueryContextAttributesEx when the switch is made.
333 return ::QueryContextAttributes(phContext, ulAttribute, pBuffer);
334 }
335
QuerySecurityPackageInfo(PSecPkgInfoW * pkgInfo)336 SECURITY_STATUS SSPILibraryDefault::QuerySecurityPackageInfo(
337 PSecPkgInfoW* pkgInfo) {
338 return ::QuerySecurityPackageInfoW(const_cast<LPWSTR>(package_name_.c_str()),
339 pkgInfo);
340 }
341
FreeCredentialsHandle(PCredHandle phCredential)342 SECURITY_STATUS SSPILibraryDefault::FreeCredentialsHandle(
343 PCredHandle phCredential) {
344 return ::FreeCredentialsHandle(phCredential);
345 }
346
DeleteSecurityContext(PCtxtHandle phContext)347 SECURITY_STATUS SSPILibraryDefault::DeleteSecurityContext(
348 PCtxtHandle phContext) {
349 return ::DeleteSecurityContext(phContext);
350 }
351
FreeContextBuffer(PVOID pvContextBuffer)352 SECURITY_STATUS SSPILibraryDefault::FreeContextBuffer(PVOID pvContextBuffer) {
353 return ::FreeContextBuffer(pvContextBuffer);
354 }
355
HttpAuthSSPI(SSPILibrary * library,HttpAuth::Scheme scheme)356 HttpAuthSSPI::HttpAuthSSPI(SSPILibrary* library, HttpAuth::Scheme scheme)
357 : library_(library),
358 scheme_(scheme),
359 delegation_type_(DelegationType::kNone) {
360 DCHECK(library_);
361 DCHECK(scheme_ == HttpAuth::AUTH_SCHEME_NEGOTIATE ||
362 scheme_ == HttpAuth::AUTH_SCHEME_NTLM);
363 SecInvalidateHandle(&cred_);
364 SecInvalidateHandle(&ctxt_);
365 }
366
~HttpAuthSSPI()367 HttpAuthSSPI::~HttpAuthSSPI() {
368 ResetSecurityContext();
369 if (SecIsValidHandle(&cred_)) {
370 library_->FreeCredentialsHandle(&cred_);
371 SecInvalidateHandle(&cred_);
372 }
373 }
374
Init(const NetLogWithSource &)375 bool HttpAuthSSPI::Init(const NetLogWithSource&) {
376 return true;
377 }
378
NeedsIdentity() const379 bool HttpAuthSSPI::NeedsIdentity() const {
380 return decoded_server_auth_token_.empty();
381 }
382
AllowsExplicitCredentials() const383 bool HttpAuthSSPI::AllowsExplicitCredentials() const {
384 return true;
385 }
386
SetDelegation(DelegationType delegation_type)387 void HttpAuthSSPI::SetDelegation(DelegationType delegation_type) {
388 delegation_type_ = delegation_type;
389 }
390
ResetSecurityContext()391 void HttpAuthSSPI::ResetSecurityContext() {
392 if (SecIsValidHandle(&ctxt_)) {
393 library_->DeleteSecurityContext(&ctxt_);
394 SecInvalidateHandle(&ctxt_);
395 }
396 }
397
ParseChallenge(HttpAuthChallengeTokenizer * tok)398 HttpAuth::AuthorizationResult HttpAuthSSPI::ParseChallenge(
399 HttpAuthChallengeTokenizer* tok) {
400 if (!SecIsValidHandle(&ctxt_)) {
401 return net::ParseFirstRoundChallenge(scheme_, tok);
402 }
403 std::string encoded_auth_token;
404 return net::ParseLaterRoundChallenge(scheme_, tok, &encoded_auth_token,
405 &decoded_server_auth_token_);
406 }
407
GenerateAuthToken(const AuthCredentials * credentials,const std::string & spn,const std::string & channel_bindings,std::string * auth_token,const NetLogWithSource & net_log,CompletionOnceCallback)408 int HttpAuthSSPI::GenerateAuthToken(const AuthCredentials* credentials,
409 const std::string& spn,
410 const std::string& channel_bindings,
411 std::string* auth_token,
412 const NetLogWithSource& net_log,
413 CompletionOnceCallback /*callback*/) {
414 // Initial challenge.
415 if (!SecIsValidHandle(&cred_)) {
416 // ParseChallenge fails early if a non-empty token is received on the first
417 // challenge.
418 DCHECK(decoded_server_auth_token_.empty());
419 int rv = OnFirstRound(credentials, net_log);
420 if (rv != OK)
421 return rv;
422 }
423
424 DCHECK(SecIsValidHandle(&cred_));
425 void* out_buf;
426 int out_buf_len;
427 int rv = GetNextSecurityToken(
428 spn, channel_bindings,
429 static_cast<void*>(const_cast<char*>(decoded_server_auth_token_.c_str())),
430 decoded_server_auth_token_.length(), net_log, &out_buf, &out_buf_len);
431 if (rv != OK)
432 return rv;
433
434 // Base64 encode data in output buffer and prepend the scheme.
435 std::string encode_input(static_cast<char*>(out_buf), out_buf_len);
436 std::string encode_output;
437 base::Base64Encode(encode_input, &encode_output);
438 // OK, we are done with |out_buf|
439 free(out_buf);
440 if (scheme_ == HttpAuth::AUTH_SCHEME_NEGOTIATE) {
441 *auth_token = "Negotiate " + encode_output;
442 } else {
443 *auth_token = "NTLM " + encode_output;
444 }
445 return OK;
446 }
447
OnFirstRound(const AuthCredentials * credentials,const NetLogWithSource & net_log)448 int HttpAuthSSPI::OnFirstRound(const AuthCredentials* credentials,
449 const NetLogWithSource& net_log) {
450 DCHECK(!SecIsValidHandle(&cred_));
451 int rv = OK;
452 if (credentials) {
453 std::u16string domain;
454 std::u16string user;
455 SplitDomainAndUser(credentials->username(), &domain, &user);
456 rv = AcquireExplicitCredentials(library_, domain, user,
457 credentials->password(), net_log, &cred_);
458 if (rv != OK)
459 return rv;
460 } else {
461 rv = AcquireDefaultCredentials(library_, net_log, &cred_);
462 if (rv != OK)
463 return rv;
464 }
465
466 return rv;
467 }
468
GetNextSecurityToken(const std::string & spn,const std::string & channel_bindings,const void * in_token,int in_token_len,const NetLogWithSource & net_log,void ** out_token,int * out_token_len)469 int HttpAuthSSPI::GetNextSecurityToken(const std::string& spn,
470 const std::string& channel_bindings,
471 const void* in_token,
472 int in_token_len,
473 const NetLogWithSource& net_log,
474 void** out_token,
475 int* out_token_len) {
476 ULONG max_token_length = 0;
477 // Microsoft SDKs have a loose relationship with const.
478 Error rv = library_->DetermineMaxTokenLength(&max_token_length);
479 if (rv != OK)
480 return rv;
481
482 CtxtHandle* ctxt_ptr = nullptr;
483 SecBufferDesc in_buffer_desc, out_buffer_desc;
484 SecBufferDesc* in_buffer_desc_ptr = nullptr;
485 SecBuffer in_buffers[2], out_buffer;
486
487 in_buffer_desc.ulVersion = SECBUFFER_VERSION;
488 in_buffer_desc.cBuffers = 0;
489 in_buffer_desc.pBuffers = in_buffers;
490 if (in_token_len > 0) {
491 // Prepare input buffer.
492 SecBuffer& sec_buffer = in_buffers[in_buffer_desc.cBuffers++];
493 sec_buffer.BufferType = SECBUFFER_TOKEN;
494 sec_buffer.cbBuffer = in_token_len;
495 sec_buffer.pvBuffer = const_cast<void*>(in_token);
496 ctxt_ptr = &ctxt_;
497 } else {
498 // If there is no input token, then we are starting a new authentication
499 // sequence. If we have already initialized our security context, then
500 // we're incorrectly reusing the auth handler for a new sequence.
501 if (SecIsValidHandle(&ctxt_)) {
502 NOTREACHED();
503 return ERR_UNEXPECTED;
504 }
505 }
506
507 std::vector<char> sec_channel_bindings_buffer;
508 if (!channel_bindings.empty()) {
509 sec_channel_bindings_buffer.reserve(sizeof(SEC_CHANNEL_BINDINGS) +
510 channel_bindings.size());
511 sec_channel_bindings_buffer.resize(sizeof(SEC_CHANNEL_BINDINGS));
512 SEC_CHANNEL_BINDINGS* bindings_desc =
513 reinterpret_cast<SEC_CHANNEL_BINDINGS*>(
514 sec_channel_bindings_buffer.data());
515 bindings_desc->cbApplicationDataLength = channel_bindings.size();
516 bindings_desc->dwApplicationDataOffset = sizeof(SEC_CHANNEL_BINDINGS);
517 sec_channel_bindings_buffer.insert(sec_channel_bindings_buffer.end(),
518 channel_bindings.begin(),
519 channel_bindings.end());
520 DCHECK_EQ(sizeof(SEC_CHANNEL_BINDINGS) + channel_bindings.size(),
521 sec_channel_bindings_buffer.size());
522
523 SecBuffer& sec_buffer = in_buffers[in_buffer_desc.cBuffers++];
524 sec_buffer.BufferType = SECBUFFER_CHANNEL_BINDINGS;
525 sec_buffer.cbBuffer = sec_channel_bindings_buffer.size();
526 sec_buffer.pvBuffer = sec_channel_bindings_buffer.data();
527 }
528
529 if (in_buffer_desc.cBuffers > 0)
530 in_buffer_desc_ptr = &in_buffer_desc;
531
532 // Prepare output buffer.
533 out_buffer_desc.ulVersion = SECBUFFER_VERSION;
534 out_buffer_desc.cBuffers = 1;
535 out_buffer_desc.pBuffers = &out_buffer;
536 out_buffer.BufferType = SECBUFFER_TOKEN;
537 out_buffer.cbBuffer = max_token_length;
538 out_buffer.pvBuffer = malloc(out_buffer.cbBuffer);
539 if (!out_buffer.pvBuffer)
540 return ERR_OUT_OF_MEMORY;
541
542 DWORD context_flags = 0;
543 // Firefox only sets ISC_REQ_DELEGATE, but MSDN documentation indicates that
544 // ISC_REQ_MUTUAL_AUTH must also be set. On Windows delegation by KDC policy
545 // is always respected.
546 if (delegation_type_ != DelegationType::kNone)
547 context_flags |= (ISC_REQ_DELEGATE | ISC_REQ_MUTUAL_AUTH);
548
549 net_log.BeginEvent(NetLogEventType::AUTH_LIBRARY_INIT_SEC_CTX, [&] {
550 base::Value::Dict params;
551 params.Set("spn", spn);
552 params.Set("flags", ContextFlagsToValue(context_flags));
553 return params;
554 });
555
556 // This returns a token that is passed to the remote server.
557 DWORD context_attributes = 0;
558 std::u16string spn16 = base::ASCIIToUTF16(spn);
559 SECURITY_STATUS status = library_->InitializeSecurityContext(
560 &cred_, // phCredential
561 ctxt_ptr, // phContext
562 base::as_writable_wcstr(spn16), // pszTargetName
563 context_flags, // fContextReq
564 0, // Reserved1 (must be 0)
565 SECURITY_NATIVE_DREP, // TargetDataRep
566 in_buffer_desc_ptr, // pInput
567 0, // Reserved2 (must be 0)
568 &ctxt_, // phNewContext
569 &out_buffer_desc, // pOutput
570 &context_attributes, // pfContextAttr
571 nullptr); // ptsExpiry
572 rv = MapInitializeSecurityContextStatusToError(status);
573 net_log.EndEvent(NetLogEventType::AUTH_LIBRARY_INIT_SEC_CTX, [&] {
574 return InitializeSecurityContextParams(library_, &ctxt_, rv, status,
575 context_attributes);
576 });
577
578 if (rv != OK) {
579 ResetSecurityContext();
580 free(out_buffer.pvBuffer);
581 return rv;
582 }
583 if (!out_buffer.cbBuffer) {
584 free(out_buffer.pvBuffer);
585 out_buffer.pvBuffer = nullptr;
586 }
587 *out_token = out_buffer.pvBuffer;
588 *out_token_len = out_buffer.cbBuffer;
589 return OK;
590 }
591
SplitDomainAndUser(const std::u16string & combined,std::u16string * domain,std::u16string * user)592 void SplitDomainAndUser(const std::u16string& combined,
593 std::u16string* domain,
594 std::u16string* user) {
595 // |combined| may be in the form "user" or "DOMAIN\user".
596 // Separate the two parts if they exist.
597 // TODO(cbentzel): I believe user@domain is also a valid form.
598 size_t backslash_idx = combined.find(L'\\');
599 if (backslash_idx == std::u16string::npos) {
600 domain->clear();
601 *user = combined;
602 } else {
603 *domain = combined.substr(0, backslash_idx);
604 *user = combined.substr(backslash_idx + 1);
605 }
606 }
607
608 } // namespace net
609