summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Authentication/Auth.php
blob: f358eac37ef956c2d10a01b182b799b3cb59236e (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
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
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

namespace Icinga\Authentication;

use Exception;
use Icinga\Application\Config;
use Icinga\Application\Hook\AuditHook;
use Icinga\Application\Icinga;
use Icinga\Application\Logger;
use Icinga\Authentication\User\ExternalBackend;
use Icinga\Authentication\UserGroup\UserGroupBackend;
use Icinga\Data\ConfigObject;
use Icinga\Exception\IcingaException;
use Icinga\Exception\NotReadableError;
use Icinga\User;
use Icinga\User\Preferences;
use Icinga\User\Preferences\PreferencesStore;
use Icinga\Web\Session;
use Icinga\Web\StyleSheet;

class Auth
{
    /**
     * Singleton instance
     *
     * @var self
     */
    private static $instance;

    /**
     * Request
     *
     * @var \Icinga\Web\Request
     */
    protected $request;

    /**
     * Response
     *
     * @var \Icinga\Web\Response
     */
    protected $response;

    /**
     * Authenticated user
     *
     * @var User|null
     */
    private $user;


    /**
     * @see getInstance()
     */
    private function __construct()
    {
    }

    /**
     * Get the authentication manager
     *
     * @return self
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Get the auth chain
     *
     * @return AuthChain
     */
    public function getAuthChain()
    {
        return new AuthChain();
    }

    /**
     * Get whether the user is authenticated
     *
     * @return bool
     */
    public function isAuthenticated()
    {
        if ($this->user !== null) {
            return true;
        }
        $this->authenticateFromSession();
        if ($this->user === null && ! $this->authExternal()) {
            return false;
        }
        return true;
    }

    public function setAuthenticated(User $user, $persist = true)
    {
        $this->setupUser($user);

        // Reload CSS if the theme changed
        $themingConfig = Icinga::app()->getConfig()->getSection('themes');
        $userTheme = $user->getPreferences()->getValue('icingaweb', 'theme');
        if (! (bool) $themingConfig->get('disabled', false) && $userTheme !== null) {
            $defaultTheme = $themingConfig->get('default', StyleSheet::DEFAULT_THEME);
            if ($userTheme !== $defaultTheme) {
                $this->getResponse()->setReloadCss(true);
            }
        }

        // Also reload CSS if the theme mode changed
        $themeMode = $user->getPreferences()->getValue('icingaweb', 'theme_mode');
        if ($themeMode && $themeMode !== StyleSheet::DEFAULT_MODE) {
            $this->getResponse()->setReloadCss(true);
        }

        // Reload entire layout if the locale changed
        if (($locale = $user->getPreferences()->getValue('icingaweb', 'language')) !== null) {
            if (setlocale(LC_ALL, 0) !== $locale && $this->getRequest()->isXmlHttpRequest()) {
                $this->getResponse()->setHeader('X-Icinga-Redirect-Http', 'yes');
            }
        }

        $this->user = $user;
        if ($persist) {
            $this->persistCurrentUser();
        }

        AuditHook::logActivity('login', 'User logged in');
    }

    /**
     * Getter for groups belonged to authenticated user
     *
     * @return  array
     * @see     User::getGroups
     */
    public function getGroups()
    {
        return $this->user->getGroups();
    }

    /**
     * Get the request
     *
     * @return \Icinga\Web\Request
     */
    public function getRequest()
    {
        if ($this->request === null) {
            $this->request = Icinga::app()->getRequest();
        }
        return $this->request;
    }

    /**
     * Get the response
     *
     * @return \Icinga\Web\Response
     */
    public function getResponse()
    {
        if ($this->response === null) {
            $this->response = Icinga::app()->getResponse();
        }
        return $this->response;
    }

    /**
     * Get applied restrictions matching a given restriction name
     *
     * Returns a list of applied restrictions, empty if no user is
     * authenticated
     *
     * @param  string  $restriction  Restriction name
     * @return array
     */
    public function getRestrictions($restriction)
    {
        if (! $this->isAuthenticated()) {
            return array();
        }
        return $this->user->getRestrictions($restriction);
    }

    /**
     * Returns the current user or null if no user is authenticated
     *
     * @return User|null
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set the authenticated user
     *
     * Note that this method just sets the authenticated user and thus bypasses our default authentication process in
     * {@link setAuthenticated()}.
     *
     * @param User $user
     *
     * @return $this
     */
    public function setUser(User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Try to authenticate the user with the current session
     *
     * Authentication for externally-authenticated users will be revoked if the username changed or external
     * authentication is no longer in effect
     */
    public function authenticateFromSession()
    {
        $this->user = Session::getSession()->get('user');
        if ($this->user !== null && $this->user->isExternalUser()) {
            list($originUsername, $field) = $this->user->getExternalUserInformation();
            $username = ExternalBackend::getRemoteUser($field);
            if ($username === null || $username !== $originUsername) {
                $this->removeAuthorization();
            }
        }
    }

    /**
     * Attempt to authenticate a user from external user backends
     *
     * @return bool
     */
    protected function authExternal()
    {
        $user = new User('');
        foreach ($this->getAuthChain() as $userBackend) {
            if ($userBackend instanceof ExternalBackend) {
                if ($userBackend->authenticate($user)) {
                    if (! $user->hasDomain()) {
                        $user->setDomain(Config::app()->get('authentication', 'default_domain'));
                    }
                    $this->setAuthenticated($user);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Attempt to authenticate a user using HTTP authentication on API requests only
     *
     * Supports only the Basic HTTP authentication scheme. XHR will be ignored.
     *
     * @return bool
     */
    public function authHttp()
    {
        $request = $this->getRequest();
        $header = $request->getHeader('Authorization');
        if (empty($header)) {
            return false;
        }
        list($scheme) = explode(' ', $header, 2);
        if ($scheme !== 'Basic') {
            return false;
        }
        $authorization = substr($header, strlen('Basic '));
        $credentials = base64_decode($authorization);
        $credentials = array_filter(explode(':', $credentials, 2));
        if (count($credentials) !== 2) {
            // Deny empty username and/or password
            return false;
        }
        $user = new User($credentials[0]);
        if (! $user->hasDomain()) {
            $user->setDomain(Config::app()->get('authentication', 'default_domain'));
        }
        $password = $credentials[1];
        if ($this->getAuthChain()->setSkipExternalBackends(true)->authenticate($user, $password)) {
            $this->setAuthenticated($user, false);
            $user->setIsHttpUser(true);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Challenge client immediately for HTTP authentication
     *
     * Sends the response w/ the 401 Unauthorized status code and WWW-Authenticate header.
     */
    public function challengeHttp()
    {
        $response = $this->getResponse();
        $response->setHttpResponseCode(401);
        $response->setHeader('WWW-Authenticate', 'Basic realm="Icinga Web 2"');
        $response->sendHeaders();
        exit();
    }

    /**
     * Whether an authenticated user has a given permission
     *
     * @param  string  $permission  Permission name
     *
     * @return bool                 True if the user owns the given permission, false if not or if not authenticated
     */
    public function hasPermission($permission)
    {
        if (! $this->isAuthenticated()) {
            return false;
        }
        return $this->user->can($permission);
    }

    /**
     * Writes the current user to the session
     */
    public function persistCurrentUser()
    {
        // @TODO(el): https://dev.icinga.com/issues/10646
        $params = session_get_cookie_params();
        setcookie(
            'icingaweb2-session',
            time(),
            0,
            $params['path'],
            $params['domain'],
            $params['secure'],
            $params['httponly']
        );
        Session::getSession()->set('user', $this->user)->refreshId();
    }

    /**
     * Purges the current authorization information and session
     */
    public function removeAuthorization()
    {
        AuditHook::logActivity('logout', 'User logged out');
        $this->user = null;
        Session::getSession()->purge();
    }

    /**
     * Setup the given user
     *
     * This loads preferences, groups and roles.
     *
     * @param User $user
     *
     * @return void
     */
    public function setupUser(User $user)
    {
        // Load the user's preferences

        try {
            $config = Config::app();
        } catch (NotReadableError $e) {
            Logger::error(
                new IcingaException(
                    'Cannot load preferences for user "%s". An exception was thrown: %s',
                    $user->getUsername(),
                    $e
                )
            );
            $config = new Config();
        }

        $preferencesConfig = new ConfigObject([
            'resource'  => $config->get('global', 'config_resource')
        ]);

        try {
            $preferencesStore = PreferencesStore::create($preferencesConfig, $user);
            $preferences = new Preferences($preferencesStore->load());
        } catch (Exception $e) {
            Logger::error(
                new IcingaException(
                    'Cannot load preferences for user "%s". An exception was thrown: %s',
                    $user->getUsername(),
                    $e
                )
            );
            $preferences = new Preferences();
        }

        $user->setPreferences($preferences);

        // Load the user's groups
        $groups = $user->getGroups();
        $userBackendName = $user->getAdditional('backend_name');
        foreach (Config::app('groups') as $name => $config) {
            $groupsUserBackend = $config->user_backend;
            if ($groupsUserBackend
                && $groupsUserBackend !== 'none'
                && $userBackendName !== null
                && $groupsUserBackend !== $userBackendName
            ) {
                // Do not ask for Group membership if a specific User Backend
                // has been assigned to that Group Backend, and the user has
                // been authenticated by another User Backend
                continue;
            }

            try {
                $groupBackend = UserGroupBackend::create($name, $config);
                $groupsFromBackend = $groupBackend->getMemberships($user);
            } catch (Exception $e) {
                Logger::error(
                    'Can\'t get group memberships for user \'%s\' from backend \'%s\'. An exception was thrown: %s',
                    $user->getUsername(),
                    $name,
                    $e
                );
                continue;
            }

            if (empty($groupsFromBackend)) {
                Logger::debug(
                    'No groups found in backend "%s" which the user "%s" is a member of.',
                    $name,
                    $user->getUsername()
                );
                continue;
            }

            $groupsFromBackend = array_values($groupsFromBackend);
            Logger::debug(
                'Groups found in backend "%s" for user "%s": %s',
                $name,
                $user->getUsername(),
                join(', ', $groupsFromBackend)
            );
            $groups = array_merge($groups, array_combine($groupsFromBackend, $groupsFromBackend));
        }

        $user->setGroups($groups);

        // Load the user's roles
        $admissionLoader = new AdmissionLoader();
        $admissionLoader->applyRoles($user);
    }
}