summaryrefslogtreecommitdiffstats
path: root/application/forms/Config/UserBackend/LdapBackendForm.php
blob: e7804cc52a7e83444796567585e7dfc38364c5a0 (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
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

namespace Icinga\Forms\Config\UserBackend;

use Exception;
use Icinga\Data\ResourceFactory;
use Icinga\Protocol\Ldap\LdapCapabilities;
use Icinga\Protocol\Ldap\LdapConnection;
use Icinga\Protocol\Ldap\LdapException;
use Icinga\Web\Form;

/**
 * Form class for adding/modifying LDAP user backends
 */
class LdapBackendForm extends Form
{
    /**
     * The ldap resource names the user can choose from
     *
     * @var array
     */
    protected $resources;

    /**
     * Default values for the form elements
     *
     * @var string[]
     */
    protected $suggestions = array();

    /**
     * Cache for {@link getLdapCapabilities()}
     *
     * @var LdapCapabilities
     */
    protected $ldapCapabilities;

    /**
     * Initialize this form
     */
    public function init()
    {
        $this->setName('form_config_authbackend_ldap');
    }

    /**
     * Set the resource names the user can choose from
     *
     * @param   array   $resources      The resources to choose from
     *
     * @return  $this
     */
    public function setResources(array $resources)
    {
        $this->resources = $resources;
        return $this;
    }

    /**
     * Create and add elements to this form
     *
     * @param   array   $formData
     */
    public function createElements(array $formData)
    {
        $isAd = isset($formData['type']) ? $formData['type'] === 'msldap' : false;

        $this->addElement(
            'text',
            'name',
            array(
                'required'      => true,
                'label'         => $this->translate('Backend Name'),
                'description'   => $this->translate(
                    'The name of this authentication provider that is used to differentiate it from others.'
                ),
                'value'         => $this->getSuggestion('name')
            )
        );
        $this->addElement(
            'select',
            'resource',
            array(
                'required'      => true,
                'label'         => $this->translate('LDAP Connection'),
                'description'   => $this->translate(
                    'The LDAP connection to use for authenticating with this provider.'
                ),
                'multiOptions'  => !empty($this->resources)
                    ? array_combine($this->resources, $this->resources)
                    : array(),
                'value'         => $this->getSuggestion('resource')
            )
        );

        if (! $isAd && !empty($this->resources)) {
            $this->addElement(
                'button',
                'discovery_btn',
                array(
                    'class'             => 'control-button',
                    'type'              => 'submit',
                    'value'             => 'discovery_btn',
                    'label'             => $this->translate('Discover', 'A button to discover LDAP capabilities'),
                    'title'             => $this->translate(
                        'Push to fill in the chosen connection\'s default settings.'
                    ),
                    'decorators'        => array(
                        array('ViewHelper', array('separator' => '')),
                        array('Spinner'),
                        array('HtmlTag', array('tag' => 'div', 'class' => 'control-group form-controls'))
                    ),
                    'formnovalidate'    => 'formnovalidate'
                )
            );
        }

        if ($isAd) {
            // ActiveDirectory defaults
            $userClass = 'user';
            $filter = '!(objectClass=computer)';
            $userNameAttribute = 'sAMAccountName';
        } else {
            // OpenLDAP defaults
            $userClass = 'inetOrgPerson';
            $filter = null;
            $userNameAttribute = 'uid';
        }

        $this->addElement(
            'text',
            'user_class',
            array(
                'preserveDefault'   => true,
                'required'          => ! $isAd,
                'ignore'            => $isAd,
                'disabled'          => $isAd ?: null,
                'label'             => $this->translate('LDAP User Object Class'),
                'description'       => $this->translate('The object class used for storing users on the LDAP server.'),
                'value'             => $this->getSuggestion('user_class', $userClass)
            )
        );
        $this->addElement(
            'text',
            'filter',
            array(
                'preserveDefault'   => true,
                'allowEmpty'        => true,
                'value'             => $this->getSuggestion('filter', $filter),
                'label'             => $this->translate('LDAP Filter'),
                'description'       => $this->translate(
                    'An additional filter to use when looking up users using the specified connection. '
                    . 'Leave empty to not to use any additional filter rules.'
                ),
                'requirement'       => $this->translate(
                    'The filter needs to be expressed as standard LDAP expression.'
                    . ' (e.g. &(foo=bar)(bar=foo) or foo=bar)'
                ),
                'validators'        => array(
                    array(
                        'Callback',
                        false,
                        array(
                            'callback'  => function ($v) {
                                // This is not meant to be a full syntax check. It will just
                                // ensure that we can safely strip unnecessary parentheses.
                                $v = trim($v);
                                return ! $v || $v[0] !== '(' || (
                                    strpos($v, ')(') !== false ? substr($v, -2) === '))' : substr($v, -1) === ')'
                                );
                            },
                            'messages'  => array(
                                'callbackValue' => $this->translate('The filter is invalid. Please check your syntax.')
                            )
                        )
                    )
                )
            )
        );
        $this->addElement(
            'text',
            'user_name_attribute',
            array(
                'preserveDefault'   => true,
                'required'          => ! $isAd,
                'ignore'            => $isAd,
                'disabled'          => $isAd ?: null,
                'label'             => $this->translate('LDAP User Name Attribute'),
                'description'       => $this->translate(
                    'The attribute name used for storing the user name on the LDAP server.'
                ),
                'value'             => $this->getSuggestion('user_name_attribute', $userNameAttribute)
            )
        );
        $this->addElement(
            'hidden',
            'backend',
            array(
                'disabled'  => true,
                'value'     => $this->getSuggestion('backend', $isAd ? 'msldap' : 'ldap')
            )
        );
        $this->addElement(
            'text',
            'base_dn',
            array(
                'preserveDefault'   => true,
                'required'          => false,
                'label'             => $this->translate('LDAP Base DN'),
                'description'       => $this->translate(
                    'The path where users can be found on the LDAP server. Leave ' .
                    'empty to select all users available using the specified connection.'
                ),
                'value'             => $this->getSuggestion('base_dn')
            )
        );

        $this->addElement(
            'text',
            'domain',
            array(
                'label'         => $this->translate('Domain'),
                'description'   => $this->translate(
                    'The domain the LDAP server is responsible for upon authentication.'
                    . ' Note that if you specify a domain here,'
                    . ' the LDAP backend only authenticates users who specify a domain upon login.'
                    . ' If the domain of the user matches the domain configured here, this backend is responsible for'
                    . ' authenticating the user based on the username without the domain part.'
                    . ' If your LDAP backend holds usernames with a domain part or if it is not necessary in your setup'
                    . ' to authenticate users based on their domains, leave this field empty.'
                ),
                'preserveDefault' => true,
                'value'         => $this->getSuggestion('domain')
            )
        );

        $this->addElement(
            'button',
            'btn_discover_domain',
            array(
                'class'             => 'control-button',
                'type'              => 'submit',
                'value'             => 'discovery_btn',
                'label'             => $this->translate('Discover the domain'),
                'title'             => $this->translate(
                    'Push to disover and fill in the domain of the LDAP server.'
                ),
                'decorators'        => array(
                    array('ViewHelper', array('separator' => '')),
                    array('Spinner'),
                    array('HtmlTag', array('tag' => 'div', 'class' => 'control-group form-controls'))
                ),
                'formnovalidate'    => 'formnovalidate'
            )
        );
    }

    public function isValidPartial(array $formData)
    {
        $isAd = isset($formData['type']) && $formData['type'] === 'msldap';
        $baseDn = null;
        $hasAdOid = false;
        $discoverySuccessful = false;

        if (! $isAd && ! empty($this->resources) && isset($formData['discovery_btn'])
            && $formData['discovery_btn'] === 'discovery_btn') {
            $discoverySuccessful = true;
            try {
                $capabilities = $this->getLdapCapabilities($formData);
                $baseDn = $capabilities->getDefaultNamingContext();
                $hasAdOid = $capabilities->isActiveDirectory();
            } catch (Exception $e) {
                $this->warning(sprintf(
                    $this->translate('Failed to discover the chosen LDAP connection: %s'),
                    $e->getMessage()
                ));
                $discoverySuccessful = false;
            }
        }

        if ($discoverySuccessful) {
            if ($isAd || $hasAdOid) {
                // ActiveDirectory defaults
                $userClass = 'user';
                $filter = '!(objectClass=computer)';
                $userNameAttribute = 'sAMAccountName';
            } else {
                // OpenLDAP defaults
                $userClass = 'inetOrgPerson';
                $filter = null;
                $userNameAttribute = 'uid';
            }

            $formData['user_class'] = $userClass;

            if (! isset($formData['filter']) || $formData['filter'] === '') {
                $formData['filter'] = $filter;
            }

            $formData['user_name_attribute'] = $userNameAttribute;

            if ($baseDn !== null && (! isset($formData['base_dn']) || $formData['base_dn'] === '')) {
                $formData['base_dn'] = $baseDn;
            }
        }

        if (isset($formData['btn_discover_domain']) && $formData['btn_discover_domain'] === 'discovery_btn') {
            try {
                $formData['domain'] = $this->discoverDomain($formData);
            } catch (LdapException $e) {
                $this->error($e->getMessage());
            }
        }

        return parent::isValidPartial($formData);
    }

    /**
     * Get the LDAP capabilities of either the resource specified by the user or the default one
     *
     * @param   string[]    $formData
     *
     * @return  LdapCapabilities
     */
    protected function getLdapCapabilities(array $formData)
    {
        if ($this->ldapCapabilities === null) {
            $this->ldapCapabilities = ResourceFactory::create(
                isset($formData['resource']) ? $formData['resource'] : reset($this->resources)
            )->bind()->getCapabilities();
        }

        return $this->ldapCapabilities;
    }

    /**
     * Discover the domain the LDAP server is responsible for
     *
     * @param   string[]    $formData
     *
     * @return  string
     */
    protected function discoverDomain(array $formData)
    {
        $cap = $this->getLdapCapabilities($formData);

        if ($cap->isActiveDirectory()) {
            $netBiosName = $cap->getNetBiosName();
            if ($netBiosName !== null) {
                return $netBiosName;
            }
        }

        return $this->defaultNamingContextToFQDN($cap);
    }

    /**
     * Get the default naming context as FQDN
     *
     * @param   LdapCapabilities    $cap
     *
     * @return  string|null
     */
    protected function defaultNamingContextToFQDN(LdapCapabilities $cap)
    {
        $defaultNamingContext = $cap->getDefaultNamingContext();
        if ($defaultNamingContext !== null) {
            $validationMatches = array();
            if (preg_match('/\bdc=[^,]+(?:,dc=[^,]+)*$/', strtolower($defaultNamingContext), $validationMatches)) {
                $splitMatches = array();
                preg_match_all('/dc=([^,]+)/', $validationMatches[0], $splitMatches);
                return implode('.', $splitMatches[1]);
            }
        }
    }

    /**
     * Get the default values for the form elements
     *
     * @return string[]
     */
    public function getSuggestions()
    {
        return $this->suggestions;
    }

    /**
     * Get the default value for the given form element or the given default
     *
     * @param   string  $element
     * @param   string  $default
     *
     * @return  string
     */
    public function getSuggestion($element, $default = null)
    {
        return isset($this->suggestions[$element]) ? $this->suggestions[$element] : $default;
    }

    /**
     * Set the default values for the form elements
     *
     * @param string[] $suggestions
     *
     * @return $this
     */
    public function setSuggestions(array $suggestions)
    {
        $this->suggestions = $suggestions;

        return $this;
    }
}