File: Server.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 (438 lines) | stat: -rw-r--r-- 11,424 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
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
<?php

namespace SimpleSAML\Module\cdc;

/**
 * CDC server class.
 *
 * @package SimpleSAMLphp
 */

class Server
{
    /**
     * The domain.
     *
     * @var string
     */
    private $domain;


    /**
     * The URL to the server.
     *
     * @var string
     */
    private $server;


    /**
     * Our shared key.
     *
     * @var string
     */
    private $key;


    /**
     * The lifetime of our cookie, in seconds.
     *
     * If this is 0, the cookie will expire when the browser is closed.
     *
     * @param int
     */
    private $cookieLifetime;


    /**
     * Initialize a CDC server.
     *
     * @param string $domain  The domain we are a server for.
     * @throws \SimpleSAML\Error\Exception
     */
    public function __construct($domain)
    {
        assert(is_string($domain));

        $cdcConfig = \SimpleSAML\Configuration::getConfig('module_cdc.php');
        $config = $cdcConfig->getConfigItem($domain, null);

        if ($config === null) {
            throw new \SimpleSAML\Error\Exception('Unknown CDC domain: '.var_export($domain, true));
        }

        $this->domain = $domain;
        $this->server = $config->getString('server');
        $this->key = $config->getString('key');
        $this->cookieLifetime = $config->getInteger('cookie.lifetime', 0);

        if ($this->key === 'ExampleSharedKey') {
            throw new \SimpleSAML\Error\Exception(
                'Key for CDC domain '.var_export($domain, true).' not changed from default.'
            );
        }
    }


    /**
     * Send a request to this CDC server.
     *
     * @param array $request  The CDC request.
     * @return void
     */
    public function sendRequest(array $request)
    {
        assert(isset($request['return']));
        assert(isset($request['op']));

        $request['domain'] = $this->domain;
        $this->send($this->server, 'CDCRequest', $request);
    }


    /**
     * Parse and validate response received from a CDC server.
     *
     * @return array|null  The response, or NULL if no response is received.
     * @throws \SimpleSAML\Error\Exception
     */
    public function getResponse()
    {
        $response = self::get('CDCResponse');
        if ($response === null) {
            return null;
        }

        if ($response['domain'] !== $this->domain) {
            throw new \SimpleSAML\Error\Exception('Response received from wrong domain.');
        }

        $this->validate('CDCResponse');

        return $response;
    }


    /**
     * Parse and process a CDC request.
     * @throws \SimpleSAML\Error\BadRequest
     * @return void
     */
    public static function processRequest()
    {
        $request = self::get('CDCRequest');
        if ($request === null) {
            throw new \SimpleSAML\Error\BadRequest('Missing "CDCRequest" parameter.');
        }

        $domain = $request['domain'];
        $server = new Server($domain);

        $server->validate('CDCRequest');
        $server->handleRequest($request);
    }


    /**
     * Handle a parsed CDC requst.
     *
     * @param array $request
     * @throws \SimpleSAML\Error\Exception
     * @return void
     */
    private function handleRequest(array $request)
    {
        if (!isset($request['op'])) {
            throw new \SimpleSAML\Error\BadRequest('Missing "op" in CDC request.');
        }
        $op = (string) $request['op'];

        \SimpleSAML\Logger::info('Received CDC request with "op": '.var_export($op, true));

        if (!isset($request['return'])) {
            throw new \SimpleSAML\Error\BadRequest('Missing "return" in CDC request.');
        }
        $return = (string) $request['return'];

        switch ($op) {
            case 'append':
                $response = $this->handleAppend($request);
                break;
            case 'delete':
                $response = $this->handleDelete($request);
                break;
            case 'read':
                $response = $this->handleRead($request);
                break;
            default:
                $response = 'unknown-op';
        }

        if (is_string($response)) {
            $response = [
                'status' => $response,
            ];
        }

        $response['op'] = $op;
        if (isset($request['id'])) {
            $response['id'] = (string) $request['id'];
        }
        $response['domain'] = $this->domain;

        $this->send($return, 'CDCResponse', $response);
    }


    /**
     * Handle an append request.
     *
     * @param array $request  The request.
     * @throws \SimpleSAML\Error\BadRequest
     * @return string The response.
     */
    private function handleAppend(array $request)
    {
        if (!isset($request['entityID'])) {
            throw new \SimpleSAML\Error\BadRequest('Missing entityID in append request.');
        }
        $entityID = (string) $request['entityID'];

        $list = $this->getCDC();

        $prevIndex = array_search($entityID, $list, true);
        if ($prevIndex !== false) {
            unset($list[$prevIndex]);
        }
        $list[] = $entityID;

        $this->setCDC($list);

        return 'ok';
    }


    /**
     * Handle a delete request.
     *
     * @param array $request  The request.
     * @return string The response.
     */
    private function handleDelete(array $request)
    {
        $params = [
            'path' => '/',
            'domain' => '.'.$this->domain,
            'secure' => true,
            'httponly' => false,
        ];

        \SimpleSAML\Utils\HTTP::setCookie('_saml_idp', null, $params, false);
        return 'ok';
    }


    /**
     * Handle a read request.
     *
     * @param array $request  The request.
     * @return array  The response.
     */
    private function handleRead(array $request)
    {
        $list = $this->getCDC();

        return [
            'status' => 'ok',
            'cdc' => $list,
        ];
    }


    /**
     * Helper function for parsing and validating a CDC message.
     *
     * @param string $parameter  The name of the query parameter.
     * @throws \SimpleSAML\Error\BadRequest
     * @return array|null  The response, or NULL if no response is received.
     */
    private static function get($parameter)
    {
        assert(is_string($parameter));

        if (!isset($_REQUEST[$parameter])) {
            return null;
        }
        $message = (string) $_REQUEST[$parameter];

        $message = @base64_decode($message);
        if ($message === false) {
            throw new \SimpleSAML\Error\BadRequest('Error base64-decoding CDC message.');
        }

        $message = @json_decode($message, true);
        if ($message === false) {
            throw new \SimpleSAML\Error\BadRequest('Error json-decoding CDC message.');
        }

        if (!isset($message['timestamp'])) {
            throw new \SimpleSAML\Error\BadRequest('Missing timestamp in CDC message.');
        }
        $timestamp = (int) $message['timestamp'];

        if ($timestamp + 60 < time()) {
            throw new \SimpleSAML\Error\BadRequest('CDC signature has expired.');
        }
        if ($timestamp - 60 > time()) {
            throw new \SimpleSAML\Error\BadRequest('CDC signature from the future.');
        }

        if (!isset($message['domain'])) {
            throw new \SimpleSAML\Error\BadRequest('Missing domain in CDC message.');
        }

        return $message;
    }


    /**
     * Helper function for validating the signature on a CDC message.
     *
     * Will throw an exception if the message is invalid.
     *
     * @param string $parameter  The name of the query parameter.
     * @throws \SimpleSAML\Error\BadRequest
     * @return void
     */
    private function validate($parameter)
    {
        assert(is_string($parameter));
        assert(isset($_REQUEST[$parameter]));

        $message = (string) $_REQUEST[$parameter];

        if (!isset($_REQUEST['Signature'])) {
            throw new \SimpleSAML\Error\BadRequest('Missing Signature on CDC message.');
        }
        $signature = (string) $_REQUEST['Signature'];

        $cSignature = $this->calcSignature($message);
        if ($signature !== $cSignature) {
            throw new \SimpleSAML\Error\BadRequest('Invalid signature on CDC message.');
        }
    }


    /**
     * Helper function for sending CDC messages.
     *
     * @param string $to  The URL the message should be delivered to.
     * @param string $parameter  The query parameter the message should be sent in.
     * @param array $message  The CDC message.
     * @return void
     */
    private function send($to, $parameter, array $message)
    {
        assert(is_string($to));
        assert(is_string($parameter));

        $message['timestamp'] = time();
        $message = json_encode($message);
        $message = base64_encode($message);

        $signature = $this->calcSignature($message);

        $params = [
            $parameter => $message,
            'Signature' => $signature,
        ];

        $url = \SimpleSAML\Utils\HTTP::addURLParameters($to, $params);
        if (strlen($url) < 2048) {
            \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
        } else {
            \SimpleSAML\Utils\HTTP::submitPOSTData($to, $params);
        }
    }


    /**
     * Calculate the signature on the given message.
     *
     * @param string $rawMessage  The base64-encoded message.
     * @return string  The signature.
     */
    private function calcSignature($rawMessage)
    {
        assert(is_string($rawMessage));

        return sha1($this->key.$rawMessage.$this->key);
    }


    /**
     * Get the IdP entities saved in the common domain cookie.
     *
     * @return array  List of IdP entities.
     */
    private function getCDC()
    {
        if (!isset($_COOKIE['_saml_idp'])) {
            return [];
        }

        $ret = (string) $_COOKIE['_saml_idp'];
        $ret = explode(' ', $ret);
        foreach ($ret as &$idp) {
            $idp = base64_decode($idp);
            if ($idp === false) {
                // Not properly base64 encoded
                \SimpleSAML\Logger::warning('CDC - Invalid base64-encoding of CDC entry.');
                return [];
            }
        }

        return $ret;
    }


    /**
     * Build a CDC cookie string.
     *
     * @param array $list  The list of IdPs.
     * @return string  The CDC cookie value.
     */
    private function setCDC(array $list)
    {
        foreach ($list as &$value) {
            $value = base64_encode($value);
        }

        $cookie = implode(' ', $list);

        while (strlen($cookie) > 4000) {
            // The cookie is too long. Remove the oldest elements until it is short enough
            $tmp = explode(' ', $cookie, 2);
            if (count($tmp) === 1) {
                /*
                 * We are left with a single entityID whose base64
                 * representation is too long to fit in a cookie.
                 */
                break;
            }
            $cookie = $tmp[1];
        }

        $params = [
            'lifetime' => $this->cookieLifetime,
            'path' => '/',
            'domain' => '.'.$this->domain,
            'secure' => true,
            'httponly' => false,
        ];

        \SimpleSAML\Utils\HTTP::setCookie('_saml_idp', $cookie, $params, false);

        return '_saml_idp';
    }
}