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

namespace Icinga\Authentication;

use Icinga\Application\Hook\AuditHook;
use Iterator;
use Icinga\Application\Config;
use Icinga\Application\Logger;
use Icinga\Authentication\User\ExternalBackend;
use Icinga\Authentication\User\UserBackend;
use Icinga\Authentication\User\UserBackendInterface;
use Icinga\Data\ConfigObject;
use Icinga\Exception\AuthenticationException;
use Icinga\Exception\ConfigurationError;
use Icinga\Exception\NotReadableError;
use Icinga\User;

/**
 * Iterate user backends created from config
 */
class AuthChain implements Authenticatable, Iterator
{
    /**
     * Authentication config file
     *
     * @var string
     */
    const AUTHENTICATION_CONFIG = 'authentication';

    /**
     * Error code if the authentication configuration was not readable
     *
     * @var int
     */
    const EPERM = 1;

    /**
     * Error code if the authentication configuration is empty
     */
    const EEMPTY = 2;

    /**
     * Error code if all authentication methods failed
     *
     * @var int
     */
    const EFAIL = 3;

    /**
     * Error code if not all authentication methods were available
     *
     * @var int
     */
    const ENOTALL = 4;

    /**
     * User backends configuration
     *
     * @var Config
     */
    protected $config;

    /**
     * The consecutive user backend while looping
     *
     * @var UserBackendInterface
     */
    protected $currentBackend;

    /**
     * Last error code
     *
     * @var int|null
     */
    protected $error;

    /**
     * Whether external user backends should be skipped on iteration
     *
     * @var bool
     */
    protected $skipExternalBackends = false;

    /**
     * Create a new authentication chain from config
     *
     * @param Config $config User backends configuration
     */
    public function __construct(Config $config = null)
    {
        if ($config === null) {
            try {
                $this->config = Config::app(static::AUTHENTICATION_CONFIG);
            } catch (NotReadableError $e) {
                $this->config = new Config();
                $this->error = static::EPERM;
            }
        } else {
            $this->config = $config;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function authenticate(User $user, $password)
    {
        $this->error = null;
        $backendsTried = 0;
        $backendsWithError = 0;
        foreach ($this as $backend) {
            ++$backendsTried;
            try {
                $authenticated = $backend->authenticate($user, $password);
            } catch (AuthenticationException $e) {
                Logger::error($e);
                ++$backendsWithError;
                continue;
            }
            if ($authenticated) {
                $user->setAdditional('backend_name', $backend->getName());
                $user->setAdditional('backend_type', $this->config->current()->get('backend'));
                return true;
            }
        }

        if ($backendsTried === 0) {
            $this->error = static::EEMPTY;
        } elseif ($backendsTried === $backendsWithError) {
            $this->error = static::EFAIL;
        } elseif ($backendsWithError) {
            $this->error = static::ENOTALL;
        } else {
            AuditHook::logActivity('login-failed', 'User failed to authenticate', null, $user->getUsername());
        }

        return false;
    }

    /**
     * Get the last error code
     *
     * @return int|null
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * Whether authentication had errors
     *
     * @return bool
     */
    public function hasError()
    {
        return $this->error !== null;
    }

    /**
     * Get whether to skip external user backends on iteration
     *
     * @return bool
     */
    public function getSkipExternalBackends()
    {
        return $this->skipExternalBackends;
    }

    /**
     * Set whether to skip external user backends on iteration
     *
     * @param   bool $skipExternalBackends
     *
     * @return  $this
     */
    public function setSkipExternalBackends($skipExternalBackends = true)
    {
        $this->skipExternalBackends = (bool) $skipExternalBackends;
        return $this;
    }

    /**
     * Rewind the chain
     *
     * @return void
     */
    public function rewind(): void
    {
        $this->currentBackend = null;
        $this->config->rewind();
    }

    /**
     * Get the current user backend
     *
     * @return UserBackendInterface
     */
    public function current(): UserBackendInterface
    {
        return $this->currentBackend;
    }

    /**
     * Get the key of the current user backend config
     *
     * @return string
     */
    public function key(): string
    {
        return $this->config->key();
    }

    /**
     * Move forward to the next user backend config
     *
     * @return void
     */
    public function next(): void
    {
        $this->config->next();
    }

    /**
     * Check whether the current user backend is valid, i.e. it's enabled, not an external user backend and whether its
     * config is valid
     *
     * @return bool
     */
    public function valid(): bool
    {
        if (! $this->config->valid()) {
            // Stop when there are no more backends to check
            return false;
        }

        $backendConfig = $this->config->current();
        if ((bool) $backendConfig->get('disabled', false)) {
            $this->next();
            return $this->valid();
        }

        $name = $this->key();
        try {
            $backend = UserBackend::create($name, $backendConfig);
        } catch (ConfigurationError $e) {
            Logger::error(
                new ConfigurationError(
                    'Can\'t create authentication backend "%s". An exception was thrown:',
                    $name,
                    $e
                )
            );
            $this->next();
            return $this->valid();
        }

        if ($this->getSkipExternalBackends()
            && $backend instanceof ExternalBackend
        ) {
            $this->next();
            return $this->valid();
        }

        $this->currentBackend = $backend;
        return true;
    }
}