-
Notifications
You must be signed in to change notification settings - Fork 503
/
client_side_request.cc
2261 lines (1916 loc) · 76.9 KB
/
client_side_request.cc
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
/*
* Copyright (C) 1996-2023 The Squid Software Foundation and contributors
*
* Squid software is distributed under GPLv2+ license and includes
* contributions from numerous individuals and organizations.
* Please see the COPYING and CONTRIBUTORS files for details.
*/
/* DEBUG: section 85 Client-side Request Routines */
/*
* General logic of request processing:
*
* We run a series of tests to determine if access will be permitted, and to do
* any redirection. Then we call into the result clientStream to retrieve data.
* From that point on it's up to reply management.
*/
#include "squid.h"
#include "acl/FilledChecklist.h"
#include "acl/Gadgets.h"
#include "anyp/PortCfg.h"
#include "base/AsyncJobCalls.h"
#include "client_side.h"
#include "client_side_reply.h"
#include "client_side_request.h"
#include "ClientRequestContext.h"
#include "clientStream.h"
#include "comm/Connection.h"
#include "comm/Write.h"
#include "error/Detail.h"
#include "errorpage.h"
#include "fd.h"
#include "fde.h"
#include "format/Token.h"
#include "gopher.h"
#include "helper.h"
#include "helper/Reply.h"
#include "http.h"
#include "http/Stream.h"
#include "HttpHdrCc.h"
#include "HttpReply.h"
#include "HttpRequest.h"
#include "ip/NfMarkConfig.h"
#include "ip/QosConfig.h"
#include "ipcache.h"
#include "log/access_log.h"
#include "MemObject.h"
#include "Parsing.h"
#include "profiler/Profiler.h"
#include "proxyp/Header.h"
#include "redirect.h"
#include "rfc1738.h"
#include "SquidConfig.h"
#include "SquidTime.h"
#include "Store.h"
#include "StrList.h"
#include "tools.h"
#include "wordlist.h"
#if USE_AUTH
#include "auth/UserRequest.h"
#endif
#if USE_ADAPTATION
#include "adaptation/AccessCheck.h"
#include "adaptation/Answer.h"
#include "adaptation/Iterator.h"
#include "adaptation/Service.h"
#if ICAP_CLIENT
#include "adaptation/icap/History.h"
#endif
#endif
#if USE_OPENSSL
#include "ssl/ServerBump.h"
#include "ssl/support.h"
#endif
#if LINGERING_CLOSE
#define comm_close comm_lingering_close
#endif
static const char *const crlf = "\r\n";
#if FOLLOW_X_FORWARDED_FOR
#if !defined(SQUID_X_FORWARDED_FOR_HOP_MAX)
#define SQUID_X_FORWARDED_FOR_HOP_MAX 64
#endif
static void clientFollowXForwardedForCheck(Acl::Answer answer, void *data);
#endif /* FOLLOW_X_FORWARDED_FOR */
ErrorState *clientBuildError(err_type, Http::StatusCode, char const *url, Ip::Address &, HttpRequest *, const AccessLogEntry::Pointer &);
CBDATA_CLASS_INIT(ClientRequestContext);
/* Local functions */
/* other */
static void clientAccessCheckDoneWrapper(Acl::Answer, void *);
#if USE_OPENSSL
static void sslBumpAccessCheckDoneWrapper(Acl::Answer, void *);
#endif
static int clientHierarchical(ClientHttpRequest * http);
static void clientInterpretRequestHeaders(ClientHttpRequest * http);
static HLPCB clientRedirectDoneWrapper;
static HLPCB clientStoreIdDoneWrapper;
static void checkNoCacheDoneWrapper(Acl::Answer, void *);
SQUIDCEXTERN CSR clientGetMoreData;
SQUIDCEXTERN CSS clientReplyStatus;
SQUIDCEXTERN CSD clientReplyDetach;
static void checkFailureRatio(err_type, hier_code);
ClientRequestContext::~ClientRequestContext()
{
/*
* Release our "lock" on our parent, ClientHttpRequest, if we
* still have one
*/
if (http)
cbdataReferenceDone(http);
delete error;
debugs(85,3, "ClientRequestContext destructed, this=" << this);
}
ClientRequestContext::ClientRequestContext(ClientHttpRequest *anHttp) :
http(cbdataReference(anHttp)),
acl_checklist(NULL),
redirect_state(REDIRECT_NONE),
store_id_state(REDIRECT_NONE),
host_header_verify_done(false),
http_access_done(false),
adapted_http_access_done(false),
#if USE_ADAPTATION
adaptation_acl_check_done(false),
#endif
redirect_done(false),
store_id_done(false),
no_cache_done(false),
interpreted_req_hdrs(false),
toClientMarkingDone(false),
#if USE_OPENSSL
sslBumpCheckDone(false),
#endif
error(NULL),
readNextRequest(false)
{
debugs(85, 3, "ClientRequestContext constructed, this=" << this);
}
CBDATA_CLASS_INIT(ClientHttpRequest);
ClientHttpRequest::ClientHttpRequest(ConnStateData * aConn) :
#if USE_ADAPTATION
AsyncJob("ClientHttpRequest"),
#endif
request(NULL),
uri(NULL),
log_uri(NULL),
req_sz(0),
calloutContext(NULL),
maxReplyBodySize_(0),
entry_(NULL),
loggingEntry_(NULL),
conn_(cbdataReference(aConn))
#if USE_OPENSSL
, sslBumpNeed_(Ssl::bumpEnd)
#endif
#if USE_ADAPTATION
, receivedWholeAdaptedReply(false)
, request_satisfaction_mode(false)
, request_satisfaction_offset(0)
#endif
{
al = new AccessLogEntry;
CodeContext::Reset(al);
al->cache.start_time = current_time;
if (aConn) {
al->tcpClient = clientConnection = aConn->clientConnection;
al->cache.port = aConn->port;
al->cache.caddr = aConn->log_addr;
al->proxyProtocolHeader = aConn->proxyProtocolHeader();
al->updateError(aConn->bareError);
#if USE_OPENSSL
if (aConn->clientConnection != NULL && aConn->clientConnection->isOpen()) {
if (auto ssl = fd_table[aConn->clientConnection->fd].ssl.get())
al->cache.sslClientCert.resetWithoutLocking(SSL_get_peer_certificate(ssl));
}
#endif
}
dlinkAdd(this, &active, &ClientActiveRequests);
}
/*
* returns true if client specified that the object must come from the cache
* without contacting origin server
*/
bool
ClientHttpRequest::onlyIfCached()const
{
assert(request);
return request->cache_control &&
request->cache_control->hasOnlyIfCached();
}
/**
* This function is designed to serve a fairly specific purpose.
* Occasionally our vBNS-connected caches can talk to each other, but not
* the rest of the world. Here we try to detect frequent failures which
* make the cache unusable (e.g. DNS lookup and connect() failures). If
* the failure:success ratio goes above 1.0 then we go into "hit only"
* mode where we only return UDP_HIT or UDP_MISS_NOFETCH. Neighbors
* will only fetch HITs from us if they are using the ICP protocol. We
* stay in this mode for 5 minutes.
*
* Duane W., Sept 16, 1996
*/
static void
checkFailureRatio(err_type etype, hier_code hcode)
{
// Can be set at compile time with -D compiler flag
#ifndef FAILURE_MODE_TIME
#define FAILURE_MODE_TIME 300
#endif
if (hcode == HIER_NONE)
return;
// don't bother when ICP is disabled.
if (Config.Port.icp <= 0)
return;
static double magic_factor = 100.0;
double n_good;
double n_bad;
n_good = magic_factor / (1.0 + request_failure_ratio);
n_bad = magic_factor - n_good;
switch (etype) {
case ERR_DNS_FAIL:
case ERR_CONNECT_FAIL:
case ERR_SECURE_CONNECT_FAIL:
case ERR_READ_ERROR:
++n_bad;
break;
default:
++n_good;
}
request_failure_ratio = n_bad / n_good;
if (hit_only_mode_until > squid_curtime)
return;
if (request_failure_ratio < 1.0)
return;
debugs(33, DBG_CRITICAL, "WARNING: Failure Ratio at "<< std::setw(4)<<
std::setprecision(3) << request_failure_ratio);
debugs(33, DBG_CRITICAL, "WARNING: ICP going into HIT-only mode for " <<
FAILURE_MODE_TIME / 60 << " minutes...");
hit_only_mode_until = squid_curtime + FAILURE_MODE_TIME;
request_failure_ratio = 0.8; /* reset to something less than 1.0 */
}
ClientHttpRequest::~ClientHttpRequest()
{
debugs(33, 3, "httpRequestFree: " << uri);
PROF_start(httpRequestFree);
// Even though freeResources() below may destroy the request,
// we no longer set request->body_pipe to NULL here
// because we did not initiate that pipe (ConnStateData did)
/* the ICP check here was erroneous
* - StoreEntry::releaseRequest was always called if entry was valid
*/
logRequest();
loggingEntry(NULL);
if (request)
checkFailureRatio(request->error.category, al->hier.code);
freeResources();
#if USE_ADAPTATION
announceInitiatorAbort(virginHeadSource);
if (adaptedBodySource != NULL)
stopConsumingFrom(adaptedBodySource);
#endif
if (calloutContext)
delete calloutContext;
clientConnection = NULL;
if (conn_)
cbdataReferenceDone(conn_);
/* moving to the next connection is handled by the context free */
dlinkDelete(&active, &ClientActiveRequests);
PROF_stop(httpRequestFree);
}
/**
* Create a request and kick it off
*
* \retval 0 success
* \retval -1 failure
*
* TODO: Pass in the buffers to be used in the inital Read request, as they are
* determined by the user
*/
int
clientBeginRequest(const HttpRequestMethod& method, char const *url, CSCB * streamcallback,
CSD * streamdetach, ClientStreamData streamdata, HttpHeader const *header,
char *tailbuf, size_t taillen, const MasterXaction::Pointer &mx)
{
size_t url_sz;
ClientHttpRequest *http = new ClientHttpRequest(NULL);
HttpRequest *request;
StoreIOBuffer tempBuffer;
if (http->al != NULL)
http->al->cache.start_time = current_time;
/* this is only used to adjust the connection offset in client_side.c */
http->req_sz = 0;
tempBuffer.length = taillen;
tempBuffer.data = tailbuf;
/* client stream setup */
clientStreamInit(&http->client_stream, clientGetMoreData, clientReplyDetach,
clientReplyStatus, new clientReplyContext(http), streamcallback,
streamdetach, streamdata, tempBuffer);
/* make it visible in the 'current acctive requests list' */
/* Set flags */
/* internal requests only makes sense in an
* accelerator today. TODO: accept flags ? */
http->flags.accel = true;
/* allow size for url rewriting */
url_sz = strlen(url) + Config.appendDomainLen + 5;
http->uri = (char *)xcalloc(url_sz, 1);
strcpy(http->uri, url); // XXX: polluting http->uri before parser validation
request = HttpRequest::FromUrlXXX(http->uri, mx, method);
if (!request) {
debugs(85, 5, "Invalid URL: " << http->uri);
return -1;
}
/*
* now update the headers in request with our supplied headers.
* HttpRequest::FromUrl() should return a blank header set, but
* we use Update to be sure of correctness.
*/
if (header)
request->header.update(header);
/* http struct now ready */
/*
* build new header list *? TODO
*/
request->flags.accelerated = http->flags.accel;
/* this is an internally created
* request, not subject to acceleration
* target overrides */
// TODO: detect and handle internal requests of internal objects?
/* Internally created requests cannot have bodies today */
request->content_length = 0;
request->client_addr.setNoAddr();
#if FOLLOW_X_FORWARDED_FOR
request->indirect_client_addr.setNoAddr();
#endif /* FOLLOW_X_FORWARDED_FOR */
request->my_addr.setNoAddr(); /* undefined for internal requests */
request->my_addr.port(0);
request->http_ver = Http::ProtocolVersion();
http->initRequest(request);
/* optional - skip the access check ? */
http->calloutContext = new ClientRequestContext(http);
http->calloutContext->http_access_done = false;
http->calloutContext->redirect_done = true;
http->calloutContext->no_cache_done = true;
http->doCallouts();
return 0;
}
bool
ClientRequestContext::httpStateIsValid()
{
ClientHttpRequest *http_ = http;
if (cbdataReferenceValid(http_))
return true;
http = NULL;
cbdataReferenceDone(http_);
return false;
}
#if FOLLOW_X_FORWARDED_FOR
/**
* clientFollowXForwardedForCheck() checks the content of X-Forwarded-For:
* against the followXFF ACL, or cleans up and passes control to
* clientAccessCheck().
*
* The trust model here is a little ambiguous. So to clarify the logic:
* - we may always use the direct client address as the client IP.
* - these trust tests merey tell whether we trust given IP enough to believe the
* IP string which it appended to the X-Forwarded-For: header.
* - if at any point we don't trust what an IP adds we stop looking.
* - at that point the current contents of indirect_client_addr are the value set
* by the last previously trusted IP.
* ++ indirect_client_addr contains the remote direct client from the trusted peers viewpoint.
*/
static void
clientFollowXForwardedForCheck(Acl::Answer answer, void *data)
{
ClientRequestContext *calloutContext = (ClientRequestContext *) data;
if (!calloutContext->httpStateIsValid())
return;
ClientHttpRequest *http = calloutContext->http;
HttpRequest *request = http->request;
if (answer.allowed() && request->x_forwarded_for_iterator.size() != 0) {
/*
* Remove the last comma-delimited element from the
* x_forwarded_for_iterator and use it to repeat the cycle.
*/
const char *p;
const char *asciiaddr;
int l;
Ip::Address addr;
p = request->x_forwarded_for_iterator.termedBuf();
l = request->x_forwarded_for_iterator.size();
/*
* XXX x_forwarded_for_iterator should really be a list of
* IP addresses, but it's a String instead. We have to
* walk backwards through the String, biting off the last
* comma-delimited part each time. As long as the data is in
* a String, we should probably implement and use a variant of
* strListGetItem() that walks backwards instead of forwards
* through a comma-separated list. But we don't even do that;
* we just do the work in-line here.
*/
/* skip trailing space and commas */
while (l > 0 && (p[l-1] == ',' || xisspace(p[l-1])))
--l;
request->x_forwarded_for_iterator.cut(l);
/* look for start of last item in list */
while (l > 0 && ! (p[l-1] == ',' || xisspace(p[l-1])))
--l;
asciiaddr = p+l;
if ((addr = asciiaddr)) {
request->indirect_client_addr = addr;
request->x_forwarded_for_iterator.cut(l);
calloutContext->acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
if (!Config.onoff.acl_uses_indirect_client) {
/* override the default src_addr tested if we have to go deeper than one level into XFF */
Filled(calloutContext->acl_checklist)->src_addr = request->indirect_client_addr;
}
if (++calloutContext->currentXffHopNumber < SQUID_X_FORWARDED_FOR_HOP_MAX) {
calloutContext->acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, data);
return;
}
const auto headerName = Http::HeaderLookupTable.lookup(Http::HdrType::X_FORWARDED_FOR).name;
debugs(28, DBG_CRITICAL, "ERROR: Ignoring trailing " << headerName << " addresses" <<
Debug::Extra << "addresses allowed by follow_x_forwarded_for: " << calloutContext->currentXffHopNumber <<
Debug::Extra << "last/accepted address: " << request->indirect_client_addr <<
Debug::Extra << "ignored trailing addresses: " << request->x_forwarded_for_iterator);
// fall through to resume clientAccessCheck() processing
}
}
/* clean up, and pass control to clientAccessCheck */
if (Config.onoff.log_uses_indirect_client) {
/*
* Ensure that the access log shows the indirect client
* instead of the direct client.
*/
http->al->cache.caddr = request->indirect_client_addr;
if (ConnStateData *conn = http->getConn())
conn->log_addr = request->indirect_client_addr;
}
request->x_forwarded_for_iterator.clean();
request->flags.done_follow_x_forwarded_for = true;
if (answer.conflicted()) {
debugs(28, DBG_CRITICAL, "ERROR: Processing X-Forwarded-For. Stopping at IP address: " << request->indirect_client_addr );
}
/* process actual access ACL as normal. */
calloutContext->clientAccessCheck();
}
#endif /* FOLLOW_X_FORWARDED_FOR */
static void
hostHeaderIpVerifyWrapper(const ipcache_addrs* ia, const Dns::LookupDetails &dns, void *data)
{
ClientRequestContext *c = static_cast<ClientRequestContext*>(data);
c->hostHeaderIpVerify(ia, dns);
}
void
ClientRequestContext::hostHeaderIpVerify(const ipcache_addrs* ia, const Dns::LookupDetails &dns)
{
Comm::ConnectionPointer clientConn = http->getConn()->clientConnection;
// note the DNS details for the transaction stats.
http->request->recordLookup(dns);
// Is the NAT destination IP in DNS?
if (ia && ia->have(clientConn->local)) {
debugs(85, 3, "validate IP " << clientConn->local << " possible from Host:");
http->request->flags.hostVerified = true;
http->doCallouts();
return;
}
debugs(85, 3, HERE << "FAIL: validate IP " << clientConn->local << " possible from Host:");
hostHeaderVerifyFailed("local IP", "any domain IP");
}
void
ClientRequestContext::hostHeaderVerifyFailed(const char *A, const char *B)
{
// IP address validation for Host: failed. Admin wants to ignore them.
// NP: we do not yet handle CONNECT tunnels well, so ignore for them
if (!Config.onoff.hostStrictVerify && http->request->method != Http::METHOD_CONNECT) {
debugs(85, 3, "SECURITY ALERT: Host header forgery detected on " << http->getConn()->clientConnection <<
" (" << A << " does not match " << B << ") on URL: " << http->request->effectiveRequestUri());
// NP: it is tempting to use 'flags.noCache' but that is all about READing cache data.
// The problems here are about WRITE for new cache content, which means flags.cachable
http->request->flags.cachable = false; // MUST NOT cache (for now)
// XXX: when we have updated the cache key to base on raw-IP + URI this cacheable limit can go.
http->request->flags.hierarchical = false; // MUST NOT pass to peers (for now)
// XXX: when we have sorted out the best way to relay requests properly to peers this hierarchical limit can go.
http->doCallouts();
return;
}
debugs(85, DBG_IMPORTANT, "SECURITY ALERT: Host header forgery detected on " <<
http->getConn()->clientConnection << " (" << A << " does not match " << B << ")");
if (const char *ua = http->request->header.getStr(Http::HdrType::USER_AGENT))
debugs(85, DBG_IMPORTANT, "SECURITY ALERT: By user agent: " << ua);
debugs(85, DBG_IMPORTANT, "SECURITY ALERT: on URL: " << http->request->effectiveRequestUri());
// IP address validation for Host: failed. reject the connection.
clientStreamNode *node = (clientStreamNode *)http->client_stream.tail->prev->data;
clientReplyContext *repContext = dynamic_cast<clientReplyContext *>(node->data.getRaw());
assert (repContext);
repContext->setReplyToError(ERR_CONFLICT_HOST, Http::scConflict,
http->request->method, NULL,
http->getConn()->clientConnection->remote,
http->request,
NULL,
#if USE_AUTH
http->getConn() != NULL && http->getConn()->getAuth() != NULL ?
http->getConn()->getAuth() : http->request->auth_user_request);
#else
NULL);
#endif
node = (clientStreamNode *)http->client_stream.tail->data;
clientStreamRead(node, http, node->readBuffer);
}
void
ClientRequestContext::hostHeaderVerify()
{
// Require a Host: header.
const char *host = http->request->header.getStr(Http::HdrType::HOST);
if (!host) {
// TODO: dump out the HTTP/1.1 error about missing host header.
// otherwise this is fine, can't forge a header value when its not even set.
debugs(85, 3, HERE << "validate skipped with no Host: header present.");
http->doCallouts();
return;
}
if (http->request->flags.internal) {
// TODO: kill this when URL handling allows partial URLs out of accel mode
// and we no longer screw with the URL just to add our internal host there
debugs(85, 6, HERE << "validate skipped due to internal composite URL.");
http->doCallouts();
return;
}
// Locate if there is a port attached, strip ready for IP lookup
char *portStr = NULL;
char *hostB = xstrdup(host);
host = hostB;
if (host[0] == '[') {
// IPv6 literal.
portStr = strchr(hostB, ']');
if (portStr && *(++portStr) != ':') {
portStr = NULL;
}
} else {
// Domain or IPv4 literal with port
portStr = strrchr(hostB, ':');
}
uint16_t port = 0;
if (portStr) {
*portStr = '\0'; // strip the ':'
if (*(++portStr) != '\0') {
char *end = NULL;
int64_t ret = strtoll(portStr, &end, 10);
if (end == portStr || *end != '\0' || ret < 1 || ret > 0xFFFF) {
// invalid port details. Replace the ':'
*(--portStr) = ':';
portStr = NULL;
} else
port = (ret & 0xFFFF);
}
}
debugs(85, 3, "validate host=" << host << ", port=" << port << ", portStr=" << (portStr?portStr:"NULL"));
if (http->request->flags.intercepted || http->request->flags.interceptTproxy) {
// verify the Host: port (if any) matches the apparent destination
if (portStr && port != http->getConn()->clientConnection->local.port()) {
debugs(85, 3, "FAIL on validate port " << http->getConn()->clientConnection->local.port() <<
" matches Host: port " << port << " (" << portStr << ")");
hostHeaderVerifyFailed("intercepted port", portStr);
} else {
// XXX: match the scheme default port against the apparent destination
// verify the destination DNS is one of the Host: headers IPs
ipcache_nbgethostbyname(host, hostHeaderIpVerifyWrapper, this);
}
} else if (!Config.onoff.hostStrictVerify) {
debugs(85, 3, "validate skipped.");
http->doCallouts();
} else if (strlen(host) != strlen(http->request->url.host())) {
// Verify forward-proxy requested URL domain matches the Host: header
debugs(85, 3, "FAIL on validate URL domain length " << http->request->url.host() << " matches Host: " << host);
hostHeaderVerifyFailed(host, http->request->url.host());
} else if (matchDomainName(host, http->request->url.host()) != 0) {
// Verify forward-proxy requested URL domain matches the Host: header
debugs(85, 3, "FAIL on validate URL domain " << http->request->url.host() << " matches Host: " << host);
hostHeaderVerifyFailed(host, http->request->url.host());
} else if (portStr && port != http->request->url.port()) {
// Verify forward-proxy requested URL domain matches the Host: header
debugs(85, 3, "FAIL on validate URL port " << http->request->url.port() << " matches Host: port " << portStr);
hostHeaderVerifyFailed("URL port", portStr);
} else if (!portStr && http->request->method != Http::METHOD_CONNECT && http->request->url.port() != http->request->url.getScheme().defaultPort()) {
// Verify forward-proxy requested URL domain matches the Host: header
// Special case: we don't have a default-port to check for CONNECT. Assume URL is correct.
debugs(85, 3, "FAIL on validate URL port " << http->request->url.port() << " matches Host: default port " << http->request->url.getScheme().defaultPort());
hostHeaderVerifyFailed("URL port", "default port");
} else {
// Okay no problem.
debugs(85, 3, "validate passed.");
http->request->flags.hostVerified = true;
http->doCallouts();
}
safe_free(hostB);
}
/* This is the entry point for external users of the client_side routines */
void
ClientRequestContext::clientAccessCheck()
{
#if FOLLOW_X_FORWARDED_FOR
if (!http->request->flags.doneFollowXff() &&
Config.accessList.followXFF &&
http->request->header.has(Http::HdrType::X_FORWARDED_FOR)) {
/* we always trust the direct client address for actual use */
http->request->indirect_client_addr = http->request->client_addr;
http->request->indirect_client_addr.port(0);
/* setup the XFF iterator for processing */
http->request->x_forwarded_for_iterator = http->request->header.getList(Http::HdrType::X_FORWARDED_FOR);
/* begin by checking to see if we trust direct client enough to walk XFF */
acl_checklist = clientAclChecklistCreate(Config.accessList.followXFF, http);
acl_checklist->nonBlockingCheck(clientFollowXForwardedForCheck, this);
return;
}
#endif
if (Config.accessList.http) {
acl_checklist = clientAclChecklistCreate(Config.accessList.http, http);
acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
} else {
debugs(0, DBG_CRITICAL, "No http_access configuration found. This will block ALL traffic");
clientAccessCheckDone(ACCESS_DENIED);
}
}
/**
* Identical in operation to clientAccessCheck() but performed later using different configured ACL list.
* The default here is to allow all. Since the earlier http_access should do a default deny all.
* This check is just for a last-minute denial based on adapted request headers.
*/
void
ClientRequestContext::clientAccessCheck2()
{
if (Config.accessList.adapted_http) {
acl_checklist = clientAclChecklistCreate(Config.accessList.adapted_http, http);
acl_checklist->nonBlockingCheck(clientAccessCheckDoneWrapper, this);
} else {
debugs(85, 2, HERE << "No adapted_http_access configuration. default: ALLOW");
clientAccessCheckDone(ACCESS_ALLOWED);
}
}
void
clientAccessCheckDoneWrapper(Acl::Answer answer, void *data)
{
ClientRequestContext *calloutContext = (ClientRequestContext *) data;
if (!calloutContext->httpStateIsValid())
return;
calloutContext->clientAccessCheckDone(answer);
}
void
ClientRequestContext::clientAccessCheckDone(const Acl::Answer &answer)
{
acl_checklist = NULL;
err_type page_id;
Http::StatusCode status;
debugs(85, 2, "The request " << http->request->method << ' ' <<
http->uri << " is " << answer <<
"; last ACL checked: " << (AclMatchedName ? AclMatchedName : "[none]"));
#if USE_AUTH
char const *proxy_auth_msg = "<null>";
if (http->getConn() != NULL && http->getConn()->getAuth() != NULL)
proxy_auth_msg = http->getConn()->getAuth()->denyMessage("<null>");
else if (http->request->auth_user_request != NULL)
proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
#endif
if (!answer.allowed()) {
// auth has a grace period where credentials can be expired but okay not to challenge.
/* Send an auth challenge or error */
// XXX: do we still need aclIsProxyAuth() ?
bool auth_challenge = (answer == ACCESS_AUTH_REQUIRED || aclIsProxyAuth(AclMatchedName));
debugs(85, 5, "Access Denied: " << http->uri);
debugs(85, 5, "AclMatchedName = " << (AclMatchedName ? AclMatchedName : "<null>"));
#if USE_AUTH
if (auth_challenge)
debugs(33, 5, "Proxy Auth Message = " << (proxy_auth_msg ? proxy_auth_msg : "<null>"));
#endif
/*
* NOTE: get page_id here, based on AclMatchedName because if
* USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in
* the clientCreateStoreEntry() call just below. Pedro Ribeiro
* <pribeiro@isel.pt>
*/
page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, answer != ACCESS_AUTH_REQUIRED);
http->logType.update(LOG_TCP_DENIED);
if (auth_challenge) {
#if USE_AUTH
if (http->request->flags.sslBumped) {
/*SSL Bumped request, authentication is not possible*/
status = Http::scForbidden;
} else if (!http->flags.accel) {
/* Proxy authorisation needed */
status = Http::scProxyAuthenticationRequired;
} else {
/* WWW authorisation needed */
status = Http::scUnauthorized;
}
#else
// need auth, but not possible to do.
status = Http::scForbidden;
#endif
if (page_id == ERR_NONE)
page_id = ERR_CACHE_ACCESS_DENIED;
} else {
status = Http::scForbidden;
if (page_id == ERR_NONE)
page_id = ERR_ACCESS_DENIED;
}
Ip::Address tmpnoaddr;
tmpnoaddr.setNoAddr();
error = clientBuildError(page_id, status,
NULL,
http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmpnoaddr,
http->request, http->al
);
#if USE_AUTH
error->auth_user_request =
http->getConn() != NULL && http->getConn()->getAuth() != NULL ?
http->getConn()->getAuth() : http->request->auth_user_request;
#endif
readNextRequest = true;
}
/* ACCESS_ALLOWED continues here ... */
xfree(http->uri);
http->uri = SBufToCstring(http->request->effectiveRequestUri());
http->doCallouts();
}
#if USE_ADAPTATION
void
ClientHttpRequest::noteAdaptationAclCheckDone(Adaptation::ServiceGroupPointer g)
{
debugs(93,3,HERE << this << " adaptationAclCheckDone called");
#if ICAP_CLIENT
Adaptation::Icap::History::Pointer ih = request->icapHistory();
if (ih != NULL) {
if (getConn() != NULL && getConn()->clientConnection != NULL) {
ih->rfc931 = getConn()->clientConnection->rfc931;
#if USE_OPENSSL
if (getConn()->clientConnection->isOpen()) {
ih->ssluser = sslGetUserEmail(fd_table[getConn()->clientConnection->fd].ssl.get());
}
#endif
}
ih->log_uri = log_uri;
ih->req_sz = req_sz;
}
#endif
if (!g) {
debugs(85,3, HERE << "no adaptation needed");
doCallouts();
return;
}
startAdaptation(g);
}
#endif
static void
clientRedirectAccessCheckDone(Acl::Answer answer, void *data)
{
ClientRequestContext *context = (ClientRequestContext *)data;
ClientHttpRequest *http = context->http;
context->acl_checklist = NULL;
if (answer.allowed())
redirectStart(http, clientRedirectDoneWrapper, context);
else {
Helper::Reply const nilReply(Helper::Error);
context->clientRedirectDone(nilReply);
}
}
void
ClientRequestContext::clientRedirectStart()
{
debugs(33, 5, HERE << "'" << http->uri << "'");
http->al->syncNotes(http->request);
if (Config.accessList.redirector) {
acl_checklist = clientAclChecklistCreate(Config.accessList.redirector, http);
acl_checklist->nonBlockingCheck(clientRedirectAccessCheckDone, this);
} else
redirectStart(http, clientRedirectDoneWrapper, this);
}
/**
* This methods handles Access checks result of StoreId access list.
* Will handle as "ERR" (no change) in a case Access is not allowed.
*/
static void
clientStoreIdAccessCheckDone(Acl::Answer answer, void *data)
{
ClientRequestContext *context = static_cast<ClientRequestContext *>(data);
ClientHttpRequest *http = context->http;
context->acl_checklist = NULL;
if (answer.allowed())
storeIdStart(http, clientStoreIdDoneWrapper, context);
else {
debugs(85, 3, "access denied expected ERR reply handling: " << answer);
Helper::Reply const nilReply(Helper::Error);
context->clientStoreIdDone(nilReply);
}
}
/**
* Start locating an alternative storeage ID string (if any) from admin
* configured helper program. This is an asynchronous operation terminating in
* ClientRequestContext::clientStoreIdDone() when completed.
*/
void
ClientRequestContext::clientStoreIdStart()
{
debugs(33, 5,"'" << http->uri << "'");
if (Config.accessList.store_id) {
acl_checklist = clientAclChecklistCreate(Config.accessList.store_id, http);
acl_checklist->nonBlockingCheck(clientStoreIdAccessCheckDone, this);
} else
storeIdStart(http, clientStoreIdDoneWrapper, this);
}
static int
clientHierarchical(ClientHttpRequest * http)
{
HttpRequest *request = http->request;
HttpRequestMethod method = request->method;
// intercepted requests MUST NOT (yet) be sent to peers unless verified
if (!request->flags.hostVerified && (request->flags.intercepted || request->flags.interceptTproxy))
return 0;
/*
* IMS needs a private key, so we can use the hierarchy for IMS only if our
* neighbors support private keys
*/
if (request->flags.ims && !neighbors_do_private_keys)
return 0;
/*
* This is incorrect: authenticating requests can be sent via a hierarchy
* (they can even be cached if the correct headers are set on the reply)
*/
if (request->flags.auth)
return 0;
if (method == Http::METHOD_TRACE)
return 1;
if (method != Http::METHOD_GET)
return 0;
if (request->flags.loopDetected)
return 0;
if (request->url.getScheme() == AnyP::PROTO_HTTP)
return method.respMaybeCacheable();
if (request->url.getScheme() == AnyP::PROTO_GOPHER)
return gopherCachable(request);
if (request->url.getScheme() == AnyP::PROTO_CACHE_OBJECT)
return 0;
return 1;
}
static void
clientCheckPinning(ClientHttpRequest * http)
{
HttpRequest *request = http->request;
HttpHeader *req_hdr = &request->header;
ConnStateData *http_conn = http->getConn();
/* Internal requests such as those from ESI includes may be without
* a client connection
*/
if (!http_conn)
return;
request->flags.connectionAuthDisabled = http_conn->port->connection_auth_disabled;
if (!request->flags.connectionAuthDisabled) {
if (Comm::IsConnOpen(http_conn->pinning.serverConnection)) {