summaryrefslogtreecommitdiffstats
path: root/library/Icingadb/Common/Auth.php
blob: d25526e65ce8496210b0e3573ea5a3a300c89520 (plain)
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
<?php

/* Icinga DB Web | (c) 2020 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Icingadb\Common;

use Icinga\Authentication\Auth as IcingaAuth;
use Icinga\Exception\ConfigurationError;
use Icinga\Module\Icingadb\Authentication\ObjectAuthorization;
use Icinga\Util\StringHelper;
use ipl\Orm\Compat\FilterProcessor;
use ipl\Orm\Model;
use ipl\Orm\Query;
use ipl\Orm\UnionQuery;
use ipl\Sql\Expression;
use ipl\Stdlib\Filter;
use ipl\Web\Filter\QueryString;

trait Auth
{
    public function getAuth(): IcingaAuth
    {
        return IcingaAuth::getInstance();
    }

    /**
     * Check whether access to the given route is permitted
     *
     * @param string $name
     *
     * @return bool
     */
    public function isPermittedRoute(string $name): bool
    {
        if ($this->getAuth()->getUser()->isUnrestricted()) {
            return true;
        }

        // The empty array is for PHP pre 7.4, older versions require at least a single param for array_merge
        $routeDenylist = array_flip(array_merge([], ...array_map(function ($restriction) {
            return StringHelper::trimSplit($restriction);
        }, $this->getAuth()->getRestrictions('icingadb/denylist/routes'))));

        return ! array_key_exists($name, $routeDenylist);
    }

    /**
     * Check whether the permission is granted on the object
     *
     * @param string $permission
     * @param Model $object
     *
     * @return bool
     */
    public function isGrantedOn(string $permission, Model $object): bool
    {
        if ($this->getAuth()->getUser()->isUnrestricted()) {
            return $this->getAuth()->hasPermission($permission);
        }

        return ObjectAuthorization::grantsOn($permission, $object);
    }

    /**
     * Check whether the permission is granted on objects matching the type and filter
     *
     * The check will be performed on every object matching the filter. Though the result
     * only allows to determine whether the permission is granted on **any** or *none*
     * of the objects in question. Any subsequent call to {@see Auth::isGrantedOn} will
     * make use of the underlying results the check has determined in order to avoid
     * unnecessary queries.
     *
     * @param string $permission
     * @param string $type
     * @param Filter\Rule $filter
     * @param bool $cache Pass `false` to not perform the check on every object
     *
     * @return bool
     */
    public function isGrantedOnType(string $permission, string $type, Filter\Rule $filter, bool $cache = true): bool
    {
        if ($this->getAuth()->getUser()->isUnrestricted()) {
            return $this->getAuth()->hasPermission($permission);
        }

        return ObjectAuthorization::grantsOnType($permission, $type, $filter, $cache);
    }

    /**
     * Check whether the filter matches the given object
     *
     * @param string $queryString
     * @param Model  $object
     *
     * @return bool
     */
    public function isMatchedOn(string $queryString, Model $object): bool
    {
        return ObjectAuthorization::matchesOn($queryString, $object);
    }

    /**
     * Apply Icinga DB Web's restrictions depending on what is queried
     *
     * This will apply `icingadb/filter/objects` in any case. `icingadb/filter/services` is only
     * applied to queries fetching services and `icingadb/filter/hosts` is applied to queries
     * fetching either hosts or services. It also applies custom variable restrictions and
     * obfuscations. (`icingadb/denylist/variables` and `icingadb/protect/variables`)
     *
     * @param Query $query
     *
     * @return void
     */
    public function applyRestrictions(Query $query)
    {
        if ($this->getAuth()->getUser()->isUnrestricted()) {
            return;
        }

        if ($query instanceof UnionQuery) {
            $queries = $query->getUnions();
        } else {
            $queries = [$query];
        }

        $orgQuery = $query;
        foreach ($queries as $query) {
            $relations = [$query->getModel()->getTableName()];
            foreach ($query->getWith() as $relationPath => $relation) {
                $relations[$relationPath] = $relation->getTarget()->getTableName();
            }

            $customVarRelationName = array_search('customvar_flat', $relations, true);
            $applyServiceRestriction = in_array('service', $relations, true);
            $applyHostRestriction = in_array('host', $relations, true)
                // Hosts and services have a special relation as a service can't exist without its host.
                // Hence why the hosts restriction is also applied if only services are queried.
                || $applyServiceRestriction;

            $hostStateRelation = array_search('host_state', $relations, true);
            $serviceStateRelation = array_search('service_state', $relations, true);

            $resolver = $query->getResolver();

            $queryFilter = Filter::any();
            $obfuscationRules = Filter::any();
            foreach ($this->getAuth()->getUser()->getRoles() as $role) {
                $roleFilter = Filter::all();

                if ($customVarRelationName !== false) {
                    if (($restriction = $role->getRestrictions('icingadb/denylist/variables'))) {
                        $roleFilter->add($this->parseDenylist(
                            $restriction,
                            $customVarRelationName
                                ? $resolver->qualifyColumn('flatname', $customVarRelationName)
                                : 'flatname'
                        ));
                    }

                    if (($restriction = $role->getRestrictions('icingadb/protect/variables'))) {
                        $obfuscationRules->add($this->parseDenylist(
                            $restriction,
                            $customVarRelationName
                                ? $resolver->qualifyColumn('flatname', $customVarRelationName)
                                : 'flatname'
                        ));
                    }
                }

                if ($customVarRelationName === false || count($relations) > 1) {
                    if (($restriction = $role->getRestrictions('icingadb/filter/objects'))) {
                        $roleFilter->add($this->parseRestriction($restriction, 'icingadb/filter/objects'));
                    }

                    if ($applyHostRestriction && ($restriction = $role->getRestrictions('icingadb/filter/hosts'))) {
                        $hostFilter = $this->parseRestriction($restriction, 'icingadb/filter/hosts');
                        if ($orgQuery instanceof UnionQuery) {
                            $this->forceQueryOptimization($hostFilter, 'hostgroup.name');
                        }

                        $roleFilter->add($hostFilter);
                    }

                    if (
                        $applyServiceRestriction
                        && ($restriction = $role->getRestrictions('icingadb/filter/services'))
                    ) {
                        $serviceFilter = $this->parseRestriction($restriction, 'icingadb/filter/services');
                        if ($orgQuery instanceof UnionQuery) {
                            $this->forceQueryOptimization($serviceFilter, 'servicegroup.name');
                        }

                        $roleFilter->add(Filter::any(Filter::unlike('service.id', '*'), $serviceFilter));
                    }
                }

                if (! $roleFilter->isEmpty()) {
                    $queryFilter->add($roleFilter);
                }
            }

            if (! $this->getAuth()->hasPermission('icingadb/object/show-source')) {
                // In case the user does not have permission to see the object's `Source` tab, then the user must be
                // restricted from accessing the executed command for the object.
                $columns = $query->getColumns();
                $commandColumns = [];
                if ($hostStateRelation !== false) {
                    $commandColumns[] = $resolver->qualifyColumn('check_commandline', $hostStateRelation);
                }

                if ($serviceStateRelation !== false) {
                    $commandColumns[] = $resolver->qualifyColumn('check_commandline', $serviceStateRelation);
                }

                if (! empty($columns)) {
                    foreach ($commandColumns as $commandColumn) {
                        $commandColumnPath = array_search($commandColumn, $columns, true);
                        if ($commandColumnPath !== false) {
                            $columns[$commandColumn] = new Expression("'***'");
                            unset($columns[$commandColumnPath]);
                        }
                    }

                    $query->columns($columns);
                } else {
                    $query->withoutColumns($commandColumns);
                }
            }

            if (! $obfuscationRules->isEmpty()) {
                $flatvaluePath = $customVarRelationName
                    ? $resolver->qualifyColumn('flatvalue', $customVarRelationName)
                    : 'flatvalue';

                $columns = $query->getColumns();
                if (empty($columns)) {
                    $columns = [
                        $customVarRelationName
                            ? $resolver->qualifyColumn('flatname', $customVarRelationName)
                            : 'flatname',
                        $flatvaluePath
                    ];
                }

                $flatvalue = null;
                if (isset($columns[$flatvaluePath])) {
                    $flatvalue = $columns[$flatvaluePath];
                } else {
                    $flatvaluePathAt = array_search($flatvaluePath, $columns, true);
                    if ($flatvaluePathAt !== false) {
                        $flatvalue = $columns[$flatvaluePathAt];
                        if (is_int($flatvaluePathAt)) {
                            unset($columns[$flatvaluePathAt]);
                        } else {
                            $flatvaluePath = $flatvaluePathAt;
                        }
                    }
                }

                if ($flatvalue !== null) {
                    // TODO: The four lines below are needed because there is still no way to postpone filter column
                    //       qualification. (i.e. Just like the expression, filter rules need to be handled the same
                    //       so that their columns are qualified lazily when assembling the query)
                    $queryClone = clone $query;
                    $queryClone->getSelectBase()->resetWhere();
                    FilterProcessor::apply($obfuscationRules, $queryClone);
                    $where = $queryClone->getSelectBase()->getWhere();

                    $values = [];
                    $rendered = $query->getDb()->getQueryBuilder()->buildCondition($where, $values);
                    $columns[$flatvaluePath] = new Expression(
                        "CASE WHEN (" . $rendered . ") THEN (%s) ELSE '***' END",
                        [$flatvalue],
                        ...$values
                    );

                    $query->columns($columns);
                }
            }

            $query->filter($queryFilter);
        }
    }

    /**
     * Parse the given restriction
     *
     * @param string $queryString
     * @param string $restriction The name of the restriction
     *
     * @return Filter\Rule
     */
    protected function parseRestriction(string $queryString, string $restriction): Filter\Rule
    {
        $allowedColumns = [
            'host.name',
            'hostgroup.name',
            'host.user.name',
            'host.usergroup.name',
            'service.name',
            'servicegroup.name',
            'service.user.name',
            'service.usergroup.name',
            '(host|service).vars.<customvar-name>' => function ($c) {
                return preg_match('/^(?:host|service)\.vars\./i', $c);
            }
        ];

        return QueryString::fromString($queryString)
            ->on(
                QueryString::ON_CONDITION,
                function (Filter\Condition $condition) use (
                    $restriction,
                    $queryString,
                    $allowedColumns
                ) {
                    foreach ($allowedColumns as $column) {
                        if (is_callable($column)) {
                            if ($column($condition->getColumn())) {
                                return;
                            }
                        } elseif ($column === $condition->getColumn()) {
                            return;
                        }
                    }

                    throw new ConfigurationError(
                        t(
                            'Cannot apply restriction %s using the filter %s.'
                            . ' You can only use the following columns: %s'
                        ),
                        $restriction,
                        $queryString,
                        join(
                            ', ',
                            array_map(
                                function ($k, $v) {
                                    return is_string($k) ? $k : $v;
                                },
                                array_keys($allowedColumns),
                                $allowedColumns
                            )
                        )
                    );
                }
            )->parse();
    }

    /**
     * Parse the given denylist
     *
     * @param string $denylist Comma separated list of column names
     * @param string $column The column which should not equal any of the denylisted names
     *
     * @return Filter\None
     */
    protected function parseDenylist(string $denylist, string $column): Filter\None
    {
        $filter = Filter::none();
        foreach (explode(',', $denylist) as $value) {
            $filter->add(Filter::like($column, trim($value)));
        }

        return $filter;
    }

    /**
     * Force query optimization on the given service/host filter rule
     *
     * Applies forceOptimization, when the given filter rule contains the given filter column
     *
     * @param Filter\Rule $filterRule
     * @param string $filterColumn
     *
     * @return void
     */
    protected function forceQueryOptimization(Filter\Rule $filterRule, string $filterColumn)
    {
        // TODO: This is really a very poor solution is therefore only a quick fix.
        //  We need to somehow manage to make this more enjoyable and creative!
        if ($filterRule instanceof Filter\Chain) {
            foreach ($filterRule as $rule) {
                $this->forceQueryOptimization($rule, $filterColumn);
            }
        } elseif ($filterRule->getColumn() === $filterColumn) {
            $filterRule->metaData()->set('forceOptimization', true);
        }
    }
}