1 /*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include <time.h>
12
13 #if defined(WEBRTC_WIN)
14 #include <windows.h>
15 #include <winsock2.h>
16 #include <ws2tcpip.h>
17
18 #define SECURITY_WIN32
19 #include <security.h>
20 #endif
21
22 #include <ctype.h> // for isspace
23 #include <stdio.h> // for sprintf
24
25 #include <utility> // for pair
26 #include <vector>
27
28 #include "absl/strings/match.h"
29 #include "rtc_base/crypt_string.h" // for CryptString
30 #include "rtc_base/http_common.h"
31 #include "rtc_base/logging.h"
32 #include "rtc_base/message_digest.h"
33 #include "rtc_base/socket_address.h"
34 #include "rtc_base/string_utils.h"
35 #include "rtc_base/strings/string_builder.h"
36 #include "rtc_base/third_party/base64/base64.h" // for Base64
37 #include "rtc_base/zero_memory.h" // for ExplicitZeroMemory
38
39 namespace rtc {
40 namespace {
41 #if defined(WEBRTC_WIN) && !defined(WINUWP)
42 ///////////////////////////////////////////////////////////////////////////////
43 // ConstantToLabel can be used to easily generate string names from constant
44 // values. This can be useful for logging descriptive names of error messages.
45 // Usage:
46 // const ConstantToLabel LIBRARY_ERRORS[] = {
47 // KLABEL(SOME_ERROR),
48 // KLABEL(SOME_OTHER_ERROR),
49 // ...
50 // LASTLABEL
51 // }
52 //
53 // int err = LibraryFunc();
54 // LOG(LS_ERROR) << "LibraryFunc returned: "
55 // << GetErrorName(err, LIBRARY_ERRORS);
56 struct ConstantToLabel {
57 int value;
58 const char* label;
59 };
60
LookupLabel(int value,const ConstantToLabel entries[])61 const char* LookupLabel(int value, const ConstantToLabel entries[]) {
62 for (int i = 0; entries[i].label; ++i) {
63 if (value == entries[i].value) {
64 return entries[i].label;
65 }
66 }
67 return 0;
68 }
69
GetErrorName(int err,const ConstantToLabel * err_table)70 std::string GetErrorName(int err, const ConstantToLabel* err_table) {
71 if (err == 0)
72 return "No error";
73
74 if (err_table != 0) {
75 if (const char* value = LookupLabel(err, err_table))
76 return value;
77 }
78
79 char buffer[16];
80 snprintf(buffer, sizeof(buffer), "0x%08x", err);
81 return buffer;
82 }
83
84 #define KLABEL(x) \
85 { x, #x }
86 #define LASTLABEL \
87 { 0, 0 }
88
89 const ConstantToLabel SECURITY_ERRORS[] = {
90 KLABEL(SEC_I_COMPLETE_AND_CONTINUE),
91 KLABEL(SEC_I_COMPLETE_NEEDED),
92 KLABEL(SEC_I_CONTEXT_EXPIRED),
93 KLABEL(SEC_I_CONTINUE_NEEDED),
94 KLABEL(SEC_I_INCOMPLETE_CREDENTIALS),
95 KLABEL(SEC_I_RENEGOTIATE),
96 KLABEL(SEC_E_CERT_EXPIRED),
97 KLABEL(SEC_E_INCOMPLETE_MESSAGE),
98 KLABEL(SEC_E_INSUFFICIENT_MEMORY),
99 KLABEL(SEC_E_INTERNAL_ERROR),
100 KLABEL(SEC_E_INVALID_HANDLE),
101 KLABEL(SEC_E_INVALID_TOKEN),
102 KLABEL(SEC_E_LOGON_DENIED),
103 KLABEL(SEC_E_NO_AUTHENTICATING_AUTHORITY),
104 KLABEL(SEC_E_NO_CREDENTIALS),
105 KLABEL(SEC_E_NOT_OWNER),
106 KLABEL(SEC_E_OK),
107 KLABEL(SEC_E_SECPKG_NOT_FOUND),
108 KLABEL(SEC_E_TARGET_UNKNOWN),
109 KLABEL(SEC_E_UNKNOWN_CREDENTIALS),
110 KLABEL(SEC_E_UNSUPPORTED_FUNCTION),
111 KLABEL(SEC_E_UNTRUSTED_ROOT),
112 KLABEL(SEC_E_WRONG_PRINCIPAL),
113 LASTLABEL};
114 #undef KLABEL
115 #undef LASTLABEL
116 #endif // defined(WEBRTC_WIN) && !defined(WINUWP)
117
118 typedef std::pair<std::string, std::string> HttpAttribute;
119 typedef std::vector<HttpAttribute> HttpAttributeList;
120
IsEndOfAttributeName(size_t pos,size_t len,const char * data)121 inline bool IsEndOfAttributeName(size_t pos, size_t len, const char* data) {
122 if (pos >= len)
123 return true;
124 if (isspace(static_cast<unsigned char>(data[pos])))
125 return true;
126 // The reason for this complexity is that some attributes may contain trailing
127 // equal signs (like base64 tokens in Negotiate auth headers)
128 if ((pos + 1 < len) && (data[pos] == '=') &&
129 !isspace(static_cast<unsigned char>(data[pos + 1])) &&
130 (data[pos + 1] != '=')) {
131 return true;
132 }
133 return false;
134 }
135
HttpParseAttributes(const char * data,size_t len,HttpAttributeList & attributes)136 void HttpParseAttributes(const char* data,
137 size_t len,
138 HttpAttributeList& attributes) {
139 size_t pos = 0;
140 while (true) {
141 // Skip leading whitespace
142 while ((pos < len) && isspace(static_cast<unsigned char>(data[pos]))) {
143 ++pos;
144 }
145
146 // End of attributes?
147 if (pos >= len)
148 return;
149
150 // Find end of attribute name
151 size_t start = pos;
152 while (!IsEndOfAttributeName(pos, len, data)) {
153 ++pos;
154 }
155
156 HttpAttribute attribute;
157 attribute.first.assign(data + start, data + pos);
158
159 // Attribute has value?
160 if ((pos < len) && (data[pos] == '=')) {
161 ++pos; // Skip '='
162 // Check if quoted value
163 if ((pos < len) && (data[pos] == '"')) {
164 while (++pos < len) {
165 if (data[pos] == '"') {
166 ++pos;
167 break;
168 }
169 if ((data[pos] == '\\') && (pos + 1 < len))
170 ++pos;
171 attribute.second.append(1, data[pos]);
172 }
173 } else {
174 while ((pos < len) && !isspace(static_cast<unsigned char>(data[pos])) &&
175 (data[pos] != ',')) {
176 attribute.second.append(1, data[pos++]);
177 }
178 }
179 }
180
181 attributes.push_back(attribute);
182 if ((pos < len) && (data[pos] == ','))
183 ++pos; // Skip ','
184 }
185 }
186
HttpHasAttribute(const HttpAttributeList & attributes,const std::string & name,std::string * value)187 bool HttpHasAttribute(const HttpAttributeList& attributes,
188 const std::string& name,
189 std::string* value) {
190 for (HttpAttributeList::const_iterator it = attributes.begin();
191 it != attributes.end(); ++it) {
192 if (it->first == name) {
193 if (value) {
194 *value = it->second;
195 }
196 return true;
197 }
198 }
199 return false;
200 }
201
HttpHasNthAttribute(HttpAttributeList & attributes,size_t index,std::string * name,std::string * value)202 bool HttpHasNthAttribute(HttpAttributeList& attributes,
203 size_t index,
204 std::string* name,
205 std::string* value) {
206 if (index >= attributes.size())
207 return false;
208
209 if (name)
210 *name = attributes[index].first;
211 if (value)
212 *value = attributes[index].second;
213 return true;
214 }
215
quote(const std::string & str)216 std::string quote(const std::string& str) {
217 std::string result;
218 result.push_back('"');
219 for (size_t i = 0; i < str.size(); ++i) {
220 if ((str[i] == '"') || (str[i] == '\\'))
221 result.push_back('\\');
222 result.push_back(str[i]);
223 }
224 result.push_back('"');
225 return result;
226 }
227
228 #if defined(WEBRTC_WIN) && !defined(WINUWP)
229 struct NegotiateAuthContext : public HttpAuthContext {
230 CredHandle cred;
231 CtxtHandle ctx;
232 size_t steps;
233 bool specified_credentials;
234
NegotiateAuthContextrtc::__anon5283ab7c0111::NegotiateAuthContext235 NegotiateAuthContext(const std::string& auth, CredHandle c1, CtxtHandle c2)
236 : HttpAuthContext(auth),
237 cred(c1),
238 ctx(c2),
239 steps(0),
240 specified_credentials(false) {}
241
~NegotiateAuthContextrtc::__anon5283ab7c0111::NegotiateAuthContext242 ~NegotiateAuthContext() override {
243 DeleteSecurityContext(&ctx);
244 FreeCredentialsHandle(&cred);
245 }
246 };
247 #endif // defined(WEBRTC_WIN) && !defined(WINUWP)
248
249 } // anonymous namespace
250
HttpAuthenticate(const char * challenge,size_t len,const SocketAddress & server,const std::string & method,const std::string & uri,const std::string & username,const CryptString & password,HttpAuthContext * & context,std::string & response,std::string & auth_method)251 HttpAuthResult HttpAuthenticate(const char* challenge,
252 size_t len,
253 const SocketAddress& server,
254 const std::string& method,
255 const std::string& uri,
256 const std::string& username,
257 const CryptString& password,
258 HttpAuthContext*& context,
259 std::string& response,
260 std::string& auth_method) {
261 HttpAttributeList args;
262 HttpParseAttributes(challenge, len, args);
263 HttpHasNthAttribute(args, 0, &auth_method, nullptr);
264
265 if (context && (context->auth_method != auth_method))
266 return HAR_IGNORE;
267
268 // BASIC
269 if (absl::EqualsIgnoreCase(auth_method, "basic")) {
270 if (context)
271 return HAR_CREDENTIALS; // Bad credentials
272 if (username.empty())
273 return HAR_CREDENTIALS; // Missing credentials
274
275 context = new HttpAuthContext(auth_method);
276
277 // TODO(bugs.webrtc.org/8905): Convert sensitive to a CryptString and also
278 // return response as CryptString so contents get securely deleted
279 // automatically.
280 // std::string decoded = username + ":" + password;
281 size_t len = username.size() + password.GetLength() + 2;
282 char* sensitive = new char[len];
283 size_t pos = strcpyn(sensitive, len, username.data(), username.size());
284 pos += strcpyn(sensitive + pos, len - pos, ":");
285 password.CopyTo(sensitive + pos, true);
286
287 response = auth_method;
288 response.append(" ");
289 // TODO: create a sensitive-source version of Base64::encode
290 response.append(Base64::Encode(sensitive));
291 ExplicitZeroMemory(sensitive, len);
292 delete[] sensitive;
293 return HAR_RESPONSE;
294 }
295
296 // DIGEST
297 if (absl::EqualsIgnoreCase(auth_method, "digest")) {
298 if (context)
299 return HAR_CREDENTIALS; // Bad credentials
300 if (username.empty())
301 return HAR_CREDENTIALS; // Missing credentials
302
303 context = new HttpAuthContext(auth_method);
304
305 std::string cnonce, ncount;
306 char buffer[256];
307 sprintf(buffer, "%d", static_cast<int>(time(0)));
308 cnonce = MD5(buffer);
309 ncount = "00000001";
310
311 std::string realm, nonce, qop, opaque;
312 HttpHasAttribute(args, "realm", &realm);
313 HttpHasAttribute(args, "nonce", &nonce);
314 bool has_qop = HttpHasAttribute(args, "qop", &qop);
315 bool has_opaque = HttpHasAttribute(args, "opaque", &opaque);
316
317 // TODO(bugs.webrtc.org/8905): Convert sensitive to a CryptString and also
318 // return response as CryptString so contents get securely deleted
319 // automatically.
320 // std::string A1 = username + ":" + realm + ":" + password;
321 size_t len = username.size() + realm.size() + password.GetLength() + 3;
322 char* sensitive = new char[len]; // A1
323 size_t pos = strcpyn(sensitive, len, username.data(), username.size());
324 pos += strcpyn(sensitive + pos, len - pos, ":");
325 pos += strcpyn(sensitive + pos, len - pos, realm.c_str());
326 pos += strcpyn(sensitive + pos, len - pos, ":");
327 password.CopyTo(sensitive + pos, true);
328
329 std::string A2 = method + ":" + uri;
330 std::string middle;
331 if (has_qop) {
332 qop = "auth";
333 middle = nonce + ":" + ncount + ":" + cnonce + ":" + qop;
334 } else {
335 middle = nonce;
336 }
337 std::string HA1 = MD5(sensitive);
338 ExplicitZeroMemory(sensitive, len);
339 delete[] sensitive;
340 std::string HA2 = MD5(A2);
341 std::string dig_response = MD5(HA1 + ":" + middle + ":" + HA2);
342
343 rtc::StringBuilder ss;
344 ss << auth_method;
345 ss << " username=" << quote(username);
346 ss << ", realm=" << quote(realm);
347 ss << ", nonce=" << quote(nonce);
348 ss << ", uri=" << quote(uri);
349 if (has_qop) {
350 ss << ", qop=" << qop;
351 ss << ", nc=" << ncount;
352 ss << ", cnonce=" << quote(cnonce);
353 }
354 ss << ", response=\"" << dig_response << "\"";
355 if (has_opaque) {
356 ss << ", opaque=" << quote(opaque);
357 }
358 response = ss.str();
359 return HAR_RESPONSE;
360 }
361
362 #if defined(WEBRTC_WIN) && !defined(WINUWP)
363 #if 1
364 bool want_negotiate = absl::EqualsIgnoreCase(auth_method, "negotiate");
365 bool want_ntlm = absl::EqualsIgnoreCase(auth_method, "ntlm");
366 // SPNEGO & NTLM
367 if (want_negotiate || want_ntlm) {
368 const size_t MAX_MESSAGE = 12000, MAX_SPN = 256;
369 char out_buf[MAX_MESSAGE], spn[MAX_SPN];
370
371 #if 0 // Requires funky windows versions
372 DWORD len = MAX_SPN;
373 if (DsMakeSpn("HTTP", server.HostAsURIString().c_str(), nullptr,
374 server.port(),
375 0, &len, spn) != ERROR_SUCCESS) {
376 RTC_LOG_F(WARNING) << "(Negotiate) - DsMakeSpn failed";
377 return HAR_IGNORE;
378 }
379 #else
380 snprintf(spn, MAX_SPN, "HTTP/%s", server.ToString().c_str());
381 #endif
382
383 SecBuffer out_sec;
384 out_sec.pvBuffer = out_buf;
385 out_sec.cbBuffer = sizeof(out_buf);
386 out_sec.BufferType = SECBUFFER_TOKEN;
387
388 SecBufferDesc out_buf_desc;
389 out_buf_desc.ulVersion = 0;
390 out_buf_desc.cBuffers = 1;
391 out_buf_desc.pBuffers = &out_sec;
392
393 const ULONG NEG_FLAGS_DEFAULT =
394 // ISC_REQ_ALLOCATE_MEMORY
395 ISC_REQ_CONFIDENTIALITY
396 //| ISC_REQ_EXTENDED_ERROR
397 //| ISC_REQ_INTEGRITY
398 | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT
399 //| ISC_REQ_STREAM
400 //| ISC_REQ_USE_SUPPLIED_CREDS
401 ;
402
403 ::TimeStamp lifetime;
404 SECURITY_STATUS ret = S_OK;
405 ULONG ret_flags = 0, flags = NEG_FLAGS_DEFAULT;
406
407 bool specify_credentials = !username.empty();
408 size_t steps = 0;
409
410 // uint32_t now = Time();
411
412 NegotiateAuthContext* neg = static_cast<NegotiateAuthContext*>(context);
413 if (neg) {
414 const size_t max_steps = 10;
415 if (++neg->steps >= max_steps) {
416 RTC_LOG(WARNING) << "AsyncHttpsProxySocket::Authenticate(Negotiate) "
417 "too many retries";
418 return HAR_ERROR;
419 }
420 steps = neg->steps;
421
422 std::string challenge, decoded_challenge;
423 if (HttpHasNthAttribute(args, 1, &challenge, nullptr) &&
424 Base64::Decode(challenge, Base64::DO_STRICT, &decoded_challenge,
425 nullptr)) {
426 SecBuffer in_sec;
427 in_sec.pvBuffer = const_cast<char*>(decoded_challenge.data());
428 in_sec.cbBuffer = static_cast<unsigned long>(decoded_challenge.size());
429 in_sec.BufferType = SECBUFFER_TOKEN;
430
431 SecBufferDesc in_buf_desc;
432 in_buf_desc.ulVersion = 0;
433 in_buf_desc.cBuffers = 1;
434 in_buf_desc.pBuffers = &in_sec;
435
436 ret = InitializeSecurityContextA(
437 &neg->cred, &neg->ctx, spn, flags, 0, SECURITY_NATIVE_DREP,
438 &in_buf_desc, 0, &neg->ctx, &out_buf_desc, &ret_flags, &lifetime);
439 if (FAILED(ret)) {
440 RTC_LOG(LS_ERROR) << "InitializeSecurityContext returned: "
441 << GetErrorName(ret, SECURITY_ERRORS);
442 return HAR_ERROR;
443 }
444 } else if (neg->specified_credentials) {
445 // Try again with default credentials
446 specify_credentials = false;
447 delete context;
448 context = neg = 0;
449 } else {
450 return HAR_CREDENTIALS;
451 }
452 }
453
454 if (!neg) {
455 unsigned char userbuf[256], passbuf[256], domainbuf[16];
456 SEC_WINNT_AUTH_IDENTITY_A auth_id, *pauth_id = 0;
457 if (specify_credentials) {
458 memset(&auth_id, 0, sizeof(auth_id));
459 size_t len = password.GetLength() + 1;
460 char* sensitive = new char[len];
461 password.CopyTo(sensitive, true);
462 std::string::size_type pos = username.find('\\');
463 if (pos == std::string::npos) {
464 auth_id.UserLength = static_cast<unsigned long>(
465 std::min(sizeof(userbuf) - 1, username.size()));
466 memcpy(userbuf, username.c_str(), auth_id.UserLength);
467 userbuf[auth_id.UserLength] = 0;
468 auth_id.DomainLength = 0;
469 domainbuf[auth_id.DomainLength] = 0;
470 auth_id.PasswordLength = static_cast<unsigned long>(
471 std::min(sizeof(passbuf) - 1, password.GetLength()));
472 memcpy(passbuf, sensitive, auth_id.PasswordLength);
473 passbuf[auth_id.PasswordLength] = 0;
474 } else {
475 auth_id.UserLength = static_cast<unsigned long>(
476 std::min(sizeof(userbuf) - 1, username.size() - pos - 1));
477 memcpy(userbuf, username.c_str() + pos + 1, auth_id.UserLength);
478 userbuf[auth_id.UserLength] = 0;
479 auth_id.DomainLength =
480 static_cast<unsigned long>(std::min(sizeof(domainbuf) - 1, pos));
481 memcpy(domainbuf, username.c_str(), auth_id.DomainLength);
482 domainbuf[auth_id.DomainLength] = 0;
483 auth_id.PasswordLength = static_cast<unsigned long>(
484 std::min(sizeof(passbuf) - 1, password.GetLength()));
485 memcpy(passbuf, sensitive, auth_id.PasswordLength);
486 passbuf[auth_id.PasswordLength] = 0;
487 }
488 ExplicitZeroMemory(sensitive, len);
489 delete[] sensitive;
490 auth_id.User = userbuf;
491 auth_id.Domain = domainbuf;
492 auth_id.Password = passbuf;
493 auth_id.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
494 pauth_id = &auth_id;
495 RTC_LOG(LS_VERBOSE)
496 << "Negotiate protocol: Using specified credentials";
497 } else {
498 RTC_LOG(LS_VERBOSE) << "Negotiate protocol: Using default credentials";
499 }
500
501 CredHandle cred;
502 ret = AcquireCredentialsHandleA(
503 0, const_cast<char*>(want_negotiate ? NEGOSSP_NAME_A : NTLMSP_NAME_A),
504 SECPKG_CRED_OUTBOUND, 0, pauth_id, 0, 0, &cred, &lifetime);
505 if (ret != SEC_E_OK) {
506 RTC_LOG(LS_ERROR) << "AcquireCredentialsHandle error: "
507 << GetErrorName(ret, SECURITY_ERRORS);
508 return HAR_IGNORE;
509 }
510
511 // CSecBufferBundle<5, CSecBufferBase::FreeSSPI> sb_out;
512
513 CtxtHandle ctx;
514 ret = InitializeSecurityContextA(&cred, 0, spn, flags, 0,
515 SECURITY_NATIVE_DREP, 0, 0, &ctx,
516 &out_buf_desc, &ret_flags, &lifetime);
517 if (FAILED(ret)) {
518 RTC_LOG(LS_ERROR) << "InitializeSecurityContext returned: "
519 << GetErrorName(ret, SECURITY_ERRORS);
520 FreeCredentialsHandle(&cred);
521 return HAR_IGNORE;
522 }
523
524 RTC_DCHECK(!context);
525 context = neg = new NegotiateAuthContext(auth_method, cred, ctx);
526 neg->specified_credentials = specify_credentials;
527 neg->steps = steps;
528 }
529
530 if ((ret == SEC_I_COMPLETE_NEEDED) ||
531 (ret == SEC_I_COMPLETE_AND_CONTINUE)) {
532 ret = CompleteAuthToken(&neg->ctx, &out_buf_desc);
533 RTC_LOG(LS_VERBOSE) << "CompleteAuthToken returned: "
534 << GetErrorName(ret, SECURITY_ERRORS);
535 if (FAILED(ret)) {
536 return HAR_ERROR;
537 }
538 }
539
540 std::string decoded(out_buf, out_buf + out_sec.cbBuffer);
541 response = auth_method;
542 response.append(" ");
543 response.append(Base64::Encode(decoded));
544 return HAR_RESPONSE;
545 }
546 #endif
547 #endif // defined(WEBRTC_WIN) && !defined(WINUWP)
548
549 return HAR_IGNORE;
550 }
551
552 //////////////////////////////////////////////////////////////////////
553
554 } // namespace rtc
555