24#include <openssl/err.h>
28#include <freerdp/settings.h>
29#include <freerdp/utils/proxy_utils.h>
30#include <freerdp/crypto/crypto.h>
33#include <winpr/assert.h>
34#include <winpr/sysinfo.h>
35#include <winpr/environment.h>
39#include <freerdp/log.h>
40#define TAG FREERDP_TAG("core.proxy")
52 SOCKS_CMD_CONNECT = 1,
54 SOCKS_CMD_UDP_ASSOCIATE = 3
64static const char logprefix[] =
"SOCKS Proxy:";
67static const char* rplstat[] = {
"succeeded",
68 "general SOCKS server failure",
69 "connection not allowed by ruleset",
70 "Network unreachable",
74 "Command not supported",
75 "Address type not supported" };
78static BOOL http_proxy_connect(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
79 const char* proxyPassword,
const char* hostname, UINT16 port);
82static BOOL socks_proxy_connect(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
83 const char* proxyPassword,
const char* hostname, UINT16 port);
84static void proxy_read_environment(rdpSettings* settings,
char* envname);
86BOOL proxy_prepare(rdpSettings* settings,
const char** lpPeerHostname, UINT16* lpPeerPort,
87 const char** lpProxyUsername,
const char** lpProxyPassword)
94 proxy_read_environment(settings,
"https_proxy");
97 proxy_read_environment(settings,
"HTTPS_PROXY");
100 proxy_read_environment(settings,
"no_proxy");
103 proxy_read_environment(settings,
"NO_PROXY");
108 if (!*lpPeerHostname || !winpr_str_is_valid_hostname(*lpPeerHostname))
120static BOOL value_to_int(
const char* value, LONGLONG* result, LONGLONG min, LONGLONG max)
124 if (!value || !result)
128 rc = _strtoi64(value,
nullptr, 0);
133 if ((rc < min) || (rc > max))
141static BOOL cidr4_match(
const struct in_addr* addr,
const struct in_addr* net, BYTE bits)
146 const uint32_t mask = htonl(0xFFFFFFFFu << (32 - bits));
147 const uint32_t amask = addr->s_addr & mask;
148 const uint32_t nmask = net->s_addr & mask;
149 return amask == nmask;
153static BOOL cidr6_match(
const struct in6_addr* address,
const struct in6_addr* network,
156 const uint32_t* a = (
const uint32_t*)address;
157 const uint32_t* n = (
const uint32_t*)network;
158 const size_t bits_whole = bits >> 5;
159 const size_t bits_incomplete = bits & 0x1F;
163 if (memcmp(a, n, bits_whole << 2) != 0)
169 uint32_t mask = htonl((0xFFFFFFFFu) << (32 - bits_incomplete));
171 if ((a[bits_whole] ^ n[bits_whole]) & mask)
179static BOOL option_ends_with(
const char* str,
const char* ext)
183 const size_t strLen = strlen(str);
184 const size_t extLen = strlen(ext);
189 return _strnicmp(&str[strLen - extLen], ext, extLen) == 0;
196static BOOL no_proxy_match_host(
const char* val,
const char* hostname)
199 WINPR_ASSERT(hostname);
202 if (_stricmp(
"*", val) == 0)
210 return option_ends_with(hostname, val);
214static BOOL starts_with(
const char* val,
const char* prefix)
216 const size_t plen = strlen(prefix);
217 const size_t vlen = strlen(val);
220 return _strnicmp(val, prefix, plen) == 0;
224static BOOL no_proxy_match_ip(
const char* val,
const char* hostname)
227 WINPR_ASSERT(hostname);
229 struct sockaddr_in sa4 = WINPR_C_ARRAY_INIT;
230 struct sockaddr_in6 sa6 = WINPR_C_ARRAY_INIT;
232 if (inet_pton(AF_INET, hostname, &sa4.sin_addr) == 1)
235 if (starts_with(hostname, val))
238 char* sub = strchr(val,
'/');
242 struct sockaddr_in mask = WINPR_C_ARRAY_INIT;
243 if (inet_pton(AF_INET, val, &mask.sin_addr) == 0)
247 if (memcmp(&mask, &sa4,
sizeof(mask)) == 0)
252 const unsigned long usub = strtoul(sub,
nullptr, 0);
253 if ((errno == 0) && (usub <= UINT8_MAX))
254 return cidr4_match(&sa4.sin_addr, &mask.sin_addr, (UINT8)usub);
257 else if (inet_pton(AF_INET6, hostname, &sa6.sin6_addr) == 1)
262 char str[INET6_ADDRSTRLEN + 1] = WINPR_C_ARRAY_INIT;
263 strncpy(str, val, INET6_ADDRSTRLEN);
265 const size_t len = strnlen(str, INET6_ADDRSTRLEN);
268 if (str[len - 1] ==
']')
273 if (starts_with(hostname, str))
276 char* sub = strchr(str,
'/');
280 struct sockaddr_in6 mask = WINPR_C_ARRAY_INIT;
281 if (inet_pton(AF_INET6, str, &mask.sin6_addr) == 0)
285 if (memcmp(&mask, &sa6,
sizeof(mask)) == 0)
290 const unsigned long usub = strtoul(sub,
nullptr, 0);
291 if ((errno == 0) && (usub <= UINT8_MAX))
292 return cidr6_match(&sa6.sin6_addr, &mask.sin6_addr, (UINT8)usub);
300static BOOL is_ipv6_addr(
const char* hostname,
size_t len)
302 struct sockaddr_in6 sa6 = WINPR_C_ARRAY_INIT;
303 if (strnlen(hostname, len) > INET6_ADDRSTRLEN)
305 return inet_pton(AF_INET6, hostname, &sa6.sin6_addr) == 1;
309static BOOL check_no_proxy(rdpSettings* settings,
const char* no_proxy)
311 const char* delimiter =
", ";
313 char* context =
nullptr;
315 if (!no_proxy || !settings)
318 char* copy = _strdup(no_proxy);
323 char* current = strtok_s(copy, delimiter, &context);
325 while (current && !result)
327 const size_t currentlen = strlen(current);
331 const char* ServerHostname =
333 WLog_DBG(TAG,
"%s => %s (%" PRIuz
")", ServerHostname, current, currentlen);
335 if (no_proxy_match_host(current, ServerHostname))
337 else if (no_proxy_match_ip(current, ServerHostname))
341 current = strtok_s(
nullptr, delimiter, &context);
348void proxy_read_environment(rdpSettings* settings,
char* envname)
350 const DWORD envlen = GetEnvironmentVariableA(envname,
nullptr, 0);
352 if (!envlen || (envlen <= 1))
355 char* env = calloc(1, envlen);
359 WLog_ERR(TAG,
"Not enough memory");
363 if (GetEnvironmentVariableA(envname, env, envlen) == envlen - 1)
365 if (_strnicmp(
"NO_PROXY", envname, 9) == 0)
367 if (check_no_proxy(settings, env))
369 WLog_INFO(TAG,
"deactivating proxy: %s [%s=%s]",
373 WLog_WARN(TAG,
"failed to set FreeRDP_ProxyType=PROXY_TYPE_NONE");
378 if (!proxy_parse_uri(settings, env))
381 TAG,
"Error while parsing proxy URI from environment variable; ignoring proxy");
389BOOL proxy_parse_uri(rdpSettings* settings,
const char* uri_in)
392 const char* protocol =
"";
395 if (!settings || !uri_in)
398 char* uri_copy = _strdup(uri_in);
399 char* uri = uri_copy;
404 char* p = strstr(uri,
"://");
409 if (_stricmp(
"no_proxy", uri) == 0)
414 if (_stricmp(
"http", uri) == 0)
420 else if (_stricmp(
"socks5", uri) == 0)
428 WLog_ERR(TAG,
"Only HTTP and SOCKS5 proxies supported by now");
445 char* atPtr = strrchr(uri,
'@');
456 char* colonPtr = strchr(uri,
':');
458 if (!colonPtr || (colonPtr > atPtr))
460 WLog_ERR(TAG,
"invalid syntax for proxy (contains no password)");
467 WLog_ERR(TAG,
"unable to allocate proxy username");
475 WLog_ERR(TAG,
"unable to allocate proxy password");
484 char* p = strchr(uri,
':');
490 if (!value_to_int(&p[1], &val, 0, UINT16_MAX))
492 WLog_ERR(TAG,
"invalid syntax for proxy (invalid port)");
498 WLog_ERR(TAG,
"invalid syntax for proxy (port missing)");
507 if (_stricmp(
"http", protocol) == 0)
517 WLog_DBG(TAG,
"setting default proxy port: %" PRIu16, port);
524 char* p = strchr(uri,
'/');
531 if (_stricmp(
"", uri) == 0)
533 WLog_ERR(TAG,
"invalid syntax for proxy (hostname missing)");
539 WLog_INFO(TAG,
"Parsed proxy configuration: %s://%s:%s@%s:%" PRIu16, protocol,
546 WLog_INFO(TAG,
"Parsed proxy configuration: %s://%s:%" PRIu16, protocol,
554 WLog_WARN(TAG,
"Failed to parse proxy configuration: %s://%s:%" PRIu16, protocol, uri,
560BOOL proxy_connect(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
561 const char* proxyPassword,
const char* hostname, UINT16 port)
563 WINPR_ASSERT(context);
564 rdpSettings* settings = context->settings;
568 case PROXY_TYPE_NONE:
569 case PROXY_TYPE_IGNORE:
572 case PROXY_TYPE_HTTP:
573 return http_proxy_connect(context, bufferedBio, proxyUsername, proxyPassword, hostname,
576 case PROXY_TYPE_SOCKS:
577 return socks_proxy_connect(context, bufferedBio, proxyUsername, proxyPassword, hostname,
581 WLog_ERR(TAG,
"Invalid internal proxy configuration");
587static const char* get_response_header(
char* response)
589 char* current_pos = strchr(response,
'\r');
591 current_pos = strchr(response,
'\n');
599static BOOL http_proxy_write_hostname(
wStream* s,
const char* hostname,
size_t len)
601 const BOOL isIPv6 = is_ipv6_addr(hostname, len);
605 if (!Stream_EnsureRemainingCapacity(s, 1))
607 Stream_Write_UINT8(s,
'[');
610 if (!Stream_EnsureRemainingCapacity(s, len))
612 Stream_Write(s, hostname, len);
616 if (!Stream_EnsureRemainingCapacity(s, 1))
618 Stream_Write_UINT8(s,
']');
625static BOOL http_proxy_connect(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
626 const char* proxyPassword,
const char* hostname, UINT16 port)
630 char port_str[10] = WINPR_C_ARRAY_INIT;
631 char recv_buf[256] = WINPR_C_ARRAY_INIT;
633 size_t resultsize = 0;
634 const char connect[] =
"CONNECT ";
635 const char httpheader[] =
" HTTP/1.1" CRLF
"Host: ";
637 WINPR_ASSERT(context);
638 WINPR_ASSERT(bufferedBio);
639 WINPR_ASSERT(hostname);
640 const UINT32 timeout =
645 const size_t hostLen = strnlen(hostname, 255 + 1);
646 if (!is_ipv6_addr(hostname, hostLen) && !winpr_str_is_valid_hostnameN(hostname, hostLen))
649 if (_itoa_s(port, port_str,
sizeof(port_str), 10) < 0)
651 WLog_ERR(TAG,
"itoa %s failed", port_str);
655 const size_t portLen = strnlen(port_str,
sizeof(port_str));
656 wStream* s = Stream_New(
nullptr, 1024);
660 const size_t clen = strnlen(connect,
sizeof(connect));
661 if (!Stream_EnsureRemainingCapacity(s, clen))
663 Stream_Write(s, connect, clen);
665 if (!http_proxy_write_hostname(s, hostname, hostLen))
668 if (!Stream_EnsureRemainingCapacity(s, 1))
670 Stream_Write_UINT8(s,
':');
672 if (!Stream_EnsureRemainingCapacity(s, portLen))
674 Stream_Write(s, port_str, portLen);
676 const size_t httplen = strnlen(httpheader,
sizeof(httpheader));
677 if (!Stream_EnsureRemainingCapacity(s, httplen))
679 Stream_Write(s, httpheader, httplen);
681 if (!http_proxy_write_hostname(s, hostname, hostLen))
684 if (!Stream_EnsureRemainingCapacity(s, 1))
686 Stream_Write_UINT8(s,
':');
688 if (!Stream_EnsureRemainingCapacity(s, portLen))
690 Stream_Write(s, port_str, portLen);
692 if (proxyUsername && proxyPassword && (strnlen(proxyUsername, 1) > 0) &&
693 (strnlen(proxyPassword, 1) > 0))
695 const char basic[] = CRLF
"Proxy-Authorization: Basic ";
696 const size_t balen = strnlen(basic,
sizeof(basic));
697 if (!Stream_EnsureRemainingCapacity(s, balen))
699 Stream_Write(s, basic, balen);
701 char* creds =
nullptr;
703 (void)winpr_asprintf(&creds, &size,
"%s:%s", proxyUsername, proxyPassword);
704 if (!creds || (size < 1))
710 char* base64 = crypto_base64_encode_len(creds, size, &b64len);
712 if (!base64 || !Stream_EnsureRemainingCapacity(s, b64len))
718 Stream_Write(s, base64, strlen(base64));
722 if (!Stream_EnsureRemainingCapacity(s, 4))
725 Stream_Write(s, CRLF CRLF, 4);
729 const size_t pos = Stream_GetPosition(s);
733 status = BIO_write(bufferedBio, Stream_Buffer(s), WINPR_ASSERTING_INT_CAST(
int, pos));
736 if ((status < 0) || ((
size_t)status != Stream_GetPosition(s)))
738 WLog_ERR(TAG,
"HTTP proxy: failed to write CONNECT request");
745 const UINT64 start = GetTickCount64();
746 while (strstr(recv_buf, CRLF CRLF) ==
nullptr)
748 if (resultsize >=
sizeof(recv_buf) - 1)
750 WLog_ERR(TAG,
"HTTP Reply headers too long: %s", get_response_header(recv_buf));
753 const size_t rdsize =
sizeof(recv_buf) - resultsize - 1ULL;
757 WINPR_ASSERT(rdsize <= INT32_MAX);
758 status = BIO_read(bufferedBio, (BYTE*)recv_buf + resultsize, (
int)rdsize);
763 if (!freerdp_shall_disconnect_context(context) && BIO_should_retry(bufferedBio))
769 WLog_ERR(TAG,
"Failed reading reply from HTTP proxy (Status %d)", status);
772 else if (status == 0)
774 const UINT64 now = GetTickCount64();
775 const UINT64 diff = now - start;
776 if (freerdp_shall_disconnect_context(context) || (now < start) || (diff > timeout))
779 WLog_ERR(TAG,
"Failed reading reply from HTTP proxy (BIO_read returned zero)");
785 resultsize += WINPR_ASSERTING_INT_CAST(
size_t, status);
790 eol = strchr(recv_buf,
'\r');
799 WLog_INFO(TAG,
"HTTP Proxy: %s", recv_buf);
801 if (strnlen(recv_buf,
sizeof(recv_buf)) < 12)
806 if (strncmp(recv_buf,
"HTTP/1.X 200", 12) != 0)
811 WLog_ERR(TAG,
"Failed to connect to proxy");
812 Stream_Free(s, TRUE);
817static int recv_socks_reply(rdpContext* context, BIO* bufferedBio, BYTE* buf,
int len,
char* reason,
822 WINPR_ASSERT(context);
824 const UINT32 timeout =
826 const UINT64 start = GetTickCount64();
830 status = BIO_read(bufferedBio, buf, len);
839 if (!freerdp_shall_disconnect_context(context) && BIO_should_retry(bufferedBio))
845 WLog_ERR(TAG,
"Failed reading %s reply from SOCKS proxy (Status %d)", reason, status);
848 else if (status == 0)
850 const UINT64 now = GetTickCount64();
851 const UINT64 diff = now - start;
852 if (freerdp_shall_disconnect_context(context) || (now < start) || (diff > timeout))
855 WLog_ERR(TAG,
"Failed reading %s reply from SOCKS proxy (BIO_read returned zero)",
864 WLog_ERR(TAG,
"Failed reading %s reply from SOCKS proxy (BIO_read returned zero)",
872 WLog_ERR(TAG,
"SOCKS Proxy reply packet too short (%s)", reason);
876 if (buf[0] != checkVer)
878 WLog_ERR(TAG,
"SOCKS Proxy version is not 5 (%s)", reason);
886static BOOL socks_proxy_userpass(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
887 const char* proxyPassword)
889 WINPR_ASSERT(context);
890 WINPR_ASSERT(bufferedBio);
892 if (!proxyUsername || !proxyPassword)
894 WLog_ERR(TAG,
"%s invalid username (%p) or password (%p)", logprefix,
895 WINPR_CXX_COMPAT_CAST(
const void*, proxyUsername),
896 WINPR_CXX_COMPAT_CAST(
const void*, proxyPassword));
900 const size_t usernameLen = (BYTE)strnlen(proxyUsername, 256);
901 if (usernameLen > 255)
903 WLog_ERR(TAG,
"%s username too long (%" PRIuz
", max=255)", logprefix, usernameLen);
907 const size_t userpassLen = (BYTE)strnlen(proxyPassword, 256);
908 if (userpassLen > 255)
910 WLog_ERR(TAG,
"%s password too long (%" PRIuz
", max=255)", logprefix, userpassLen);
916 BYTE buf[2 * 255 + 3] = WINPR_C_ARRAY_INIT;
920 buf[offset++] = WINPR_ASSERTING_INT_CAST(uint8_t, usernameLen);
921 memcpy(&buf[offset], proxyUsername, usernameLen);
922 offset += usernameLen;
924 buf[offset++] = WINPR_ASSERTING_INT_CAST(uint8_t, userpassLen);
925 memcpy(&buf[offset], proxyPassword, userpassLen);
926 offset += userpassLen;
929 const int ioffset = WINPR_ASSERTING_INT_CAST(
int, offset);
930 const int status = BIO_write(bufferedBio, buf, ioffset);
932 if (status != ioffset)
934 WLog_ERR(TAG,
"%s error writing user/password request", logprefix);
939 BYTE buf[2] = WINPR_C_ARRAY_INIT;
940 const int status = recv_socks_reply(context, bufferedBio, buf,
sizeof(buf),
"AUTH REQ", 1);
947 WLog_ERR(TAG,
"%s invalid user/password", logprefix);
954static BOOL socks_proxy_connect(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
955 const char* proxyPassword,
const char* hostname, UINT16 port)
957 WINPR_ASSERT(hostname);
960 const size_t hostnlen = strnlen(hostname, 255 + 1);
961 if (!is_ipv6_addr(hostname, hostnlen) && !winpr_str_is_valid_hostnameN(hostname, hostnlen))
964 BYTE nauthMethods = 1;
966 if (proxyUsername || proxyPassword)
971 const BYTE buf[] = { 5,
973 AUTH_M_NO_AUTH, AUTH_M_USR_PASS };
975 size_t writeLen =
sizeof(buf);
976 if (nauthMethods <= 1)
980 const int iwriteLen = WINPR_ASSERTING_INT_CAST(
int, writeLen);
981 const int status = BIO_write(bufferedBio, buf, iwriteLen);
983 if (status != iwriteLen)
985 WLog_ERR(TAG,
"%s SOCKS proxy: failed to write AUTH METHOD request", logprefix);
991 BYTE buf[2] = WINPR_C_ARRAY_INIT;
992 const int status = recv_socks_reply(context, bufferedBio, buf,
sizeof(buf),
"AUTH REQ", 5);
1000 WLog_DBG(TAG,
"%s (NO AUTH) method was selected", logprefix);
1003 case AUTH_M_USR_PASS:
1004 if (nauthMethods < 2)
1006 WLog_ERR(TAG,
"%s USER/PASS method was not proposed to server", logprefix);
1009 if (!socks_proxy_userpass(context, bufferedBio, proxyUsername, proxyPassword))
1014 WLog_ERR(TAG,
"%s unknown method 0x%x was selected by proxy", logprefix, buf[1]);
1020 BYTE buf[262] = WINPR_C_ARRAY_INIT;
1023 buf[offset++] = SOCKS_CMD_CONNECT;
1026 if (inet_pton(AF_INET6, hostname, &buf[offset + 1]) == 1)
1028 buf[offset++] = SOCKS_ADDR_IPV6;
1031 else if (inet_pton(AF_INET, hostname, &buf[offset + 1]) == 1)
1033 buf[offset++] = SOCKS_ADDR_IPV4;
1038 buf[offset++] = SOCKS_ADDR_FQDN;
1039 buf[offset++] = WINPR_ASSERTING_INT_CAST(uint8_t, hostnlen);
1040 memcpy(&buf[offset], hostname, hostnlen);
1044 if (offset >
sizeof(buf) - 2)
1046 WLog_ERR(TAG,
"Invalid offset %" PRIuz, offset);
1051 buf[offset++] = (port >> 8) & 0xff;
1052 buf[offset++] = port & 0xff;
1055 const int ioffset = WINPR_ASSERTING_INT_CAST(
int, offset);
1056 const int status = BIO_write(bufferedBio, buf, ioffset);
1058 if ((status < 0) || (status != ioffset))
1060 WLog_ERR(TAG,
"%s SOCKS proxy: failed to write CONN REQ", logprefix);
1065 BYTE buf[255] = WINPR_C_ARRAY_INIT;
1066 const int status = recv_socks_reply(context, bufferedBio, buf,
sizeof(buf),
"CONN REQ", 5);
1073 WLog_INFO(TAG,
"Successfully connected to %s:%" PRIu16, hostname, port);
1077 if ((buf[1] > 0) && (buf[1] < 9))
1078 WLog_INFO(TAG,
"SOCKS Proxy replied: %s", rplstat[buf[1]]);
1080 WLog_INFO(TAG,
"SOCKS Proxy replied: %" PRIu8
" status not listed in rfc1928", buf[1]);
WINPR_ATTR_NODISCARD FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.
WINPR_ATTR_NODISCARD FREERDP_API UINT16 freerdp_settings_get_uint16(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt16 id)
Returns a UINT16 settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_set_uint32(rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id, UINT32 val)
Sets a UINT32 settings value.
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_set_uint16(rdpSettings *settings, FreeRDP_Settings_Keys_UInt16 id, UINT16 val)
Sets a UINT16 settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_set_string(rdpSettings *settings, FreeRDP_Settings_Keys_String id, const char *val)
Sets a string settings value. The param is copied.