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