File: X509userCert.php

package info (click to toggle)
simplesamlphp 1.19.7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,920 kB
  • sloc: php: 202,044; javascript: 14,867; xml: 2,700; sh: 225; perl: 82; makefile: 70; python: 5
file content (222 lines) | stat: -rw-r--r-- 7,369 bytes parent folder | download | duplicates (3)
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
<?php

namespace SimpleSAML\Module\authX509\Auth\Source;

/**
 * This class implements x509 certificate authentication with certificate validation against an LDAP directory.
 *
 * @author Emmanuel Dreyfus <manu@netbsd.org>
 * @package SimpleSAMLphp
 */

class X509userCert extends \SimpleSAML\Auth\Source
{
    /**
     * x509 attributes to use from the certificate for searching the user in the LDAP directory.
     * @var array
     */
    private $x509attributes = ['UID' => 'uid'];


    /**
     * LDAP attribute containing the user certificate.
     * This can be set to NULL to avoid looking up the certificate in LDAP
     * @var array|null
     */
    private $ldapusercert = ['userCertificate;binary'];


    /**
     * @var \SimpleSAML\Module\ldap\ConfigHelper
     */
    private $ldapcf;


    /**
     * Constructor for this authentication source.
     *
     * All subclasses who implement their own constructor must call this constructor before using $config for anything.
     *
     * @param array $info Information about this authentication source.
     * @param array &$config Configuration for this authentication source.
     */
    public function __construct($info, &$config)
    {
        assert(is_array($info));
        assert(is_array($config));

        if (isset($config['authX509:x509attributes'])) {
            $this->x509attributes = $config['authX509:x509attributes'];
        }

        if (array_key_exists('authX509:ldapusercert', $config)) {
            $this->ldapusercert = $config['authX509:ldapusercert'];
        }

        parent::__construct($info, $config);

        $this->ldapcf = new \SimpleSAML\Module\ldap\ConfigHelper(
            $config,
            'Authentication source '.var_export($this->authId, true)
        );
    }


    /**
     * Finish a failed authentication.
     *
     * This function can be overloaded by a child authentication class that wish to perform some operations on failure.
     *
     * @param array &$state Information about the current authentication.
     * @return void
     */
    public function authFailed(&$state)
    {
        $config = \SimpleSAML\Configuration::getInstance();
        $errorcode = $state['authX509.error'];
        $errorcodes = \SimpleSAML\Error\ErrorCodes::getAllErrorCodeMessages();

        $t = new \SimpleSAML\XHTML\Template($config, 'authX509:X509error.php');
        $t->data['loginurl'] = \SimpleSAML\Utils\HTTP::getSelfURL();
        $t->data['errorcode'] = $errorcode;
        $t->data['errorcodes'] = $errorcodes;

        if (!empty($errorcode)) {
            if (array_key_exists($errorcode, $errorcodes['title'])) {
                $t->data['errortitle'] = $errorcodes['title'][$errorcode];
            }
            if (array_key_exists($errorcode, $errorcodes['descr'])) {
                $t->data['errordescr'] = $errorcodes['descr'][$errorcode];
            }
        }

        $t->show();
        exit();
    }


    /**
     * Validate certificate and login.
     *
     * This function try to validate the certificate. On success, the user is logged in without going through the login
     * page. On failure, The authX509:X509error.php template is loaded.
     *
     * @param array &$state Information about the current authentication.
     * @return void
     */
    public function authenticate(&$state)
    {
        assert(is_array($state));
        $ldapcf = $this->ldapcf;

        if (!isset($_SERVER['SSL_CLIENT_CERT']) ||
            ($_SERVER['SSL_CLIENT_CERT'] == '')) {
            $state['authX509.error'] = "NOCERT";
            $this->authFailed($state);

            throw new \Exception("Should never be reached");
        }

        $client_cert = $_SERVER['SSL_CLIENT_CERT'];
        $client_cert_data = openssl_x509_parse($client_cert);
        if ($client_cert_data === false) {
            \SimpleSAML\Logger::error('authX509: invalid cert');
            $state['authX509.error'] = "INVALIDCERT";
            $this->authFailed($state);

            throw new \Exception("Should never be reached");
        }

        $dn = null;
        foreach ($this->x509attributes as $x509_attr => $ldap_attr) {
            // value is scalar
            if (array_key_exists($x509_attr, $client_cert_data['subject'])) {
                $value = $client_cert_data['subject'][$x509_attr];
                \SimpleSAML\Logger::info('authX509: cert '.$x509_attr.' = '.$value);
                $dn = $ldapcf->searchfordn($ldap_attr, $value, true);
                /** 
                 * Remove when SSP 1.18 is released
                 * @psalm-suppress RedundantConditionGivenDocblockType
                 */
                if ($dn !== null) {
                    break;
                }
            }
        }

        if ($dn === null) {
            \SimpleSAML\Logger::error('authX509: cert has no matching user in LDAP.');
            $state['authX509.error'] = "UNKNOWNCERT";
            $this->authFailed($state);

            throw new \Exception("Should never be reached");
        }

        if ($this->ldapusercert === null) {
            // do not check for certificate match
            $attributes = $ldapcf->getAttributes($dn);
            assert(is_array($attributes));
            $state['Attributes'] = $attributes;
            $this->authSuccesful($state);

            throw new \Exception("Should never be reached");
        }

        $ldap_certs = $ldapcf->getAttributes($dn, $this->ldapusercert);

        if (empty($ldap_certs)) {
            \SimpleSAML\Logger::error('authX509: no certificate found in LDAP for dn='.$dn);
            $state['authX509.error'] = "UNKNOWNCERT";
            $this->authFailed($state);

            throw new \Exception("Should never be reached");
        }


        $merged_ldapcerts = [];
        foreach ($this->ldapusercert as $attr) {
            $merged_ldapcerts = array_merge($merged_ldapcerts, $ldap_certs[$attr]);
        }
        $ldap_certs = $merged_ldapcerts;

        foreach ($ldap_certs as $ldap_cert) {
            $pem = \SimpleSAML\Utils\Crypto::der2pem($ldap_cert);
            $ldap_cert_data = openssl_x509_parse($pem);
            if ($ldap_cert_data === false) {
                \SimpleSAML\Logger::error('authX509: cert in LDAP is invalid for dn='.$dn);
                continue;
            }

            if ($ldap_cert_data === $client_cert_data) {
                $attributes = $ldapcf->getAttributes($dn);
                assert(is_array($attributes));
                $state['Attributes'] = $attributes;
                $this->authSuccesful($state);

                throw new \Exception("Should never be reached");
            }
        }

        \SimpleSAML\Logger::error('authX509: no matching cert in LDAP for dn='.$dn);
        $state['authX509.error'] = "UNKNOWNCERT";
        $this->authFailed($state);

        throw new \Exception("Should never be reached");
    }


    /**
     * Finish a successful authentication.
     *
     * This function can be overloaded by a child authentication class that wish to perform some operations after login.
     *
     * @param array &$state Information about the current authentication.
     * @return void
     */
    public function authSuccesful(&$state)
    {
        \SimpleSAML\Auth\Source::completeAuth($state);

        throw new \Exception("Should never be reached");
    }
}