Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / net / http / http_auth_sspi_win.cc
blobf59ce4d9d781d28dc38847f9a88bf3615acafa4d
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // See "SSPI Sample Application" at
6 // http://msdn.microsoft.com/en-us/library/aa918273.aspx
8 #include "net/http/http_auth_sspi_win.h"
10 #include "base/base64.h"
11 #include "base/logging.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "net/base/net_errors.h"
15 #include "net/http/http_auth.h"
16 #include "net/http/http_auth_multi_round_parse.h"
18 namespace net {
20 namespace {
22 int MapAcquireCredentialsStatusToError(SECURITY_STATUS status,
23 const SEC_WCHAR* package) {
24 VLOG(1) << "AcquireCredentialsHandle returned 0x" << std::hex << status;
25 switch (status) {
26 case SEC_E_OK:
27 return OK;
28 case SEC_E_INSUFFICIENT_MEMORY:
29 return ERR_OUT_OF_MEMORY;
30 case SEC_E_INTERNAL_ERROR:
31 LOG(WARNING)
32 << "AcquireCredentialsHandle returned unexpected status 0x"
33 << std::hex << status;
34 return ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS;
35 case SEC_E_NO_CREDENTIALS:
36 case SEC_E_NOT_OWNER:
37 case SEC_E_UNKNOWN_CREDENTIALS:
38 return ERR_INVALID_AUTH_CREDENTIALS;
39 case SEC_E_SECPKG_NOT_FOUND:
40 // This indicates that the SSPI configuration does not match expectations
41 return ERR_UNSUPPORTED_AUTH_SCHEME;
42 default:
43 LOG(WARNING)
44 << "AcquireCredentialsHandle returned undocumented status 0x"
45 << std::hex << status;
46 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
50 int AcquireExplicitCredentials(SSPILibrary* library,
51 const SEC_WCHAR* package,
52 const base::string16& domain,
53 const base::string16& user,
54 const base::string16& password,
55 CredHandle* cred) {
56 SEC_WINNT_AUTH_IDENTITY identity;
57 identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
58 identity.User =
59 reinterpret_cast<unsigned short*>(const_cast<wchar_t*>(user.c_str()));
60 identity.UserLength = user.size();
61 identity.Domain =
62 reinterpret_cast<unsigned short*>(const_cast<wchar_t*>(domain.c_str()));
63 identity.DomainLength = domain.size();
64 identity.Password =
65 reinterpret_cast<unsigned short*>(const_cast<wchar_t*>(password.c_str()));
66 identity.PasswordLength = password.size();
68 TimeStamp expiry;
70 // Pass the username/password to get the credentials handle.
71 SECURITY_STATUS status = library->AcquireCredentialsHandle(
72 NULL, // pszPrincipal
73 const_cast<SEC_WCHAR*>(package), // pszPackage
74 SECPKG_CRED_OUTBOUND, // fCredentialUse
75 NULL, // pvLogonID
76 &identity, // pAuthData
77 NULL, // pGetKeyFn (not used)
78 NULL, // pvGetKeyArgument (not used)
79 cred, // phCredential
80 &expiry); // ptsExpiry
82 return MapAcquireCredentialsStatusToError(status, package);
85 int AcquireDefaultCredentials(SSPILibrary* library, const SEC_WCHAR* package,
86 CredHandle* cred) {
87 TimeStamp expiry;
89 // Pass the username/password to get the credentials handle.
90 // Note: Since the 5th argument is NULL, it uses the default
91 // cached credentials for the logged in user, which can be used
92 // for a single sign-on.
93 SECURITY_STATUS status = library->AcquireCredentialsHandle(
94 NULL, // pszPrincipal
95 const_cast<SEC_WCHAR*>(package), // pszPackage
96 SECPKG_CRED_OUTBOUND, // fCredentialUse
97 NULL, // pvLogonID
98 NULL, // pAuthData
99 NULL, // pGetKeyFn (not used)
100 NULL, // pvGetKeyArgument (not used)
101 cred, // phCredential
102 &expiry); // ptsExpiry
104 return MapAcquireCredentialsStatusToError(status, package);
107 int MapInitializeSecurityContextStatusToError(SECURITY_STATUS status) {
108 VLOG(1) << "InitializeSecurityContext returned 0x" << std::hex << status;
109 switch (status) {
110 case SEC_E_OK:
111 case SEC_I_CONTINUE_NEEDED:
112 return OK;
113 case SEC_I_COMPLETE_AND_CONTINUE:
114 case SEC_I_COMPLETE_NEEDED:
115 case SEC_I_INCOMPLETE_CREDENTIALS:
116 case SEC_E_INCOMPLETE_MESSAGE:
117 case SEC_E_INTERNAL_ERROR:
118 // These are return codes reported by InitializeSecurityContext
119 // but not expected by Chrome (for example, INCOMPLETE_CREDENTIALS
120 // and INCOMPLETE_MESSAGE are intended for schannel).
121 LOG(WARNING)
122 << "InitializeSecurityContext returned unexpected status 0x"
123 << std::hex << status;
124 return ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS;
125 case SEC_E_INSUFFICIENT_MEMORY:
126 return ERR_OUT_OF_MEMORY;
127 case SEC_E_UNSUPPORTED_FUNCTION:
128 NOTREACHED();
129 return ERR_UNEXPECTED;
130 case SEC_E_INVALID_HANDLE:
131 NOTREACHED();
132 return ERR_INVALID_HANDLE;
133 case SEC_E_INVALID_TOKEN:
134 return ERR_INVALID_RESPONSE;
135 case SEC_E_LOGON_DENIED:
136 return ERR_ACCESS_DENIED;
137 case SEC_E_NO_CREDENTIALS:
138 case SEC_E_WRONG_PRINCIPAL:
139 return ERR_INVALID_AUTH_CREDENTIALS;
140 case SEC_E_NO_AUTHENTICATING_AUTHORITY:
141 case SEC_E_TARGET_UNKNOWN:
142 return ERR_MISCONFIGURED_AUTH_ENVIRONMENT;
143 default:
144 LOG(WARNING)
145 << "InitializeSecurityContext returned undocumented status 0x"
146 << std::hex << status;
147 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
151 int MapQuerySecurityPackageInfoStatusToError(SECURITY_STATUS status) {
152 VLOG(1) << "QuerySecurityPackageInfo returned 0x" << std::hex << status;
153 switch (status) {
154 case SEC_E_OK:
155 return OK;
156 case SEC_E_SECPKG_NOT_FOUND:
157 // This isn't a documented return code, but has been encountered
158 // during testing.
159 return ERR_UNSUPPORTED_AUTH_SCHEME;
160 default:
161 LOG(WARNING)
162 << "QuerySecurityPackageInfo returned undocumented status 0x"
163 << std::hex << status;
164 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
168 int MapFreeContextBufferStatusToError(SECURITY_STATUS status) {
169 VLOG(1) << "FreeContextBuffer returned 0x" << std::hex << status;
170 switch (status) {
171 case SEC_E_OK:
172 return OK;
173 default:
174 // The documentation at
175 // http://msdn.microsoft.com/en-us/library/aa375416(VS.85).aspx
176 // only mentions that a non-zero (or non-SEC_E_OK) value is returned
177 // if the function fails, and does not indicate what the failure
178 // conditions are.
179 LOG(WARNING)
180 << "FreeContextBuffer returned undocumented status 0x"
181 << std::hex << status;
182 return ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
186 } // anonymous namespace
188 SECURITY_STATUS SSPILibraryDefault::AcquireCredentialsHandle(
189 LPWSTR pszPrincipal,
190 LPWSTR pszPackage,
191 unsigned long fCredentialUse,
192 void* pvLogonId,
193 void* pvAuthData,
194 SEC_GET_KEY_FN pGetKeyFn,
195 void* pvGetKeyArgument,
196 PCredHandle phCredential,
197 PTimeStamp ptsExpiry) {
198 return ::AcquireCredentialsHandle(pszPrincipal, pszPackage, fCredentialUse,
199 pvLogonId, pvAuthData, pGetKeyFn,
200 pvGetKeyArgument, phCredential, ptsExpiry);
203 SECURITY_STATUS SSPILibraryDefault::InitializeSecurityContext(
204 PCredHandle phCredential,
205 PCtxtHandle phContext,
206 SEC_WCHAR* pszTargetName,
207 unsigned long fContextReq,
208 unsigned long Reserved1,
209 unsigned long TargetDataRep,
210 PSecBufferDesc pInput,
211 unsigned long Reserved2,
212 PCtxtHandle phNewContext,
213 PSecBufferDesc pOutput,
214 unsigned long* contextAttr,
215 PTimeStamp ptsExpiry) {
216 return ::InitializeSecurityContext(phCredential, phContext, pszTargetName,
217 fContextReq, Reserved1, TargetDataRep,
218 pInput, Reserved2, phNewContext, pOutput,
219 contextAttr, ptsExpiry);
222 SECURITY_STATUS SSPILibraryDefault::QuerySecurityPackageInfo(
223 LPWSTR pszPackageName,
224 PSecPkgInfoW* pkgInfo) {
225 return ::QuerySecurityPackageInfo(pszPackageName, pkgInfo);
228 SECURITY_STATUS SSPILibraryDefault::FreeCredentialsHandle(
229 PCredHandle phCredential) {
230 return ::FreeCredentialsHandle(phCredential);
233 SECURITY_STATUS SSPILibraryDefault::DeleteSecurityContext(
234 PCtxtHandle phContext) {
235 return ::DeleteSecurityContext(phContext);
238 SECURITY_STATUS SSPILibraryDefault::FreeContextBuffer(PVOID pvContextBuffer) {
239 return ::FreeContextBuffer(pvContextBuffer);
242 HttpAuthSSPI::HttpAuthSSPI(SSPILibrary* library,
243 const std::string& scheme,
244 const SEC_WCHAR* security_package,
245 ULONG max_token_length)
246 : library_(library),
247 scheme_(scheme),
248 security_package_(security_package),
249 max_token_length_(max_token_length),
250 can_delegate_(false) {
251 DCHECK(library_);
252 SecInvalidateHandle(&cred_);
253 SecInvalidateHandle(&ctxt_);
256 HttpAuthSSPI::~HttpAuthSSPI() {
257 ResetSecurityContext();
258 if (SecIsValidHandle(&cred_)) {
259 library_->FreeCredentialsHandle(&cred_);
260 SecInvalidateHandle(&cred_);
264 bool HttpAuthSSPI::NeedsIdentity() const {
265 return decoded_server_auth_token_.empty();
268 bool HttpAuthSSPI::AllowsExplicitCredentials() const {
269 return true;
272 void HttpAuthSSPI::Delegate() {
273 can_delegate_ = true;
276 void HttpAuthSSPI::ResetSecurityContext() {
277 if (SecIsValidHandle(&ctxt_)) {
278 library_->DeleteSecurityContext(&ctxt_);
279 SecInvalidateHandle(&ctxt_);
283 HttpAuth::AuthorizationResult HttpAuthSSPI::ParseChallenge(
284 HttpAuthChallengeTokenizer* tok) {
285 if (!SecIsValidHandle(&ctxt_)) {
286 return net::ParseFirstRoundChallenge(scheme_, tok);
288 std::string encoded_auth_token;
289 return net::ParseLaterRoundChallenge(scheme_, tok, &encoded_auth_token,
290 &decoded_server_auth_token_);
293 int HttpAuthSSPI::GenerateAuthToken(const AuthCredentials* credentials,
294 const std::string& spn,
295 std::string* auth_token,
296 const CompletionCallback& /*callback*/) {
297 // Initial challenge.
298 if (!SecIsValidHandle(&cred_)) {
299 int rv = OnFirstRound(credentials);
300 if (rv != OK)
301 return rv;
304 DCHECK(SecIsValidHandle(&cred_));
305 void* out_buf;
306 int out_buf_len;
307 int rv = GetNextSecurityToken(
308 spn,
309 static_cast<void *>(const_cast<char *>(
310 decoded_server_auth_token_.c_str())),
311 decoded_server_auth_token_.length(),
312 &out_buf,
313 &out_buf_len);
314 if (rv != OK)
315 return rv;
317 // Base64 encode data in output buffer and prepend the scheme.
318 std::string encode_input(static_cast<char*>(out_buf), out_buf_len);
319 std::string encode_output;
320 base::Base64Encode(encode_input, &encode_output);
321 // OK, we are done with |out_buf|
322 free(out_buf);
323 *auth_token = scheme_ + " " + encode_output;
324 return OK;
327 int HttpAuthSSPI::OnFirstRound(const AuthCredentials* credentials) {
328 DCHECK(!SecIsValidHandle(&cred_));
329 int rv = OK;
330 if (credentials) {
331 base::string16 domain;
332 base::string16 user;
333 SplitDomainAndUser(credentials->username(), &domain, &user);
334 rv = AcquireExplicitCredentials(library_, security_package_, domain,
335 user, credentials->password(), &cred_);
336 if (rv != OK)
337 return rv;
338 } else {
339 rv = AcquireDefaultCredentials(library_, security_package_, &cred_);
340 if (rv != OK)
341 return rv;
344 return rv;
347 int HttpAuthSSPI::GetNextSecurityToken(
348 const std::string& spn,
349 const void* in_token,
350 int in_token_len,
351 void** out_token,
352 int* out_token_len) {
353 CtxtHandle* ctxt_ptr;
354 SecBufferDesc in_buffer_desc, out_buffer_desc;
355 SecBufferDesc* in_buffer_desc_ptr;
356 SecBuffer in_buffer, out_buffer;
358 if (in_token_len > 0) {
359 // Prepare input buffer.
360 in_buffer_desc.ulVersion = SECBUFFER_VERSION;
361 in_buffer_desc.cBuffers = 1;
362 in_buffer_desc.pBuffers = &in_buffer;
363 in_buffer.BufferType = SECBUFFER_TOKEN;
364 in_buffer.cbBuffer = in_token_len;
365 in_buffer.pvBuffer = const_cast<void*>(in_token);
366 ctxt_ptr = &ctxt_;
367 in_buffer_desc_ptr = &in_buffer_desc;
368 } else {
369 // If there is no input token, then we are starting a new authentication
370 // sequence. If we have already initialized our security context, then
371 // we're incorrectly reusing the auth handler for a new sequence.
372 if (SecIsValidHandle(&ctxt_)) {
373 NOTREACHED();
374 return ERR_UNEXPECTED;
376 ctxt_ptr = NULL;
377 in_buffer_desc_ptr = NULL;
380 // Prepare output buffer.
381 out_buffer_desc.ulVersion = SECBUFFER_VERSION;
382 out_buffer_desc.cBuffers = 1;
383 out_buffer_desc.pBuffers = &out_buffer;
384 out_buffer.BufferType = SECBUFFER_TOKEN;
385 out_buffer.cbBuffer = max_token_length_;
386 out_buffer.pvBuffer = malloc(out_buffer.cbBuffer);
387 if (!out_buffer.pvBuffer)
388 return ERR_OUT_OF_MEMORY;
390 DWORD context_flags = 0;
391 // Firefox only sets ISC_REQ_DELEGATE, but MSDN documentation indicates that
392 // ISC_REQ_MUTUAL_AUTH must also be set.
393 if (can_delegate_)
394 context_flags |= (ISC_REQ_DELEGATE | ISC_REQ_MUTUAL_AUTH);
396 // This returns a token that is passed to the remote server.
397 DWORD context_attribute;
398 base::string16 spn16 = base::ASCIIToUTF16(spn);
399 SECURITY_STATUS status = library_->InitializeSecurityContext(
400 &cred_, // phCredential
401 ctxt_ptr, // phContext
402 const_cast<base::char16*>(spn16.c_str()), // pszTargetName
403 context_flags, // fContextReq
404 0, // Reserved1 (must be 0)
405 SECURITY_NATIVE_DREP, // TargetDataRep
406 in_buffer_desc_ptr, // pInput
407 0, // Reserved2 (must be 0)
408 &ctxt_, // phNewContext
409 &out_buffer_desc, // pOutput
410 &context_attribute, // pfContextAttr
411 NULL); // ptsExpiry
412 int rv = MapInitializeSecurityContextStatusToError(status);
413 if (rv != OK) {
414 ResetSecurityContext();
415 free(out_buffer.pvBuffer);
416 return rv;
418 if (!out_buffer.cbBuffer) {
419 free(out_buffer.pvBuffer);
420 out_buffer.pvBuffer = NULL;
422 *out_token = out_buffer.pvBuffer;
423 *out_token_len = out_buffer.cbBuffer;
424 return OK;
427 void SplitDomainAndUser(const base::string16& combined,
428 base::string16* domain,
429 base::string16* user) {
430 // |combined| may be in the form "user" or "DOMAIN\user".
431 // Separate the two parts if they exist.
432 // TODO(cbentzel): I believe user@domain is also a valid form.
433 size_t backslash_idx = combined.find(L'\\');
434 if (backslash_idx == base::string16::npos) {
435 domain->clear();
436 *user = combined;
437 } else {
438 *domain = combined.substr(0, backslash_idx);
439 *user = combined.substr(backslash_idx + 1);
443 int DetermineMaxTokenLength(SSPILibrary* library,
444 const std::wstring& package,
445 ULONG* max_token_length) {
446 DCHECK(library);
447 DCHECK(max_token_length);
448 PSecPkgInfo pkg_info = NULL;
449 SECURITY_STATUS status = library->QuerySecurityPackageInfo(
450 const_cast<wchar_t *>(package.c_str()), &pkg_info);
451 int rv = MapQuerySecurityPackageInfoStatusToError(status);
452 if (rv != OK)
453 return rv;
454 int token_length = pkg_info->cbMaxToken;
455 status = library->FreeContextBuffer(pkg_info);
456 rv = MapFreeContextBufferStatusToError(status);
457 if (rv != OK)
458 return rv;
459 *max_token_length = token_length;
460 return OK;
463 } // namespace net