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_url(*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_urlN(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)
694 const int length = _scprintf(
"%s:%s", proxyUsername, proxyPassword);
697 const char basic[] = CRLF
"Proxy-Authorization: Basic ";
698 const size_t balen = strnlen(basic,
sizeof(basic));
699 if (!Stream_EnsureRemainingCapacity(s, balen))
701 Stream_Write(s, basic, balen);
703 char* creds =
nullptr;
705 (void)winpr_asprintf(&creds, &size,
"%s:%s", proxyUsername, proxyPassword);
706 if (!creds || (size < 1))
712 char* base64 = crypto_base64_encode_len(creds, size - 1, &b64len);
714 if (!base64 || !Stream_EnsureRemainingCapacity(s, b64len))
720 Stream_Write(s, base64, strlen(base64));
725 if (!Stream_EnsureRemainingCapacity(s, 4))
728 Stream_Write(s, CRLF CRLF, 4);
732 const size_t pos = Stream_GetPosition(s);
736 status = BIO_write(bufferedBio, Stream_Buffer(s), WINPR_ASSERTING_INT_CAST(
int, pos));
739 if ((status < 0) || ((
size_t)status != Stream_GetPosition(s)))
741 WLog_ERR(TAG,
"HTTP proxy: failed to write CONNECT request");
748 const UINT64 start = GetTickCount64();
749 while (strstr(recv_buf, CRLF CRLF) ==
nullptr)
751 if (resultsize >=
sizeof(recv_buf) - 1)
753 WLog_ERR(TAG,
"HTTP Reply headers too long: %s", get_response_header(recv_buf));
756 const size_t rdsize =
sizeof(recv_buf) - resultsize - 1ULL;
760 WINPR_ASSERT(rdsize <= INT32_MAX);
761 status = BIO_read(bufferedBio, (BYTE*)recv_buf + resultsize, (
int)rdsize);
766 if (!freerdp_shall_disconnect_context(context) && BIO_should_retry(bufferedBio))
772 WLog_ERR(TAG,
"Failed reading reply from HTTP proxy (Status %d)", status);
775 else if (status == 0)
777 const UINT64 now = GetTickCount64();
778 const UINT64 diff = now - start;
779 if (freerdp_shall_disconnect_context(context) || (now < start) || (diff > timeout))
782 WLog_ERR(TAG,
"Failed reading reply from HTTP proxy (BIO_read returned zero)");
788 resultsize += WINPR_ASSERTING_INT_CAST(
size_t, status);
793 eol = strchr(recv_buf,
'\r');
802 WLog_INFO(TAG,
"HTTP Proxy: %s", recv_buf);
804 if (strnlen(recv_buf,
sizeof(recv_buf)) < 12)
809 if (strncmp(recv_buf,
"HTTP/1.X 200", 12) != 0)
814 WLog_ERR(TAG,
"Failed to connect to proxy");
815 Stream_Free(s, TRUE);
820static int recv_socks_reply(rdpContext* context, BIO* bufferedBio, BYTE* buf,
int len,
char* reason,
825 WINPR_ASSERT(context);
827 const UINT32 timeout =
829 const UINT64 start = GetTickCount64();
833 status = BIO_read(bufferedBio, buf, len);
842 if (!freerdp_shall_disconnect_context(context) && BIO_should_retry(bufferedBio))
848 WLog_ERR(TAG,
"Failed reading %s reply from SOCKS proxy (Status %d)", reason, status);
851 else if (status == 0)
853 const UINT64 now = GetTickCount64();
854 const UINT64 diff = now - start;
855 if (freerdp_shall_disconnect_context(context) || (now < start) || (diff > timeout))
858 WLog_ERR(TAG,
"Failed reading %s reply from SOCKS proxy (BIO_read returned zero)",
867 WLog_ERR(TAG,
"Failed reading %s reply from SOCKS proxy (BIO_read returned zero)",
875 WLog_ERR(TAG,
"SOCKS Proxy reply packet too short (%s)", reason);
879 if (buf[0] != checkVer)
881 WLog_ERR(TAG,
"SOCKS Proxy version is not 5 (%s)", reason);
889static BOOL socks_proxy_userpass(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
890 const char* proxyPassword)
892 WINPR_ASSERT(context);
893 WINPR_ASSERT(bufferedBio);
895 if (!proxyUsername || !proxyPassword)
897 WLog_ERR(TAG,
"%s invalid username (%p) or password (%p)", logprefix,
898 WINPR_CXX_COMPAT_CAST(
const void*, proxyUsername),
899 WINPR_CXX_COMPAT_CAST(
const void*, proxyPassword));
903 const size_t usernameLen = (BYTE)strnlen(proxyUsername, 256);
904 if (usernameLen > 255)
906 WLog_ERR(TAG,
"%s username too long (%" PRIuz
", max=255)", logprefix, usernameLen);
910 const size_t userpassLen = (BYTE)strnlen(proxyPassword, 256);
911 if (userpassLen > 255)
913 WLog_ERR(TAG,
"%s password too long (%" PRIuz
", max=255)", logprefix, userpassLen);
919 BYTE buf[2 * 255 + 3] = WINPR_C_ARRAY_INIT;
923 buf[offset++] = WINPR_ASSERTING_INT_CAST(uint8_t, usernameLen);
924 memcpy(&buf[offset], proxyUsername, usernameLen);
925 offset += usernameLen;
927 buf[offset++] = WINPR_ASSERTING_INT_CAST(uint8_t, userpassLen);
928 memcpy(&buf[offset], proxyPassword, userpassLen);
929 offset += userpassLen;
932 const int ioffset = WINPR_ASSERTING_INT_CAST(
int, offset);
933 const int status = BIO_write(bufferedBio, buf, ioffset);
935 if (status != ioffset)
937 WLog_ERR(TAG,
"%s error writing user/password request", logprefix);
942 BYTE buf[2] = WINPR_C_ARRAY_INIT;
943 const int status = recv_socks_reply(context, bufferedBio, buf,
sizeof(buf),
"AUTH REQ", 1);
950 WLog_ERR(TAG,
"%s invalid user/password", logprefix);
957static BOOL socks_proxy_connect(rdpContext* context, BIO* bufferedBio,
const char* proxyUsername,
958 const char* proxyPassword,
const char* hostname, UINT16 port)
960 WINPR_ASSERT(hostname);
963 const size_t hostnlen = strnlen(hostname, 255 + 1);
964 if (!is_ipv6_addr(hostname, hostnlen) && !winpr_str_is_valid_urlN(hostname, hostnlen))
967 BYTE nauthMethods = 1;
969 if (proxyUsername || proxyPassword)
974 const BYTE buf[] = { 5,
976 AUTH_M_NO_AUTH, AUTH_M_USR_PASS };
978 size_t writeLen =
sizeof(buf);
979 if (nauthMethods <= 1)
983 const int iwriteLen = WINPR_ASSERTING_INT_CAST(
int, writeLen);
984 const int status = BIO_write(bufferedBio, buf, iwriteLen);
986 if (status != iwriteLen)
988 WLog_ERR(TAG,
"%s SOCKS proxy: failed to write AUTH METHOD request", logprefix);
994 BYTE buf[2] = WINPR_C_ARRAY_INIT;
995 const int status = recv_socks_reply(context, bufferedBio, buf,
sizeof(buf),
"AUTH REQ", 5);
1002 case AUTH_M_NO_AUTH:
1003 WLog_DBG(TAG,
"%s (NO AUTH) method was selected", logprefix);
1006 case AUTH_M_USR_PASS:
1007 if (nauthMethods < 2)
1009 WLog_ERR(TAG,
"%s USER/PASS method was not proposed to server", logprefix);
1012 if (!socks_proxy_userpass(context, bufferedBio, proxyUsername, proxyPassword))
1017 WLog_ERR(TAG,
"%s unknown method 0x%x was selected by proxy", logprefix, buf[1]);
1023 BYTE buf[262] = WINPR_C_ARRAY_INIT;
1026 buf[offset++] = SOCKS_CMD_CONNECT;
1029 if (inet_pton(AF_INET6, hostname, &buf[offset + 1]) == 1)
1031 buf[offset++] = SOCKS_ADDR_IPV6;
1034 else if (inet_pton(AF_INET, hostname, &buf[offset + 1]) == 1)
1036 buf[offset++] = SOCKS_ADDR_IPV4;
1041 buf[offset++] = SOCKS_ADDR_FQDN;
1042 buf[offset++] = WINPR_ASSERTING_INT_CAST(uint8_t, hostnlen);
1043 memcpy(&buf[offset], hostname, hostnlen);
1047 if (offset >
sizeof(buf) - 2)
1049 WLog_ERR(TAG,
"Invalid offset %" PRIuz, offset);
1054 buf[offset++] = (port >> 8) & 0xff;
1055 buf[offset++] = port & 0xff;
1058 const int ioffset = WINPR_ASSERTING_INT_CAST(
int, offset);
1059 const int status = BIO_write(bufferedBio, buf, ioffset);
1061 if ((status < 0) || (status != ioffset))
1063 WLog_ERR(TAG,
"%s SOCKS proxy: failed to write CONN REQ", logprefix);
1068 BYTE buf[255] = WINPR_C_ARRAY_INIT;
1069 const int status = recv_socks_reply(context, bufferedBio, buf,
sizeof(buf),
"CONN REQ", 5);
1076 WLog_INFO(TAG,
"Successfully connected to %s:%" PRIu16, hostname, port);
1080 if ((buf[1] > 0) && (buf[1] < 9))
1081 WLog_INFO(TAG,
"SOCKS Proxy replied: %s", rplstat[buf[1]]);
1083 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.