-
Notifications
You must be signed in to change notification settings - Fork 402
/
httpcli.hpp
1096 lines (965 loc) · 33.6 KB
/
httpcli.hpp
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012- OpenVPN Inc.
//
// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
//
// HTTP proxy transport object.
#ifndef OPENVPN_TRANSPORT_CLIENT_HTTPCLI_H
#define OPENVPN_TRANSPORT_CLIENT_HTTPCLI_H
#include <vector>
#include <string>
#include <sstream>
#include <algorithm> // for std::min
#include <memory>
#include <openvpn/io/io.hpp>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/string.hpp>
#include <openvpn/common/base64.hpp>
#include <openvpn/common/split.hpp>
#include <openvpn/common/options.hpp>
#include <openvpn/common/number.hpp>
#include <openvpn/common/userpass.hpp>
#include <openvpn/buffer/bufstr.hpp>
#include <openvpn/buffer/buflimit.hpp>
#include <openvpn/transport/tcplink.hpp>
#include <openvpn/transport/client/transbase.hpp>
#include <openvpn/transport/socket_protect.hpp>
#include <openvpn/transport/protocol.hpp>
#include <openvpn/http/reply.hpp>
#include <openvpn/http/status.hpp>
#include <openvpn/http/htmlskip.hpp>
#include <openvpn/proxy/proxyauth.hpp>
#include <openvpn/proxy/httpdigest.hpp>
#include <openvpn/proxy/ntlm.hpp>
#include <openvpn/client/remotelist.hpp>
#include <openvpn/crypto/digestapi.hpp>
namespace openvpn::HTTPProxyTransport {
enum AuthMethod
{
None,
Basic,
Digest,
Ntlm,
Any
};
class Options : public RC<thread_safe_refcount>
{
public:
struct CustomHeader : public RC<thread_unsafe_refcount>
{
typedef RCPtr<CustomHeader> Ptr;
std::string p1;
std::string p2;
};
struct CustomHeaderList : public std::vector<CustomHeader::Ptr>
{
};
typedef RCPtr<Options> Ptr;
RemoteList::Ptr proxy_server;
std::string username;
std::string password;
AuthMethod auth_method = Any;
bool allow_cleartext_auth = false;
std::string http_version;
std::string user_agent;
CustomHeaderList headers;
void set_proxy_server(const std::string &host, const std::string &port)
{
proxy_server.reset(new RemoteList(host, port, Protocol(Protocol::TCP), "http proxy port"));
}
void proxy_server_set_enable_cache(const bool enable_cache)
{
proxy_server->set_enable_cache(enable_cache);
}
void proxy_server_precache(RemoteList::Ptr &r)
{
if (proxy_server->get_enable_cache())
r = proxy_server;
}
static Ptr parse(const OptionList &opt)
{
if (opt.exists("http-proxy"))
{
Ptr obj(new Options);
if (obj->parse_options(opt))
return obj;
}
return Ptr();
}
private:
bool parse_options(const OptionList &opt)
{
const Option *hp = opt.get_ptr("http-proxy");
if (hp)
{
// get server/port
set_proxy_server(hp->get(1, 256), hp->get(2, 16));
// get creds
UserPass::parse(opt, "http-proxy-user-pass", 0, username, password);
const std::string auth = hp->get_optional(3, 16);
if (!auth.empty())
{
if (auth == "auto")
{
allow_cleartext_auth = true;
auth_method = Any;
}
else if (auth == "auto-nct")
{
allow_cleartext_auth = false;
auth_method = Any;
}
else if (auth == "basic")
{
allow_cleartext_auth = true;
auth_method = Basic;
}
else if (auth == "digest")
{
allow_cleartext_auth = false;
auth_method = Digest;
}
else if (auth == "ntlm")
{
allow_cleartext_auth = false;
auth_method = Ntlm;
}
else if (auth == "none")
{
auth_method = None;
}
else
{
throw Exception("Unsupported HTTP proxy auth method: " + auth);
}
}
// get options
const OptionList::IndexList *hpo = opt.get_index_ptr("http-proxy-option");
if (hpo)
{
for (OptionList::IndexList::const_iterator i = hpo->begin(); i != hpo->end(); ++i)
{
const Option &o = opt[*i];
const std::string &type = o.get(1, 64);
if (type == "VERSION")
{
http_version = o.get(2, 16);
o.touch();
}
else if (type == "AGENT")
{
user_agent = o.get(2, 256);
o.touch();
}
else if (type == "EXT1" || type == "EXT2" || type == "CUSTOM-HEADER")
{
CustomHeader::Ptr h(new CustomHeader());
h->p1 = o.get(2, 512);
h->p2 = o.get_optional(3, 512);
headers.push_back(h);
o.touch();
}
}
}
return true;
}
else
return false;
}
};
class ClientConfig : public TransportClientFactory
{
public:
typedef RCPtr<ClientConfig> Ptr;
RemoteList::Ptr remote_list;
size_t free_list_max_size;
Frame::Ptr frame;
SessionStats::Ptr stats;
Options::Ptr http_proxy_options;
StrongRandomAPI::Ptr rng; // random data source
DigestFactory::Ptr digest_factory; // needed by proxy auth methods
SocketProtect *socket_protect;
bool skip_html;
static Ptr new_obj()
{
return new ClientConfig;
}
TransportClient::Ptr new_transport_client_obj(openvpn_io::io_context &io_context,
TransportClientParent *parent) override;
private:
ClientConfig()
: free_list_max_size(8),
socket_protect(nullptr),
skip_html(false)
{
}
};
class Client : public TransportClient, AsyncResolvableTCP
{
typedef RCPtr<Client> Ptr;
typedef TCPTransport::TCPLink<openvpn_io::ip::tcp, Client *, false> LinkImpl;
friend class ClientConfig; // calls constructor
friend LinkImpl::Base; // calls tcp_read_handler
public:
void transport_start() override
{
if (!impl)
{
if (!config->http_proxy_options)
{
parent->proxy_error(Error::PROXY_ERROR, "http_proxy_options not defined");
return;
}
halt = false;
// Get target server host:port. We don't care about resolving it
// since proxy server will do that for us.
remote_list().endpoint_available(&server_host, &server_port, nullptr);
// Get proxy server host:port, and resolve it if not already cached
if (proxy_remote_list().endpoint_available(&proxy_host, &proxy_port, nullptr))
{
// already cached
start_connect_();
}
else
{
// resolve it
parent->transport_pre_resolve();
async_resolve_lock();
async_resolve_name(proxy_host, proxy_port);
}
}
}
bool transport_send_const(const Buffer &buf) override
{
return send_const(buf);
}
bool transport_send(BufferAllocated &buf) override
{
return send(buf);
}
bool transport_send_queue_empty() override
{
if (impl)
return impl->send_queue_empty();
else
return false;
}
bool transport_has_send_queue() override
{
return true;
}
void transport_stop_requeueing() override
{
}
size_t transport_send_queue_size() override
{
if (impl)
return impl->send_queue_size();
else
return 0;
}
void reset_align_adjust(const size_t align_adjust) override
{
if (impl)
impl->reset_align_adjust(align_adjust);
}
void server_endpoint_info(std::string &host, std::string &port, std::string &proto, std::string &ip_addr) const override
{
host = server_host;
port = server_port;
const IP::Addr addr = server_endpoint_addr();
proto = "TCP";
proto += addr.version_string();
proto += "-via-HTTP";
ip_addr = addr.to_string();
}
IP::Addr server_endpoint_addr() const override
{
return IP::Addr::from_asio(server_endpoint.address());
}
Protocol transport_protocol() const override
{
if (server_endpoint.address().is_v4())
return Protocol(Protocol::TCPv4);
else if (server_endpoint.address().is_v6())
return Protocol(Protocol::TCPv6);
else
return Protocol();
}
void stop() override
{
stop_();
}
virtual ~Client()
{
stop_();
}
private:
struct ProxyResponseLimit : public BufferLimit<size_t>
{
ProxyResponseLimit()
: BufferLimit(1024, 65536)
{
}
void bytes_exceeded() override
{
OPENVPN_THROW_EXCEPTION("HTTP proxy response too large (> " << max_bytes << " bytes)");
}
void lines_exceeded() override
{
OPENVPN_THROW_EXCEPTION("HTTP proxy response too large (> " << max_lines << " lines)");
}
};
Client(openvpn_io::io_context &io_context_arg,
ClientConfig *config_arg,
TransportClientParent *parent_arg)
: AsyncResolvableTCP(io_context_arg),
socket(io_context_arg),
config(config_arg),
parent(parent_arg),
halt(false),
n_transactions(0),
proxy_established(false),
http_reply_status(HTTP::ReplyParser::pending),
ntlm_phase_2_response_pending(false),
drain_content_length(0)
{
}
void transport_reparent(TransportClientParent *parent_arg) override
{
parent = parent_arg;
}
bool send_const(const Buffer &cbuf)
{
if (impl)
{
BufferAllocated buf(cbuf, 0);
return impl->send(buf);
}
else
return false;
}
bool send(BufferAllocated &buf)
{
if (impl)
return impl->send(buf);
else
return false;
}
void tcp_error_handler(const char *error) // called by LinkImpl and internally
{
std::ostringstream os;
os << "Transport error on '" << server_host << "' via HTTP proxy " << proxy_host << ':' << proxy_port << " : " << error;
stop();
parent->transport_error(Error::TRANSPORT_ERROR, os.str());
}
void proxy_error(const Error::Type fatal_err, const std::string &what)
{
std::ostringstream os;
os << "on " << proxy_host << ':' << proxy_port << ": " << what;
stop();
parent->proxy_error(fatal_err, os.str());
}
bool tcp_read_handler(BufferAllocated &buf) // called by LinkImpl
{
if (proxy_established)
{
if (!html_skip)
parent->transport_recv(buf);
else
drain_html(buf); // skip extraneous HTML after header
}
else
{
try
{
proxy_read_handler(buf);
}
catch (const std::exception &e)
{
proxy_error(Error::PROXY_ERROR, e.what());
}
}
return true;
}
void tcp_write_queue_needs_send() // called by LinkImpl
{
if (proxy_established)
parent->transport_needs_send();
}
void tcp_eof_handler() // called by LinkImpl
{
if (proxy_established)
{
config->stats->error(Error::NETWORK_EOF_ERROR);
tcp_error_handler("NETWORK_EOF_ERROR");
}
else
{
try
{
proxy_eof_handler();
}
catch (const std::exception &e)
{
proxy_error(Error::PROXY_ERROR, e.what());
}
}
}
void proxy_read_handler(BufferAllocated &buf)
{
// for anti-DoS, only allow a maximum number of chars in HTTP response
proxy_response_limit.add(buf);
if (http_reply_status == HTTP::ReplyParser::pending)
{
OPENVPN_LOG_NTNL("FROM PROXY: " << buf_to_string(buf));
for (size_t i = 0; i < buf.size(); ++i)
{
http_reply_status = http_parser.consume(http_reply, (char)buf[i]);
if (http_reply_status != HTTP::ReplyParser::pending)
{
buf.advance(i + 1);
if (http_reply_status == HTTP::ReplyParser::success)
{
// OPENVPN_LOG("*** HTTP header parse complete, resid_size=" << buf.size());
// OPENVPN_LOG(http_reply.to_string());
// we are connected, switch socket to tunnel mode
if (http_reply.status_code == HTTP::Status::Connected)
{
if (config->skip_html)
{
proxy_half_connected();
html_skip.reset(new HTTP::HTMLSkip());
drain_html(buf);
}
else
proxy_connected(buf, true);
}
else if (ntlm_phase_2_response_pending)
ntlm_auth_phase_2_pre();
}
else
{
throw Exception("HTTP proxy header parse error");
}
break;
}
}
}
// handle draining of content controlled by Content-length header
if (drain_content_length)
{
const size_t drain = std::min(drain_content_length, buf.size());
buf.advance(drain);
drain_content_length -= drain;
if (!drain_content_length)
{
if (ntlm_phase_2_response_pending)
ntlm_auth_phase_2();
}
}
}
void proxy_connected(BufferAllocated &buf, const bool notify_parent)
{
proxy_established = true;
if (parent->transport_is_openvpn_protocol())
{
// switch socket from HTTP proxy handshake mode to OpenVPN protocol mode
impl->set_raw_mode(false);
if (notify_parent)
parent->transport_connecting();
try
{
impl->inject(buf);
}
catch (const std::exception &e)
{
proxy_error(Error::PROXY_ERROR, std::string("post-header inject error: ") + e.what());
return;
}
}
else
{
if (notify_parent)
parent->transport_connecting();
parent->transport_recv(buf);
}
}
// Called after header received but before possible extraneous HTML
// is drained. At this point, we are in a state where output data
// (if OpenVPN protocol) is packetized, but input data is still in
// raw mode as we search the input stream for the end of the
// extraneous HTML. When we reach the beginning of payload data,
// proxy_connected() should be called with notify_parent == false.
void proxy_half_connected()
{
proxy_established = true;
if (parent->transport_is_openvpn_protocol())
impl->set_raw_mode_write(false);
parent->transport_connecting();
}
void drain_html(BufferAllocated &buf)
{
while (!buf.empty())
{
switch (html_skip->add(buf.pop_front()))
{
case HTTP::HTMLSkip::MATCH:
case HTTP::HTMLSkip::NOMATCH:
{
OPENVPN_LOG("Proxy: Skipped " << html_skip->n_bytes() << " byte(s) of HTML");
html_skip->get_residual(buf);
html_skip.reset();
proxy_connected(buf, false);
return;
}
case HTTP::HTMLSkip::PENDING:
break;
}
}
}
HTTPProxy::ProxyAuthenticate::Ptr get_proxy_authenticate_header(const char *type)
{
for (HTTP::HeaderList::const_iterator i = http_reply.headers.begin(); i != http_reply.headers.end(); ++i)
{
const HTTP::Header &h = *i;
if (string::strcasecmp(h.name, "proxy-authenticate") == 0)
{
HTTPProxy::ProxyAuthenticate::Ptr pa = new HTTPProxy::ProxyAuthenticate(h.value);
if (string::strcasecmp(type, pa->method) == 0)
return pa;
}
}
return HTTPProxy::ProxyAuthenticate::Ptr();
}
void proxy_eof_handler()
{
if (http_reply_status == HTTP::ReplyParser::success)
{
if (http_reply.status_code == HTTP::Status::ProxyAuthenticationRequired)
{
if (config->http_proxy_options->auth_method == None)
throw Exception("HTTP proxy authentication is disabled");
if (n_transactions > 1)
{
proxy_error(Error::PROXY_NEED_CREDS, "HTTP proxy credentials were not accepted");
return;
}
if (config->http_proxy_options->username.empty())
{
proxy_error(Error::PROXY_NEED_CREDS, "HTTP proxy requires credentials");
return;
}
HTTPProxy::ProxyAuthenticate::Ptr pa;
const AuthMethod method(config->http_proxy_options->auth_method);
if (method == Any || method == Ntlm)
{
pa = get_proxy_authenticate_header("ntlm");
if (pa)
{
ntlm_auth_phase_1(*pa);
return;
}
}
if (method == Any || method == Digest)
{
pa = get_proxy_authenticate_header("digest");
if (pa)
{
digest_auth(*pa);
return;
}
}
if (method == Any || method == Basic)
{
pa = get_proxy_authenticate_header("basic");
if (pa)
{
if (!config->http_proxy_options->allow_cleartext_auth)
throw Exception("HTTP proxy basic authentication not allowed by user preference");
basic_auth(*pa);
return;
}
}
throw Exception("HTTP proxy-authenticate method not allowed / supported");
}
else if (http_reply.status_code == HTTP::Status::ProxyError
|| http_reply.status_code == HTTP::Status::NotFound
|| http_reply.status_code == HTTP::Status::ServiceUnavailable)
{
// this is a nonfatal error, so we pass Error::UNDEF to tell the upper layer to
// retry the connection
proxy_error(Error::UNDEF, "HTTP proxy server could not connect to OpenVPN server");
return;
}
else if (http_reply.status_code == HTTP::Status::Forbidden)
OPENVPN_THROW_EXCEPTION("HTTP proxy returned Forbidden status code");
else
OPENVPN_THROW_EXCEPTION("HTTP proxy status code: " << http_reply.status_code);
}
else if (http_reply_status == HTTP::ReplyParser::pending)
throw Exception("HTTP proxy unexpected EOF: reply incomplete");
else
throw Exception("HTTP proxy general error");
}
void basic_auth(HTTPProxy::ProxyAuthenticate &pa)
{
OPENVPN_LOG("Proxy method: Basic" << std::endl
<< pa.to_string());
std::ostringstream os;
gen_headers(os);
os << "Proxy-Authorization: Basic "
<< base64->encode(config->http_proxy_options->username + ':' + config->http_proxy_options->password)
<< "\r\n";
http_request = os.str();
reset();
start_connect_();
}
void digest_auth(HTTPProxy::ProxyAuthenticate &pa)
{
try
{
OPENVPN_LOG("Proxy method: Digest" << std::endl
<< pa.to_string());
// constants
const std::string http_method = "CONNECT";
const std::string nonce_count = "00000001";
const std::string qop = "auth";
// get values from Proxy-Authenticate header
const std::string realm = pa.parms.get_value("realm");
const std::string nonce = pa.parms.get_value("nonce");
const std::string algorithm = pa.parms.get_value("algorithm");
const std::string opaque = pa.parms.get_value("opaque");
// generate a client nonce
unsigned char cnonce_raw[8];
config->rng->rand_bytes(cnonce_raw, sizeof(cnonce_raw));
const std::string cnonce = render_hex(cnonce_raw, sizeof(cnonce_raw));
// build URI
const std::string uri = server_host + ":" + server_port;
// calculate session key
const std::string session_key = HTTPProxy::Digest::calcHA1(
*config->digest_factory,
algorithm,
config->http_proxy_options->username,
realm,
config->http_proxy_options->password,
nonce,
cnonce);
// calculate response
const std::string response = HTTPProxy::Digest::calcResponse(
*config->digest_factory,
session_key,
nonce,
nonce_count,
cnonce,
qop,
http_method,
uri,
"");
// generate proxy request
std::ostringstream os;
gen_headers(os);
os << "Proxy-Authorization: Digest username=\"" << config->http_proxy_options->username << "\", realm=\"" << realm << "\", nonce=\"" << nonce << "\", uri=\"" << uri << "\", qop=" << qop << ", nc=" << nonce_count << ", cnonce=\"" << cnonce << "\", response=\"" << response << "\"";
if (!opaque.empty())
os << ", opaque=\"" + opaque + "\"";
os << "\r\n";
http_request = os.str();
reset();
start_connect_();
}
catch (const std::exception &e)
{
proxy_error(Error::PROXY_ERROR, std::string("Digest Auth: ") + e.what());
}
}
std::string get_ntlm_phase_2_response()
{
for (HTTP::HeaderList::const_iterator i = http_reply.headers.begin(); i != http_reply.headers.end(); ++i)
{
const HTTP::Header &h = *i;
if (string::strcasecmp(h.name, "proxy-authenticate") == 0)
{
std::vector<std::string> v = Split::by_space<std::vector<std::string>, StandardLex, SpaceMatch, Split::NullLimit>(h.value);
if (v.size() >= 2 && string::strcasecmp("ntlm", v[0]) == 0)
return v[1];
}
}
return "";
}
void ntlm_auth_phase_1(HTTPProxy::ProxyAuthenticate &pa)
{
OPENVPN_LOG("Proxy method: NTLM" << std::endl
<< pa.to_string());
const std::string phase_1_reply = HTTPProxy::NTLM::phase_1();
std::ostringstream os;
gen_headers(os);
os << "Proxy-Connection: Keep-Alive\r\n";
os << "Proxy-Authorization: NTLM " << phase_1_reply << "\r\n";
http_request = os.str();
reset();
ntlm_phase_2_response_pending = true;
start_connect_();
}
void ntlm_auth_phase_2_pre()
{
// if content exists, drain it first, then progress to ntlm_auth_phase_2
const std::string content_length_str = http_reply.headers.get_value_trim("content-length");
const unsigned int content_length = parse_number_throw<unsigned int>(content_length_str, "content-length");
if (content_length)
drain_content_length = content_length;
else
ntlm_auth_phase_2();
}
void ntlm_auth_phase_2()
{
ntlm_phase_2_response_pending = false;
if (http_reply.status_code != HTTP::Status::ProxyAuthenticationRequired)
throw Exception("NTLM phase-2 status is not ProxyAuthenticationRequired");
const std::string phase_2_response = get_ntlm_phase_2_response();
if (!phase_2_response.empty())
ntlm_auth_phase_3(phase_2_response);
else
throw Exception("NTLM phase-2 response missing");
}
void ntlm_auth_phase_3(const std::string &phase_2_response)
{
// do the NTLMv2 handshake
try
{
// OPENVPN_LOG("NTLM phase 3: " << phase_2_response);
const std::string phase_3_reply = HTTPProxy::NTLM::phase_3(
*config->digest_factory,
phase_2_response,
config->http_proxy_options->username,
config->http_proxy_options->password,
*config->rng);
std::ostringstream os;
gen_headers(os);
os << "Proxy-Connection: Keep-Alive\r\n";
os << "Proxy-Authorization: NTLM " << phase_3_reply << "\r\n";
http_request = os.str();
reset_partial();
http_proxy_send();
}
catch (const std::exception &e)
{
std::string what{e.what()};
if (what.find("openssl_digest_error") != std::string::npos)
{
proxy_error(Error::NTLM_MISSING_CRYPTO, "Crypto primitives required for NTLM authentication are unavailable");
}
else
{
proxy_error(Error::PROXY_ERROR, std::string("NTLM Auth: ") + e.what());
}
}
}
void gen_headers(std::ostringstream &os)
{
bool host_header_sent = false;
// emit custom headers
{
const Options::CustomHeaderList &headers = config->http_proxy_options->headers;
for (Options::CustomHeaderList::const_iterator i = headers.begin(); i != headers.end(); ++i)
{
const Options::CustomHeader &h = **i;
if (!h.p2.empty())
{
os << h.p1 << ": " << h.p2 << "\r\n";
if (!string::strcasecmp(h.p1, "host"))
host_header_sent = true;
}
else
{
os << h.p1 << "\r\n";
const std::string h5 = h.p1.substr(0, 5);
if (!string::strcasecmp(h5, "host:"))
host_header_sent = true;
}
}
}
// emit user-agent header
{
const std::string &user_agent = config->http_proxy_options->user_agent;
if (!user_agent.empty())
os << "User-Agent: " << user_agent << "\r\n";
}
// emit host header
if (!host_header_sent)
os << "Host: " << server_host << "\r\n";
}
void stop_()
{
if (!halt)
{
halt = true;
if (impl)
impl->stop();
socket.close();
async_resolve_cancel();
}
}
// do DNS resolve
void resolve_callback(const openvpn_io::error_code &error,
results_type results) override
{
// release resolver allocated resources
async_resolve_cancel();
if (!halt)
{
if (!error)
{
// save resolved endpoint list in proxy remote_list
proxy_remote_list().set_endpoint_range(results);
start_connect_();
}
else
{
std::ostringstream os;
os << "DNS resolve error on '" << proxy_host << "' for TCP (HTTP proxy): " << error.message();
config->stats->error(Error::RESOLVE_ERROR);
stop();
parent->transport_error(Error::UNDEF, os.str());
}
}
}
void reset()
{
stop();
halt = false;
proxy_response_limit.reset();
proxy_established = false;
reset_partial();
}
void reset_partial()
{
http_reply_status = HTTP::ReplyParser::pending;
http_reply.reset();
http_parser.reset();
ntlm_phase_2_response_pending = false;
drain_content_length = 0;
html_skip.reset();
}
// do TCP connect
void start_connect_()
{
proxy_remote_list().get_endpoint(server_endpoint);
OPENVPN_LOG("Contacting " << server_endpoint << " via HTTP Proxy");
parent->transport_wait_proxy();
socket.open(server_endpoint.protocol());
if (config->socket_protect)
{
if (!config->socket_protect->socket_protect(socket.native_handle(), server_endpoint_addr()))
{
config->stats->error(Error::SOCKET_PROTECT_ERROR);
stop();
parent->transport_error(Error::UNDEF, "socket_protect error (HTTP Proxy)");
return;
}
}
socket.set_option(openvpn_io::ip::tcp::no_delay(true));
socket.async_connect(server_endpoint, [self = Ptr(this)](const openvpn_io::error_code &error)
{
OPENVPN_ASYNC_HANDLER;
self->start_impl_(error); });
}
// start I/O on TCP socket
void start_impl_(const openvpn_io::error_code &error)
{
if (!halt)
{
if (!error)
{
parent->transport_wait();
impl.reset(new LinkImpl(this,
socket,
0, // send_queue_max_size is unlimited because we regulate size in cliproto.hpp
config->free_list_max_size,
(*config->frame)[Frame::READ_LINK_TCP],