1 /*
2 * Copyright (C) 1996-2021 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /* DEBUG: section 16 Cache Manager Objects */
10
11 #include "squid.h"
12 #include "base/TextException.h"
13 #include "CacheManager.h"
14 #include "comm/Connection.h"
15 #include "Debug.h"
16 #include "errorpage.h"
17 #include "fde.h"
18 #include "HttpReply.h"
19 #include "HttpRequest.h"
20 #include "mgr/Action.h"
21 #include "mgr/ActionCreator.h"
22 #include "mgr/ActionPasswordList.h"
23 #include "mgr/ActionProfile.h"
24 #include "mgr/BasicActions.h"
25 #include "mgr/Command.h"
26 #include "mgr/Forwarder.h"
27 #include "mgr/FunAction.h"
28 #include "mgr/QueryParams.h"
29 #include "parser/Tokenizer.h"
30 #include "protos.h"
31 #include "sbuf/Stream.h"
32 #include "sbuf/StringConvert.h"
33 #include "SquidConfig.h"
34 #include "SquidTime.h"
35 #include "Store.h"
36 #include "tools.h"
37 #include "wordlist.h"
38
39 #include <algorithm>
40
41 /// \ingroup CacheManagerInternal
42 #define MGR_PASSWD_SZ 128
43
44 /// creates Action using supplied Action::Create method and command
45 class ClassActionCreator: public Mgr::ActionCreator
46 {
47 public:
48 typedef Mgr::Action::Pointer Handler(const Mgr::Command::Pointer &cmd);
49
50 public:
ClassActionCreator(Handler * aHandler)51 ClassActionCreator(Handler *aHandler): handler(aHandler) {}
52
create(const Mgr::Command::Pointer & cmd) const53 virtual Mgr::Action::Pointer create(const Mgr::Command::Pointer &cmd) const {
54 return handler(cmd);
55 }
56
57 private:
58 Handler *handler;
59 };
60
61 /// Registers new profiles, ignoring attempts to register a duplicate
62 void
registerProfile(const Mgr::ActionProfile::Pointer & profile)63 CacheManager::registerProfile(const Mgr::ActionProfile::Pointer &profile)
64 {
65 Must(profile != NULL);
66 if (!CacheManager::findAction(profile->name)) {
67 menu_.push_back(profile);
68 debugs(16, 3, HERE << "registered profile: " << *profile);
69 } else {
70 debugs(16, 2, HERE << "skipped duplicate profile: " << *profile);
71 }
72 }
73
74 /**
75 \ingroup CacheManagerAPI
76 * Registers a C-style action, which is implemented as a pointer to a function
77 * taking as argument a pointer to a StoreEntry and returning void.
78 * Implemented via CacheManagerActionLegacy.
79 */
80 void
registerProfile(char const * action,char const * desc,OBJH * handler,int pw_req_flag,int atomic)81 CacheManager::registerProfile(char const * action, char const * desc, OBJH * handler, int pw_req_flag, int atomic)
82 {
83 debugs(16, 3, HERE << "registering legacy " << action);
84 const Mgr::ActionProfile::Pointer profile = new Mgr::ActionProfile(action,
85 desc, pw_req_flag, atomic, new Mgr::FunActionCreator(handler));
86 registerProfile(profile);
87 }
88
89 /**
90 * \ingroup CacheManagerAPI
91 * Registers a C++-style action, via a pointer to a subclass of
92 * a CacheManagerAction object, whose run() method will be invoked when
93 * CacheManager identifies that the user has requested the action.
94 */
95 void
registerProfile(char const * action,char const * desc,ClassActionCreator::Handler * handler,int pw_req_flag,int atomic)96 CacheManager::registerProfile(char const * action, char const * desc,
97 ClassActionCreator::Handler *handler,
98 int pw_req_flag, int atomic)
99 {
100 const Mgr::ActionProfile::Pointer profile = new Mgr::ActionProfile(action,
101 desc, pw_req_flag, atomic, new ClassActionCreator(handler));
102 registerProfile(profile);
103 }
104
105 /**
106 \ingroup CacheManagerInternal
107 * Locates an action in the actions registry ActionsList.
108 \retval NULL if Action not found
109 \retval CacheManagerAction* if the action was found
110 */
111 Mgr::ActionProfile::Pointer
findAction(char const * action) const112 CacheManager::findAction(char const * action) const
113 {
114 Must(action != NULL);
115 Menu::const_iterator a;
116
117 debugs(16, 5, "CacheManager::findAction: looking for action " << action);
118 for (a = menu_.begin(); a != menu_.end(); ++a) {
119 if (0 == strcmp((*a)->name, action)) {
120 debugs(16, 6, " found");
121 return *a;
122 }
123 }
124
125 debugs(16, 6, "Action not found.");
126 return Mgr::ActionProfilePointer();
127 }
128
129 Mgr::Action::Pointer
createNamedAction(const char * actionName)130 CacheManager::createNamedAction(const char *actionName)
131 {
132 Must(actionName);
133
134 Mgr::Command::Pointer cmd = new Mgr::Command;
135 cmd->profile = findAction(actionName);
136 cmd->params.actionName = actionName;
137
138 Must(cmd->profile != NULL);
139 return cmd->profile->creator->create(cmd);
140 }
141
142 Mgr::Action::Pointer
createRequestedAction(const Mgr::ActionParams & params)143 CacheManager::createRequestedAction(const Mgr::ActionParams ¶ms)
144 {
145 Mgr::Command::Pointer cmd = new Mgr::Command;
146 cmd->params = params;
147 cmd->profile = findAction(params.actionName.termedBuf());
148 Must(cmd->profile != NULL);
149 return cmd->profile->creator->create(cmd);
150 }
151
152 static const CharacterSet &
MgrFieldChars(const AnyP::ProtocolType & protocol)153 MgrFieldChars(const AnyP::ProtocolType &protocol)
154 {
155 // Deprecated cache_object:// scheme used '@' to delimit passwords
156 if (protocol == AnyP::PROTO_CACHE_OBJECT) {
157 static const CharacterSet fieldChars = CharacterSet("cache-object-field", "@?#").complement();
158 return fieldChars;
159 }
160
161 static const CharacterSet actionChars = CharacterSet("mgr-field", "?#").complement();
162 return actionChars;
163 }
164
165 /**
166 * define whether the URL is a cache-manager URL and parse the action
167 * requested by the user. Checks via CacheManager::ActionProtection() that the
168 * item is accessible by the user.
169 *
170 * Syntax:
171 *
172 * scheme "://" authority [ '/squid-internal-mgr' ] path-absolute [ '@' unreserved ] '?' query-string
173 *
174 * see RFC 3986 for definitions of scheme, authority, path-absolute, query-string
175 *
176 * \returns Mgr::Command object with action to perform and parameters it might use
177 */
178 Mgr::Command::Pointer
ParseUrl(const AnyP::Uri & uri)179 CacheManager::ParseUrl(const AnyP::Uri &uri)
180 {
181 Parser::Tokenizer tok(uri.path());
182
183 static const SBuf internalMagicPrefix("/squid-internal-mgr/");
184 if (!tok.skip(internalMagicPrefix) && !tok.skip('/'))
185 throw TextException("invalid URL path", Here());
186
187 Mgr::Command::Pointer cmd = new Mgr::Command();
188 cmd->params.httpUri = SBufToString(uri.absolute());
189
190 const auto &fieldChars = MgrFieldChars(uri.getScheme());
191
192 SBuf action;
193 if (!tok.prefix(action, fieldChars)) {
194 if (uri.getScheme() == AnyP::PROTO_CACHE_OBJECT) {
195 static const SBuf menuReport("menu");
196 action = menuReport;
197 } else {
198 static const SBuf indexReport("index");
199 action = indexReport;
200 }
201 }
202 cmd->params.actionName = SBufToString(action);
203
204 const auto profile = findAction(action.c_str());
205 if (!profile)
206 throw TextException(ToSBuf("action '", action, "' not found"), Here());
207
208 const char *prot = ActionProtection(profile);
209 if (!strcmp(prot, "disabled") || !strcmp(prot, "hidden"))
210 throw TextException(ToSBuf("action '", action, "' is ", prot), Here());
211 cmd->profile = profile;
212
213 SBuf passwd;
214 if (uri.getScheme() == AnyP::PROTO_CACHE_OBJECT && tok.skip('@')) {
215 (void)tok.prefix(passwd, fieldChars);
216 cmd->params.password = SBufToString(passwd);
217 }
218
219 // TODO: fix when AnyP::Uri::parse() separates path?query#fragment
220 SBuf params;
221 if (tok.skip('?')) {
222 params = tok.remaining();
223 Mgr::QueryParams::Parse(tok, cmd->params.queryParams);
224 }
225
226 if (!tok.skip('#') && !tok.atEnd())
227 throw TextException("invalid characters in URL", Here());
228 // else ignore #fragment (if any)
229
230 debugs(16, 3, "MGR request: host=" << uri.host() << ", action=" << action <<
231 ", password=" << passwd << ", params=" << params);
232
233 return cmd;
234 }
235
236 /// \ingroup CacheManagerInternal
237 /*
238 \ingroup CacheManagerInternal
239 * Decodes the headers needed to perform user authentication and fills
240 * the details into the cachemgrStateData argument
241 */
242 void
ParseHeaders(const HttpRequest * request,Mgr::ActionParams & params)243 CacheManager::ParseHeaders(const HttpRequest * request, Mgr::ActionParams ¶ms)
244 {
245 assert(request);
246
247 params.httpMethod = request->method.id();
248 params.httpFlags = request->flags;
249
250 #if HAVE_AUTH_MODULE_BASIC
251 // TODO: use the authentication system decode to retrieve these details properly.
252
253 /* base 64 _decoded_ user:passwd pair */
254 const auto basic_cookie(request->header.getAuthToken(Http::HdrType::AUTHORIZATION, "Basic"));
255
256 if (basic_cookie.isEmpty())
257 return;
258
259 const auto colonPos = basic_cookie.find(':');
260 if (colonPos == SBuf::npos) {
261 debugs(16, DBG_IMPORTANT, "CacheManager::ParseHeaders: unknown basic_cookie format '" << basic_cookie << "'");
262 return;
263 }
264
265 /* found user:password pair, reset old values */
266 params.userName = SBufToString(basic_cookie.substr(0, colonPos));
267 params.password = SBufToString(basic_cookie.substr(colonPos+1));
268
269 /* warning: this prints decoded password which maybe not be what you want to do @?@ @?@ */
270 debugs(16, 9, "CacheManager::ParseHeaders: got user: '" <<
271 params.userName << "' passwd: '" << params.password << "'");
272 #endif
273 }
274
275 /**
276 \ingroup CacheManagerInternal
277 *
278 \retval 0 if mgr->password is good or "none"
279 \retval 1 if mgr->password is "disable"
280 \retval !0 if mgr->password does not match configured password
281 */
282 int
CheckPassword(const Mgr::Command & cmd)283 CacheManager::CheckPassword(const Mgr::Command &cmd)
284 {
285 assert(cmd.profile != NULL);
286 const char *action = cmd.profile->name;
287 char *pwd = PasswdGet(Config.passwd_list, action);
288
289 debugs(16, 4, "CacheManager::CheckPassword for action " << action);
290
291 if (pwd == NULL)
292 return cmd.profile->isPwReq;
293
294 if (strcmp(pwd, "disable") == 0)
295 return 1;
296
297 if (strcmp(pwd, "none") == 0)
298 return 0;
299
300 if (!cmd.params.password.size())
301 return 1;
302
303 return cmd.params.password != pwd;
304 }
305
306 /**
307 \ingroup CacheManagerAPI
308 * Main entry point in the Cache Manager's activity. Gets called as part
309 * of the forward chain if the right URL is detected there. Initiates
310 * all needed internal work and renders the response.
311 */
312 void
Start(const Comm::ConnectionPointer & client,HttpRequest * request,StoreEntry * entry)313 CacheManager::Start(const Comm::ConnectionPointer &client, HttpRequest * request, StoreEntry * entry)
314 {
315 debugs(16, 3, "request-url= '" << request->url << "', entry-url='" << entry->url() << "'");
316
317 Mgr::Command::Pointer cmd;
318 try {
319 cmd = ParseUrl(request->url);
320
321 } catch (...) {
322 debugs(16, 2, "request URL error: " << CurrentException);
323 const auto err = new ErrorState(ERR_INVALID_URL, Http::scNotFound, request);
324 err->url = xstrdup(entry->url());
325 errorAppendEntry(entry, err);
326 entry->expires = squid_curtime;
327 return;
328 }
329
330 const char *actionName = cmd->profile->name;
331
332 entry->expires = squid_curtime;
333
334 debugs(16, 5, "CacheManager: " << client << " requesting '" << actionName << "'");
335
336 /* get additional info from request headers */
337 ParseHeaders(request, cmd->params);
338
339 const char *userName = cmd->params.userName.size() ?
340 cmd->params.userName.termedBuf() : "unknown";
341
342 /* Check password */
343
344 if (CheckPassword(*cmd) != 0) {
345 /* build error message */
346 ErrorState errState(ERR_CACHE_MGR_ACCESS_DENIED, Http::scUnauthorized, request);
347 /* warn if user specified incorrect password */
348
349 if (cmd->params.password.size()) {
350 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
351 userName << "@" <<
352 client << ": incorrect password for '" <<
353 actionName << "'" );
354 } else {
355 debugs(16, DBG_IMPORTANT, "CacheManager: " <<
356 userName << "@" <<
357 client << ": password needed for '" <<
358 actionName << "'" );
359 }
360
361 HttpReply *rep = errState.BuildHttpReply();
362
363 #if HAVE_AUTH_MODULE_BASIC
364 /*
365 * add Authenticate header using action name as a realm because
366 * password depends on the action
367 */
368 rep->header.putAuth("Basic", actionName);
369 #endif
370 // Allow cachemgr and other XHR scripts access to our version string
371 if (request->header.has(Http::HdrType::ORIGIN)) {
372 rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
373 #if HAVE_AUTH_MODULE_BASIC
374 rep->header.putExt("Access-Control-Allow-Credentials","true");
375 #endif
376 rep->header.putExt("Access-Control-Expose-Headers","Server");
377 }
378
379 /* store the reply */
380 entry->replaceHttpReply(rep);
381
382 entry->expires = squid_curtime;
383
384 entry->complete();
385
386 return;
387 }
388
389 if (request->header.has(Http::HdrType::ORIGIN)) {
390 cmd->params.httpOrigin = request->header.getStr(Http::HdrType::ORIGIN);
391 }
392
393 debugs(16, 2, "CacheManager: " <<
394 userName << "@" <<
395 client << " requesting '" <<
396 actionName << "'" );
397
398 // special case: /squid-internal-mgr/ index page
399 if (!strcmp(cmd->profile->name, "index")) {
400 ErrorState err(MGR_INDEX, Http::scOkay, request);
401 err.url = xstrdup(entry->url());
402 HttpReply *rep = err.BuildHttpReply();
403 if (strncmp(rep->body.content(),"Internal Error:", 15) == 0)
404 rep->sline.set(Http::ProtocolVersion(1,1), Http::scNotFound);
405 // Allow cachemgr and other XHR scripts access to our version string
406 if (request->header.has(Http::HdrType::ORIGIN)) {
407 rep->header.putExt("Access-Control-Allow-Origin",request->header.getStr(Http::HdrType::ORIGIN));
408 #if HAVE_AUTH_MODULE_BASIC
409 rep->header.putExt("Access-Control-Allow-Credentials","true");
410 #endif
411 rep->header.putExt("Access-Control-Expose-Headers","Server");
412 }
413 entry->replaceHttpReply(rep);
414 entry->complete();
415 return;
416 }
417
418 if (UsingSmp() && IamWorkerProcess()) {
419 // is client the right connection to pass here?
420 AsyncJob::Start(new Mgr::Forwarder(client, cmd->params, request, entry));
421 return;
422 }
423
424 Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
425 Must(action != NULL);
426 action->run(entry, true);
427 }
428
429 /*
430 \ingroup CacheManagerInternal
431 * Renders the protection level text for an action.
432 * Also doubles as a check for the protection level.
433 */
434 const char *
ActionProtection(const Mgr::ActionProfile::Pointer & profile)435 CacheManager::ActionProtection(const Mgr::ActionProfile::Pointer &profile)
436 {
437 assert(profile != NULL);
438 const char *pwd = PasswdGet(Config.passwd_list, profile->name);
439
440 if (!pwd)
441 return profile->isPwReq ? "hidden" : "public";
442
443 if (!strcmp(pwd, "disable"))
444 return "disabled";
445
446 if (strcmp(pwd, "none") == 0)
447 return "public";
448
449 return "protected";
450 }
451
452 /*
453 * \ingroup CacheManagerInternal
454 * gets from the global Config the password the user would need to supply
455 * for the action she queried
456 */
457 char *
PasswdGet(Mgr::ActionPasswordList * a,const char * action)458 CacheManager::PasswdGet(Mgr::ActionPasswordList * a, const char *action)
459 {
460 while (a) {
461 for (auto &w : a->actions) {
462 if (w.cmp(action) == 0)
463 return a->passwd;
464
465 static const SBuf allAction("all");
466 if (w == allAction)
467 return a->passwd;
468 }
469
470 a = a->next;
471 }
472
473 return NULL;
474 }
475
476 CacheManager*
GetInstance()477 CacheManager::GetInstance()
478 {
479 static CacheManager *instance = nullptr;
480 if (!instance) {
481 debugs(16, 6, "starting cachemanager up");
482 instance = new CacheManager;
483 Mgr::RegisterBasics();
484 }
485 return instance;
486 }
487