File: filterutility.cpp

package info (click to toggle)
icinga2 2.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,040 kB
  • sloc: cpp: 97,870; sql: 3,261; cs: 1,636; yacc: 1,584; sh: 1,009; ansic: 890; lex: 420; python: 80; makefile: 62; javascript: 12
file content (468 lines) | stat: -rw-r--r-- 15,061 bytes parent folder | download
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
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "remote/filterutility.hpp"
#include "remote/httputility.hpp"
#include "config/applyrule.hpp"
#include "config/configcompiler.hpp"
#include "config/expression.hpp"
#include "base/namespace.hpp"
#include "base/json.hpp"
#include "base/configtype.hpp"
#include "base/logger.hpp"
#include "base/utility.hpp"
#include <boost/algorithm/string/case_conv.hpp>
#include <memory>

using namespace icinga;

Dictionary::Ptr FilterUtility::GetTargetForVar(const String& name, const Value& value)
{
	return new Dictionary({
		{ "name", name },
		{ "type", value.GetReflectionType()->GetName() },
		{ "value", value }
	});
}

/**
 * Controls access to an object or variable based on an ApiUser's permissions.
 *
 * This is accomplished by caching the generated filter expressions so they don't have to be
 * regenerated again and again when access is repeatedly checked in script functions and when
 * evaluating expressions.
 */
class FilterExprPermissionChecker : public ScriptPermissionChecker
{
public:
	DECLARE_PTR_TYPEDEFS(FilterExprPermissionChecker);

	explicit FilterExprPermissionChecker(ApiUser::Ptr user) : m_User(std::move(user)) {}

	/**
	 * Check if the user has the given permission and cache the result if they do.
	 *
	 * This is a wrapper around FilterUtility::CheckPermission() that caches the generated
	 * filter expression for later use when checking permissions inside sandboxed ScriptFrames.
	 *
	 * Like FilterUtility::CheckPermission() an exception is thrown if the user does not have
	 * the requested permission.
	 *
	 * If the user has permission and there is a filter for the given permission, the filter
	 * expression  is generated, cached and then a pointer to it is returned, otherwise a
	 * nullptr will be returned.
	 *
	 * Since the optionally returned pointer is a raw-pointer and this class retains ownership
	 * over the expression it is only valid for the lifetime of the @c FilterExprPermissionChecker
	 * object that returned it.
	 *
	 * @param permissionString The permission string to check against the ApiUser member of this class.
	 *
	 * @return a pointer to the generated permission expression if the permission has a filter, or nullptr if not.
	 */
	Expression* CheckPermission(const String& permissionString)
	{
		auto [it, inserted] = m_PermCache.try_emplace(permissionString);
		auto& [hasPermission, permissionExpr] = it->second;

		if (inserted) {
			FilterUtility::CheckPermission(m_User, permissionString, &permissionExpr);
		} else if (!hasPermission) {
			BOOST_THROW_EXCEPTION(ScriptError("Missing permission: " + permissionString.ToLower()));
		}

		hasPermission = true;
		return permissionExpr.get();
	}

	/**
	 * Checks if this object's ApiUser has permissions to access variable `varName`.
	 *
	 * @param varName The name of the variable to check for access
	 *
	 * @return 'true' if the variable can be accessed, 'false' if it can't.
	 */
	bool CanAccessGlobalVariable(const String& varName) override
	{
		auto obj = FilterUtility::GetTargetForVar(varName, ScriptGlobal::Get(varName));
		return CheckPermissionAndEvalFilter("variables", obj, "variable");
	}

	/**
	 * Checks if this object's ApiUser has permissions to access ConfigObject `obj`.
	 *
	 * @param obj A pointer to the ConfigObject to check for access
	 *
	 * @return 'true' if the object can be accessed, 'false' if it can't.
	 */
	bool CanAccessConfigObject(const ConfigObject::Ptr& obj) override
	{
		ASSERT(obj);

		String perm = "objects/query/" + obj->GetReflectionType()->GetName();
		String varName = obj->GetReflectionType()->GetName().ToLower();

		return CheckPermissionAndEvalFilter(perm, obj, varName);
	}

private:
	bool CheckPermissionAndEvalFilter(const String& permissionString, const Object::Ptr& obj, const String& varName)
	{
		auto [it, inserted] = m_PermCache.try_emplace(permissionString);
		auto& [hasPermission, permissionExpr] = it->second;

		if (inserted) {
			hasPermission = FilterUtility::HasPermission(m_User, permissionString, &permissionExpr);
		}

		if (hasPermission && permissionExpr) {
			ScriptFrame permissionFrame(false, new Namespace());
			// Sandboxing is lifted because this only evaluates the function from the
			// ApiUser->permissions->filter
			permissionFrame.Sandboxed = false;
			return FilterUtility::EvaluateFilter(permissionFrame, permissionExpr.get(), obj, varName);
		}

		return hasPermission;
	}

	std::unordered_map<String, std::pair<bool, std::unique_ptr<Expression>>> m_PermCache;
	ApiUser::Ptr m_User;
};

Type::Ptr FilterUtility::TypeFromPluralName(const String& pluralName)
{
	String uname = pluralName;
	boost::algorithm::to_lower(uname);

	for (const Type::Ptr& type : Type::GetAllTypes()) {
		String pname = type->GetPluralName();
		boost::algorithm::to_lower(pname);

		if (uname == pname)
			return type;
	}

	return nullptr;
}

void ConfigObjectTargetProvider::FindTargets(const String& type, const std::function<void (const Value&)>& addTarget) const
{
	Type::Ptr ptype = Type::GetByName(type);
	auto *ctype = dynamic_cast<ConfigType *>(ptype.get());

	if (ctype) {
		for (const ConfigObject::Ptr& object : ctype->GetObjects()) {
			addTarget(object);
		}
	}
}

Value ConfigObjectTargetProvider::GetTargetByName(const String& type, const String& name) const
{
	ConfigObject::Ptr obj = ConfigObject::GetObject(type, name);

	if (!obj)
		BOOST_THROW_EXCEPTION(std::invalid_argument("Object does not exist."));

	return obj;
}

bool ConfigObjectTargetProvider::IsValidType(const String& type) const
{
	Type::Ptr ptype = Type::GetByName(type);

	if (!ptype)
		return false;

	return ConfigObject::TypeInstance->IsAssignableFrom(ptype);
}

String ConfigObjectTargetProvider::GetPluralName(const String& type) const
{
	return Type::GetByName(type)->GetPluralName();
}

bool FilterUtility::EvaluateFilter(ScriptFrame& frame, Expression *filter,
	const Object::Ptr& target, const String& variableName)
{
	if (!filter)
		return true;

	Type::Ptr type = target->GetReflectionType();
	String varName;

	if (variableName.IsEmpty())
		varName = type->GetName().ToLower();
	else
		varName = variableName;

	Namespace::Ptr frameNS;

	if (frame.Self.IsEmpty()) {
		frameNS = new Namespace();
		frame.Self = frameNS;
	} else {
		/* Enforce a namespace object for 'frame.self'. */
		ASSERT(frame.Self.IsObjectType<Namespace>());

		frameNS = frame.Self;

		ASSERT(frameNS != ScriptGlobal::GetGlobals());
	}

	frameNS->Set("obj", target);
	frameNS->Set(varName, target);

	for (int fid = 0; fid < type->GetFieldCount(); fid++) {
		Field field = type->GetFieldInfo(fid);

		if ((field.Attributes & FANavigation) == 0)
			continue;

		Object::Ptr joinedObj = target->NavigateField(fid);

		if (field.NavigationName)
			frameNS->Set(field.NavigationName, joinedObj);
		else
			frameNS->Set(field.Name, joinedObj);
	}

	return Convert::ToBool(filter->Evaluate(frame));
}

static void FilteredAddTarget(ScriptFrame& permissionFrame, Expression *permissionFilter,
	ScriptFrame& frame, Expression *ufilter, std::vector<Value>& result, const String& variableName, const Object::Ptr& target)
{
	if (FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName)) {
		if (FilterUtility::EvaluateFilter(frame, ufilter, target, variableName)) {
			result.emplace_back(std::move(target));
		}
	}
}

/**
 * Checks whether the given API user is granted the given permission
 *
 * When you desire an exception to be raised when the given user doesn't have the given permission,
 * you need to use FilterUtility::CheckPermission().
 *
 * @param user ApiUser pointer to the user object you want to check the permission of
 * @param permission The actual permission you want to check the user permission against
 * @param permissionFilter Expression pointer that is used as an output buffer for all the filter expressions of the
 *                         individual permissions of the given user to be evaluated. It's up to the caller to delete
 *                         this pointer when it's not needed any more.
 *
 * @return bool
 */
bool FilterUtility::HasPermission(const ApiUser::Ptr& user, const String& permission, std::unique_ptr<Expression>* permissionFilter)
{
	if (permissionFilter)
		*permissionFilter = nullptr;

	if (permission.IsEmpty())
		return true;

	bool foundPermission = false;
	String requiredPermission = permission.ToLower();

	Array::Ptr permissions = user->GetPermissions();
	if (permissions) {
		ObjectLock olock(permissions);
		for (const Value& item : permissions) {
			String permission;
			Function::Ptr filter;
			if (item.IsObjectType<Dictionary>()) {
				Dictionary::Ptr dict = item;
				permission = dict->Get("permission");
				filter = dict->Get("filter");
			} else
				permission = item;

			permission = permission.ToLower();

			if (!Utility::Match(permission, requiredPermission))
				continue;

			foundPermission = true;

			if (filter && permissionFilter) {
				std::vector<std::unique_ptr<Expression> > args;
				args.emplace_back(new GetScopeExpression(ScopeThis));
				std::unique_ptr<Expression> indexer{new IndexerExpression(std::unique_ptr<Expression>(MakeLiteral(filter)), std::unique_ptr<Expression>(MakeLiteral("call")))};
				FunctionCallExpression *fexpr = new FunctionCallExpression(std::move(indexer), std::move(args));

				if (!*permissionFilter)
					permissionFilter->reset(fexpr);
				else
					*permissionFilter = std::make_unique<LogicalOrExpression>(std::move(*permissionFilter), std::unique_ptr<Expression>(fexpr));
			}
		}
	}

	if (!foundPermission) {
		Log(LogWarning, "FilterUtility")
			<< "Missing permission: " << requiredPermission;
	}

	return foundPermission;
}

void FilterUtility::CheckPermission(const ApiUser::Ptr& user, const String& permission, std::unique_ptr<Expression>* permissionFilter)
{
	if (!HasPermission(user, permission, permissionFilter)) {
		BOOST_THROW_EXCEPTION(ScriptError("Missing permission: " + permission.ToLower()));
	}
}

std::vector<Value> FilterUtility::GetFilterTargets(const QueryDescription& qd, const Dictionary::Ptr& query, const ApiUser::Ptr& user, const String& variableName)
{
	std::vector<Value> result;

	TargetProvider::Ptr provider;

	if (qd.Provider)
		provider = qd.Provider;
	else
		provider = new ConfigObjectTargetProvider();

	FilterExprPermissionChecker::Ptr permissionChecker = new FilterExprPermissionChecker{user};
	auto* permissionFilter = permissionChecker->CheckPermission(qd.Permission);

	Namespace::Ptr permissionFrameNS = new Namespace();
	ScriptFrame permissionFrame(false, permissionFrameNS);

	for (const String& type : qd.Types) {
		String attr = type;
		boost::algorithm::to_lower(attr);

		if (attr == "type")
			attr = "name";

		if (query && query->Contains(attr)) {
			String name = HttpUtility::GetLastParameter(query, attr);
			Object::Ptr target = provider->GetTargetByName(type, name);

			if (!FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName))
				BOOST_THROW_EXCEPTION(ScriptError("Access denied to object '" + name + "' of type '" + type + "'"));

			result.emplace_back(std::move(target));
		}

		attr = provider->GetPluralName(type);
		boost::algorithm::to_lower(attr);

		if (query && query->Contains(attr)) {
			Array::Ptr names = query->Get(attr);
			if (names) {
				ObjectLock olock(names);
				for (String name : names) {
					Object::Ptr target = provider->GetTargetByName(type, name);

					if (!FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName))
						BOOST_THROW_EXCEPTION(ScriptError("Access denied to object '" + name + "' of type '" + type + "'"));

					result.emplace_back(std::move(target));
				}
			}
		}
	}

	if ((query && query->Contains("filter")) || result.empty()) {
		if (!query->Contains("type"))
			BOOST_THROW_EXCEPTION(std::invalid_argument("Type must be specified when using a filter."));

		String type = HttpUtility::GetLastParameter(query, "type");

		if (!provider->IsValidType(type))
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type specified."));

		if (qd.Types.find(type) == qd.Types.end())
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type specified for this query."));

		Namespace::Ptr frameNS = new Namespace();
		ScriptFrame frame(false, frameNS);
		frame.Sandboxed = true;
		frame.PermChecker = permissionChecker;

		if (query->Contains("filter")) {
			String filter = HttpUtility::GetLastParameter(query, "filter");
			std::unique_ptr<Expression> ufilter = ConfigCompiler::CompileText("<API query>", filter);
			Dictionary::Ptr filter_vars = query->Get("filter_vars");
			bool targeted = false;
			std::vector<ConfigObject::Ptr> targets;

			if (dynamic_cast<ConfigObjectTargetProvider*>(provider.get())) {
				auto dict (dynamic_cast<DictExpression*>(ufilter.get()));

				if (dict) {
					auto& subex (dict->GetExpressions());

					if (subex.size() == 1u) {
						if (type == "Host") {
							std::vector<const String *> targetNames;

							if (ApplyRule::GetTargetHosts(subex.at(0).get(), targetNames, filter_vars)) {
								static const auto typeHost (Type::GetByName("Host"));
								static const auto ctypeHost (dynamic_cast<ConfigType*>(typeHost.get()));
								targeted = true;

								for (auto name : targetNames) {
									auto target (ctypeHost->GetObject(*name));

									if (target) {
										targets.emplace_back(target);
									}
								}
							}
						} else if (type == "Service") {
							std::vector<std::pair<const String *, const String *>> targetNames;

							if (ApplyRule::GetTargetServices(subex.at(0).get(), targetNames, filter_vars)) {
								static const auto typeService (Type::GetByName("Service"));
								static const auto ctypeService (dynamic_cast<ConfigType*>(typeService.get()));
								targeted = true;

								for (auto name : targetNames) {
									auto target (ctypeService->GetObject(*name.first + "!" + *name.second));

									if (target) {
										targets.emplace_back(target);
									}
								}
							}
						}
					}
				}
			}

			if (targeted) {
				for (auto& target : targets) {
					if (FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName)) {
						result.emplace_back(std::move(target));
					}
				}
			} else {
				if (filter_vars) {
					ObjectLock olock (filter_vars);

					for (auto& kv : filter_vars) {
						frameNS->Set(kv.first, kv.second);
					}
				}

				provider->FindTargets(type, [&permissionFrame, permissionFilter, &frame, &ufilter, &result, variableName](const Object::Ptr& target) {
					FilteredAddTarget(permissionFrame, permissionFilter, frame, &*ufilter, result, variableName, target);
				});
			}
		} else {
			/* Ensure to pass a nullptr as filter expression.
			 * GCC 8.1.1 on F28 causes problems, see GH #6533.
			 */
			provider->FindTargets(type, [&permissionFrame, permissionFilter, &frame, &result, variableName](const Object::Ptr& target) {
				FilteredAddTarget(permissionFrame, permissionFilter, frame, nullptr, result, variableName, target);
			});
		}
	}

	return result;
}