1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// See "SSPI Sample Application" at
// http://msdn.microsoft.com/en-us/library/aa918273.aspx
#include "net/http/http_auth_sspi_win.h"
#include "base/base64.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/http/http_auth.h"
namespace net {
namespace {
int MapAcquireCredentialsStatusToError(SECURITY_STATUS status,
const SEC_WCHAR* package) {
switch (status) {
case SEC_E_OK:
return OK;
case SEC_E_INSUFFICIENT_MEMORY:
return ERR_OUT_OF_MEMORY;
case SEC_E_INTERNAL_ERROR:
return ERR_UNEXPECTED;
case SEC_E_NO_CREDENTIALS:
case SEC_E_NOT_OWNER:
case SEC_E_UNKNOWN_CREDENTIALS:
return ERR_INVALID_AUTH_CREDENTIALS;
case SEC_E_SECPKG_NOT_FOUND:
// This indicates that the SSPI configuration does not match expectations
LOG(ERROR) << "Received SEC_E_SECPKG_NOT_FOUND for " << package;
return ERR_UNSUPPORTED_AUTH_SCHEME;
default:
LOG(ERROR) << "Unexpected SECURITY_STATUS " << status;
return ERR_UNEXPECTED;
}
}
int AcquireCredentials(const SEC_WCHAR* package,
const std::wstring& domain,
const std::wstring& user,
const std::wstring& password,
CredHandle* cred) {
SEC_WINNT_AUTH_IDENTITY identity;
identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
identity.User =
reinterpret_cast<unsigned short*>(const_cast<wchar_t*>(user.c_str()));
identity.UserLength = user.size();
identity.Domain =
reinterpret_cast<unsigned short*>(const_cast<wchar_t*>(domain.c_str()));
identity.DomainLength = domain.size();
identity.Password =
reinterpret_cast<unsigned short*>(const_cast<wchar_t*>(password.c_str()));
identity.PasswordLength = password.size();
TimeStamp expiry;
// Pass the username/password to get the credentials handle.
SECURITY_STATUS status = AcquireCredentialsHandle(
NULL, // pszPrincipal
const_cast<SEC_WCHAR*>(package), // pszPackage
SECPKG_CRED_OUTBOUND, // fCredentialUse
NULL, // pvLogonID
&identity, // pAuthData
NULL, // pGetKeyFn (not used)
NULL, // pvGetKeyArgument (not used)
cred, // phCredential
&expiry); // ptsExpiry
return MapAcquireCredentialsStatusToError(status, package);
}
int AcquireDefaultCredentials(const SEC_WCHAR* package, CredHandle* cred) {
TimeStamp expiry;
// Pass the username/password to get the credentials handle.
// Note: Since the 5th argument is NULL, it uses the default
// cached credentials for the logged in user, which can be used
// for a single sign-on.
SECURITY_STATUS status = AcquireCredentialsHandle(
NULL, // pszPrincipal
const_cast<SEC_WCHAR*>(package), // pszPackage
SECPKG_CRED_OUTBOUND, // fCredentialUse
NULL, // pvLogonID
NULL, // pAuthData
NULL, // pGetKeyFn (not used)
NULL, // pvGetKeyArgument (not used)
cred, // phCredential
&expiry); // ptsExpiry
return MapAcquireCredentialsStatusToError(status, package);
}
} // anonymous namespace
HttpAuthSSPI::HttpAuthSSPI(const std::string& scheme,
SEC_WCHAR* security_package)
: scheme_(scheme),
security_package_(security_package),
max_token_length_(0) {
SecInvalidateHandle(&cred_);
SecInvalidateHandle(&ctxt_);
}
HttpAuthSSPI::~HttpAuthSSPI() {
ResetSecurityContext();
if (SecIsValidHandle(&cred_)) {
FreeCredentialsHandle(&cred_);
SecInvalidateHandle(&cred_);
}
}
bool HttpAuthSSPI::NeedsIdentity() const {
return decoded_server_auth_token_.empty();
}
bool HttpAuthSSPI::IsFinalRound() const {
return !decoded_server_auth_token_.empty();
}
void HttpAuthSSPI::ResetSecurityContext() {
if (SecIsValidHandle(&ctxt_)) {
DeleteSecurityContext(&ctxt_);
SecInvalidateHandle(&ctxt_);
}
}
bool HttpAuthSSPI::ParseChallenge(HttpAuth::ChallengeTokenizer* tok) {
// Verify the challenge's auth-scheme.
if (!tok->valid() ||
!LowerCaseEqualsASCII(tok->scheme(), StringToLowerASCII(scheme_).c_str()))
return false;
tok->set_expect_base64_token(true);
if (!tok->GetNext()) {
decoded_server_auth_token_.clear();
return true;
}
std::string encoded_auth_token = tok->value();
std::string decoded_auth_token;
bool base64_rv = base::Base64Decode(encoded_auth_token, &decoded_auth_token);
if (!base64_rv) {
LOG(ERROR) << "Base64 decoding of auth token failed.";
return false;
}
decoded_server_auth_token_ = decoded_auth_token;
return true;
}
int HttpAuthSSPI::GenerateAuthToken(const std::wstring* username,
const std::wstring* password,
const GURL& origin,
const HttpRequestInfo* request,
const ProxyInfo* proxy,
std::string* auth_token) {
DCHECK((username == NULL) == (password == NULL));
// Initial challenge.
if (!IsFinalRound()) {
int rv = OnFirstRound(username, password);
if (rv != OK)
return rv;
}
void* out_buf;
int out_buf_len;
int rv = GetNextSecurityToken(
origin,
static_cast<void *>(const_cast<char *>(
decoded_server_auth_token_.c_str())),
decoded_server_auth_token_.length(),
&out_buf,
&out_buf_len);
if (rv != OK)
return rv;
// Base64 encode data in output buffer and prepend the scheme.
std::string encode_input(static_cast<char*>(out_buf), out_buf_len);
std::string encode_output;
bool base64_rv = base::Base64Encode(encode_input, &encode_output);
// OK, we are done with |out_buf|
free(out_buf);
if (!base64_rv) {
LOG(ERROR) << "Base64 encoding of auth token failed.";
return ERR_UNEXPECTED;
}
*auth_token = scheme_ + " " + encode_output;
return OK;
}
int HttpAuthSSPI::OnFirstRound(const std::wstring* username,
const std::wstring* password) {
DCHECK((username == NULL) == (password == NULL));
int rv = DetermineMaxTokenLength(security_package_, &max_token_length_);
if (rv != OK)
return rv;
if (username) {
std::wstring domain;
std::wstring user;
SplitDomainAndUser(*username, &domain, &user);
rv = AcquireCredentials(security_package_, domain, user, *password, &cred_);
if (rv != OK)
return rv;
} else {
rv = AcquireDefaultCredentials(security_package_, &cred_);
if (rv != OK)
return rv;
}
return rv;
}
int HttpAuthSSPI::GetNextSecurityToken(
const GURL& origin,
const void * in_token,
int in_token_len,
void** out_token,
int* out_token_len) {
SECURITY_STATUS status;
TimeStamp expiry;
DWORD ctxt_attr;
CtxtHandle* ctxt_ptr;
SecBufferDesc in_buffer_desc, out_buffer_desc;
SecBufferDesc* in_buffer_desc_ptr;
SecBuffer in_buffer, out_buffer;
if (in_token_len > 0) {
// Prepare input buffer.
in_buffer_desc.ulVersion = SECBUFFER_VERSION;
in_buffer_desc.cBuffers = 1;
in_buffer_desc.pBuffers = &in_buffer;
in_buffer.BufferType = SECBUFFER_TOKEN;
in_buffer.cbBuffer = in_token_len;
in_buffer.pvBuffer = const_cast<void*>(in_token);
ctxt_ptr = &ctxt_;
in_buffer_desc_ptr = &in_buffer_desc;
} else {
// If there is no input token, then we are starting a new authentication
// sequence. If we have already initialized our security context, then
// we're incorrectly reusing the auth handler for a new sequence.
if (SecIsValidHandle(&ctxt_)) {
LOG(ERROR) << "Cannot restart authentication sequence";
return ERR_UNEXPECTED;
}
ctxt_ptr = NULL;
in_buffer_desc_ptr = NULL;
}
// Prepare output buffer.
out_buffer_desc.ulVersion = SECBUFFER_VERSION;
out_buffer_desc.cBuffers = 1;
out_buffer_desc.pBuffers = &out_buffer;
out_buffer.BufferType = SECBUFFER_TOKEN;
out_buffer.cbBuffer = max_token_length_;
out_buffer.pvBuffer = malloc(out_buffer.cbBuffer);
if (!out_buffer.pvBuffer)
return ERR_OUT_OF_MEMORY;
// The service principal name of the destination server. See
// http://msdn.microsoft.com/en-us/library/ms677949%28VS.85%29.aspx
std::wstring target(L"HTTP/");
target.append(ASCIIToWide(GetHostAndPort(origin)));
wchar_t* target_name = const_cast<wchar_t*>(target.c_str());
// This returns a token that is passed to the remote server.
status = InitializeSecurityContext(&cred_, // phCredential
ctxt_ptr, // phContext
target_name, // pszTargetName
0, // fContextReq
0, // Reserved1 (must be 0)
SECURITY_NATIVE_DREP, // TargetDataRep
in_buffer_desc_ptr, // pInput
0, // Reserved2 (must be 0)
&ctxt_, // phNewContext
&out_buffer_desc, // pOutput
&ctxt_attr, // pfContextAttr
&expiry); // ptsExpiry
// On success, the function returns SEC_I_CONTINUE_NEEDED on the first call
// and SEC_E_OK on the second call. On failure, the function returns an
// error code.
if (status != SEC_I_CONTINUE_NEEDED && status != SEC_E_OK) {
LOG(ERROR) << "InitializeSecurityContext failed " << status;
ResetSecurityContext();
free(out_buffer.pvBuffer);
return ERR_UNEXPECTED; // TODO(wtc): map error code.
}
if (!out_buffer.cbBuffer) {
free(out_buffer.pvBuffer);
out_buffer.pvBuffer = NULL;
}
*out_token = out_buffer.pvBuffer;
*out_token_len = out_buffer.cbBuffer;
return OK;
}
void SplitDomainAndUser(const std::wstring& combined,
std::wstring* domain,
std::wstring* user) {
// |combined| may be in the form "user" or "DOMAIN\user".
// Separatethe two parts if they exist.
// TODO(cbentzel): I believe user@domain is also a valid form.
size_t backslash_idx = combined.find(L'\\');
if (backslash_idx == std::wstring::npos) {
domain->clear();
*user = combined;
} else {
*domain = combined.substr(0, backslash_idx);
*user = combined.substr(backslash_idx + 1);
}
}
int DetermineMaxTokenLength(const std::wstring& package,
ULONG* max_token_length) {
PSecPkgInfo pkg_info = NULL;
SECURITY_STATUS status = QuerySecurityPackageInfo(
const_cast<wchar_t *>(package.c_str()), &pkg_info);
if (status != SEC_E_OK) {
// The documentation at
// http://msdn.microsoft.com/en-us/library/aa379359(VS.85).aspx
// only mentions that a non-zero (or non-SEC_E_OK) value is returned
// if the function fails. In practice, it appears to return
// SEC_E_SECPKG_NOT_FOUND for invalid/unknown packages.
LOG(ERROR) << "Security package " << package << " not found."
<< " Status code: " << status;
if (status == SEC_E_SECPKG_NOT_FOUND)
return ERR_UNSUPPORTED_AUTH_SCHEME;
else
return ERR_UNEXPECTED;
}
*max_token_length = pkg_info->cbMaxToken;
status = FreeContextBuffer(pkg_info);
if (status != SEC_E_OK) {
// The documentation at
// http://msdn.microsoft.com/en-us/library/aa375416(VS.85).aspx
// only mentions that a non-zero (or non-SEC_E_OK) value is returned
// if the function fails, and does not indicate what the failure conditions
// are.
LOG(ERROR) << "Unexpected problem freeing context buffer. Status code: "
<< status;
return ERR_UNEXPECTED;
}
return OK;
}
} // namespace net
|