lib.php 46.8 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
6
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21
 *
 * @package    mahara
 * @subpackage auth
22
 * @author     Catalyst IT Ltd
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
25
26
27
 *
 */

28
29
defined('INTERNAL') || die();

30
function xmlrpc_exception (Exception $e) {
Donal McMullan's avatar
Donal McMullan committed
31
32
33
34
35
36
    if (($e instanceof XmlrpcServerException) && get_class($e) == 'XmlrpcServerException') {
        $e->handle_exception();
        return;
    } elseif (($e instanceof MaharaException) && get_class($e) == 'MaharaException') {
        throw new XmlrpcServerException($e->getMessage(), $e->getCode());
        return;
37
    }
Donal McMullan's avatar
Donal McMullan committed
38
39
    xmlrpc_error('An unexpected error has occurred: '.$e->getMessage(), $e->getCode());
    log_message($e->getMessage(), LOG_LEVEL_WARN, true, true, $e->getFile(), $e->getLine(), $e->getTrace());
40
41
}

42
function get_hostname_from_uri($uri = null) {
43
44
45
46
    static $cache = array();
    if (array_key_exists($uri, $cache)) {
        return $cache[$uri];
    }
47
    $count = preg_match("@^(?:http[s]?://)?([A-Z0-9\-\.]+).*@i", $uri, $matches);
48
    $cache[$uri] = $matches[1];
49
50
51
52
53
54
55
56
57
58
59
    if ($count > 0) return $matches[1];
    return false;
}

function dropslash($wwwroot) {
    if (substr($wwwroot, -1, 1) == '/') {
        return substr($wwwroot, 0, -1);
    }
    return $wwwroot;
}

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function generate_token() {
    return sha1(str_shuffle('' . mt_rand(999999,99999999) . microtime(true)));
}

function start_jump_session($peer, $instanceid, $wantsurl="") {
    global $USER;

    $rpc_negotiation_timeout = 15;
    $providers = get_service_providers($USER->authinstance);

    $approved = false;
    foreach ($providers as $provider) {
        if ($provider['wwwroot'] == $peer->wwwroot) {
            $approved = true;
            break;
        }
    }

    if (false == $approved) {
Donal McMullan's avatar
Donal McMullan committed
79
80
        // This shouldn't happen: the user shouldn't have been presented with 
        // the link
81
        throw new AccessTotallyDeniedException('Host not approved for sso');
82
83
84
85
    }

    // set up the session
    $sso_session = get_record('sso_session',
86
                              'userid',     $USER->id);
87
88
89
90
91
92
93
94
95
96
97
    if ($sso_session == false) {
        $sso_session = new stdClass();
        $sso_session->instanceid = $instanceid;
        $sso_session->userid = $USER->id;
        $sso_session->username = $USER->username;
        $sso_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
        $sso_session->token = generate_token();
        $sso_session->confirmtimeout = time() + $rpc_negotiation_timeout;
        $sso_session->expires = time() + (integer)ini_get('session.gc_maxlifetime');
        $sso_session->sessionid = session_id();
        if (! insert_record('sso_session', $sso_session)) {
Donal McMullan's avatar
Donal McMullan committed
98
            throw new SQLException("database error");
99
100
101
102
        }
    } else {
        $sso_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
        $sso_session->token = generate_token();
103
        $sso_session->instanceid = $instanceid;
104
105
        $sso_session->confirmtimeout = time() + $rpc_negotiation_timeout;
        $sso_session->expires = time() + (integer)ini_get('session.gc_maxlifetime');
106
        $sso_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
107
108
        $sso_session->sessionid = session_id();
        if (false == update_record('sso_session', $sso_session, array('userid' => $USER->id))) {
Donal McMullan's avatar
Donal McMullan committed
109
            throw new SQLException("database error");
110
111
112
        }
    }

113
    $wwwroot = dropslash(get_config('wwwroot'));
114
115
116
117
118
119
120

    // construct the redirection URL
    $url = "{$peer->wwwroot}{$peer->application->ssolandurl}?token={$sso_session->token}&idp={$wwwroot}&wantsurl={$wantsurl}";

    return $url;
}

121
function api_dummy_method($methodname, $argsarray, $functionname) {
122
123
124
    return call_user_func_array($functionname, $argsarray);
}

125
126
function find_remote_user($username, $wwwroot) {
    $institution = get_field('host', 'institution', 'wwwroot', $wwwroot);
127
128
129
130
131
132
133

    if (false == $institution) {
        // This should never happen, because if we don't know the host we'll
        // already have exited
        throw new XmlrpcServerException('Unknown error');
    }

134
135
    $authinstances = auth_get_auth_instances_for_institution($institution);
    $candidates    = array();
136
    $auths         = array();
137

138
139
140
141
    $aiid = 'ai.id';
    if (!is_mysql()) {
        $aiid = 'CAST(ai.id AS TEXT)';
    }
142
143
144
    $sql = 'SElECT
                ai.*
            FROM
145
146
147
                {auth_instance} ai,
                {auth_instance} ai2,
                {auth_instance_config} aic
148
149
150
151
            WHERE
                ai.id = ? AND
                ai.institution = ? AND
                ai2.institution = ai.institution AND
152
                ' . $aiid . ' = aic.value AND
153
154
155
156
157
158
159
160
161
162
163
164
165
                aic.field = \'parent\' AND
                aic.instance = ai2.id AND
                ai2.authname = \'xmlrpc\'';

    foreach ($authinstances as $authinstance) {
        if ($authinstance->authname != 'xmlrpc') {
            $records = get_records_sql_array($sql, array($authinstance->id, $institution));
            if (false == $records) {
                continue;
            }
        }
        try {
            $user = new User;
166
            $user->find_by_instanceid_username($authinstance->id, $username, true);
167
            $candidates[$user->id] = $user;
168
            $auths[] = $authinstance->id;
169
170
171
        } catch (Exception $e) {
            // we don't care
            continue;
172
        }
173
174
175
176
177
178
    }

    if (count($candidates) != 1) {
        return false;
    }

179
180
    safe_require('auth', 'xmlrpc');
    return array(array_pop($candidates), new AuthXmlrpc(array_pop($auths)));
181
182
183
184
185
}

function fetch_user_image($username) {
    global $REMOTEWWWROOT;

186
187
    list ($user, $authinstance) = find_remote_user($username, $REMOTEWWWROOT);
    if (!$user) {
188
189
190
        return false;
    }

191
192
    $ic = $user->profileicon;
    if (!empty($ic)) {
193
        $filename = get_config('dataroot') . 'artefact/file/profileicons/' . ($user->profileicon % 256) . '/'.$user->profileicon;
194
195
196
197
198
199
200
201
202
203
        $return = array();
        try {
            $fi = file_get_contents($filename);
        } catch (Exception $e) {
            // meh
        }

        $return['f1'] = base64_encode($fi);

        require_once('file.php');
204
        $im = get_dataroot_image_path('artefact/file/profileicons' , $user->profileicon, 100);
205
206
207
208
        $fi = file_get_contents($im);
        $return['f2'] = base64_encode($fi);
        return $return;
    } else {
209
        // no icon
210
211
212
    }
}

213
function user_authorise($token, $useragent) {
214
    global $USER;
215
216
217

    $sso_session = get_record('sso_session', 'token', $token, 'useragent', $useragent);
    if (empty($sso_session)) {
Donal McMullan's avatar
Donal McMullan committed
218
        throw new XmlrpcServerException('No such session exists');
219
220
221
222
    }

    // check session confirm timeout
    if ($sso_session->expires < time()) {
Donal McMullan's avatar
Donal McMullan committed
223
        throw new XmlrpcServerException('This session has timed out');
224
225
226
227
228
229
230
    }

    // session okay, try getting the user
    $user = new User();
    try {
        $user->find_by_id($sso_session->userid);
    } catch (Exception $e) {
Donal McMullan's avatar
Donal McMullan committed
231
        throw new XmlrpcServerException('Unable to get information for the specified user');
232
233
    }

234
235
    require(get_config('docroot') . 'artefact/lib.php');
    require(get_config('docroot') . 'artefact/internal/lib.php');
236
237
238
239
240
241
242

    $element_list = call_static_method('ArtefactTypeProfile', 'get_all_fields');
    $element_required = call_static_method('ArtefactTypeProfile', 'get_mandatory_fields');

    // load existing profile information
    $profilefields = array();
    $profile_data = get_records_select_assoc('artefact', "owner=? AND artefacttype IN (" . join(",",array_map(create_function('$a','return db_quote($a);'),array_keys($element_list))) . ")", array($USER->get('id')), '','artefacttype, title');
243
244
245
    if ($profile_data == false) {
        $profile_data = array();
    }
246
247

    $email = get_field('artefact_internal_profile_email', 'email', 'owner', $sso_session->userid, 'principal', 1);
248
    if (false == $email) {
Donal McMullan's avatar
Donal McMullan committed
249
        throw new XmlrpcServerException("No email adress for user");
250
251
252
253
    }

    $userdata = array();
    $userdata['username']                = $user->username;
254
    $userdata['email']                   = $email;
255
256
257
258
259
    $userdata['auth']                    = 'mnet';
    $userdata['confirmed']               = 1;
    $userdata['deleted']                 = 0;
    $userdata['firstname']               = $user->firstname;
    $userdata['lastname']                = $user->lastname;
260
261
    $userdata['city']                    = array_key_exists('city', $profile_data) ? $profile_data['city']->title : '';
    $userdata['country']                 = array_key_exists('country', $profile_data) ? $profile_data['country']->title : '';
262

263
    if (is_numeric($user->profileicon)) {
264
        $filename = get_config('dataroot') . 'artefact/file/profileicons/' . ($user->profileicon % 256) . '/'.$user->profileicon;
265
        if (file_exists($filename) && is_readable($filename)) {
266
            $userdata['imagehash'] = sha1_file($filename);
267
268
269
270
271
272
273
274
275
276
277
        }
    }

    get_service_providers($USER->authinstance);

    // Todo: push application name to list of hosts... update Moodle block to display more info, maybe in 'Other' list
    $userdata['myhosts'] = array();

    return $userdata;
}

278
279
function send_content_intent($username) {
    global $REMOTEWWWROOT;
280
    require_once(get_config('docroot') . 'import/lib.php');
281

282
283
    list ($user, $authinstance) = find_remote_user($username, $REMOTEWWWROOT);
    if (!$user) {
284
        throw new ImportException(null, "Could not find user $username for $REMOTEWWWROOT");
285
286
    }

287
    if (!is_executable(get_config('pathtounzip'))) {
288
        throw new ImportException(null, "Cannot find unzip executable");
289
    }
290

291
    if (!$authinstance->weimportcontent) {
292
        $e = new ImportException(null, 'Importing content is disabled');
293
294
        $e->set_log_off(); // we don't want these ones.
        throw $e;
295
296
    }

297
    $queue = PluginImport::create_new_queue($user->id, null, $REMOTEWWWROOT, 0);
298
299

    return array(
300
        'sendtype' => (($queue->queue) ? 'queue' : 'immediate'),
301
302
303
304
        'token' => $queue->token,
    );
}

305
function send_content_ready($token, $username, $format, $importdata, $fetchnow=false) {
306
    global $REMOTEWWWROOT;
307
    require_once(get_config('docroot') . 'import/lib.php');
308

309
310
    list ($user, $authinstance) = find_remote_user($username, $REMOTEWWWROOT);
    if (!$user) {
311
        throw new ImportException(null, "Could not find user $username for $REMOTEWWWROOT");
312
313
314
315
    }

    // go verify the token
    if (!$queue = get_record('import_queue', 'token', $token, 'host', $REMOTEWWWROOT)) {
316
        throw new ImportException(null, "Could not find queue record with given token for username $username for $REMOTEWWWROOT");
317
318
319
    }

    if (strtotime($queue->expirytime) < time()) {
320
        throw new ImportException(null, "Queue record has expired");
321
322
    }

323
324
325
326
327
328
329
    $class = null;
    try {
        $class = PluginImport::class_from_format($format);
    } catch (Exception $e) {
        throw new ImportException(null, "Invalid format $format");
    }

330
    $queue->format = $format;
331
332
333
334
    if ($class == 'PluginImportLeap') {
        // don't import persondata over mnet
        // because it will just silently overwrite stuff
        // which is not really desirable.
335
        $queue->loglevel = get_config('leapovermnetloglevel');
336
337
        $importdata['skippersondata'] = true;
    }
338
339
340
    $queue->data = serialize($importdata);
    update_record('import_queue', $queue);
    $tr = new MnetImporterTransport($queue);
341
    try {
342
        $tr->validate_import_data();
343
    } catch (Exception $e) {
344
        throw new ImportException(null, 'Invalid importdata: ' . $e->getMessage());
345
    }
346
347


348

349
    if (!array_key_exists('totalsize', $importdata)) {
350
        throw new ImportException(null, 'Invalid importdata: missing totalsize');
351
352
353
    }

    if (!$user->quota_allowed($importdata['totalsize'])) {
354
        $e = new ImportException(null, 'Exceeded user quota');
355
356
357
358
        $e->set_log_off();
        throw $e;
    }

359
360

    $result = new StdClass;
361
    if ($fetchnow && PluginImport::import_immediately_allowed()) {
362
        // either immediately spawn a curl request to go fetch the file
363
        $importer = PluginImport::create_importer($queue->id, $tr, $queue);
364
        $importer->prepare();
365
366
367
368
369
        try {
            $importer->validate_transported_data($tr);
        } catch (Exception $e) {
            throw new ImportException(null, 'Invalid importdata: ' . $e->getMessage());
        }
370
        $importer->process();
371
        $importer->cleanup();
372
        delete_records('import_queue', 'id', $queue->id);
373
374
        $result->status = true;
        $result->type = 'complete';
375
376
377
378
379
        $returndata = $importer->get_return_data();
        $result->querystring = '?';
        foreach ($importer->get_return_data() as $k => $v) {
            $result->querystring .= $k . '=' . $v . '&';
        }
380
381
382
383
384
    } else {
        // or set ready to 1 for the next cronjob to go fetch it.
        $result->status = set_field('import_queue', 'ready', 1, 'id', $queue->id);
        $result->type = 'queued';
    }
385
    $importer->get('importertransport')->cleanup();
386
387
388
    return $result;
}

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
454
455
456
457
458
459
460
461
462
/**
 * If we're an IDP, kill_children will kill the session of the given user here, 
 * as well as at any other children
 *
 * NOTE: well, currently it doesn't call kill_child on any other children, but 
 * it will kill the local sessions for the user
 *
 * @param   string  $username       Username for session to kill
 * @param   string  $useragent      SHA1 hash of user agent to look for
 * @return  string                  A plaintext report of what has happened
 */
function kill_children($username, $useragent) {
    global $REMOTEWWWROOT; // comes from server.php
    //require_once(get_config('docroot') .'api/xmlrpc/client.php');

    // We've received a logout request for user X. In Mahara, usernames are unique. So we check that user X 
    // has an authinstance that would have been able to SSO to the remote site.
    $userid = get_field('usr', 'id', 'username', $username);
    $providers = get_service_providers(get_field('usr', 'authinstance', 'username', $username));

    $approved = false;
    foreach ($providers as $provider) {
        if ($provider['wwwroot'] == $REMOTEWWWROOT) {
            $approved = true;
            break;
        }
    }

    if (false == $approved) {
        return 'This host is not permitted to kill sessions for this username';
    }

    $mnetsessions = get_records_select_array('sso_session', 'userid = ? AND useragent = ?', array($userid, $useragent));

    // Prepare to destroy local sessions associated with the user
    $start = ob_start();
    $uc = ini_get('session.use_cookies');
    ini_set('session.use_cookies', false);
    $sesscache = isset($_SESSION) ? clone($_SESSION) : null;
    $sessidcache = session_id();
    session_write_close();
    unset($_SESSION);

    foreach($mnetsessions as $mnetsession) {
        // Kills all local sessions associated with this user
        // TODO: We should send kill_child requests to the remote servers too
        session_id($mnetsession->sessionid);
        session_start();
        session_unregister("USER");
        session_unregister("SESSION");
        unset($_SESSION);
        $_SESSION = array();
        session_destroy();
        session_write_close();
    }

    // We're done destroying local sessions
    ini_set('session.use_cookies', $uc);
    if ($sessidcache) {
        session_name(get_config('cookieprefix') . 'mahara');
        session_id($sessidcache);
        session_start();
        $_SESSION = ($sesscache) ? clone($sesscache) : null;
        session_write_close();
    }
    $end = ob_end_clean();

    delete_records('sso_session',
                   'useragent', $useragent,
                   'userid',    $userid);

    return true;
}

463
464
465
466
function xmlrpc_not_implemented() {
    return true;
}

467
468
469
470
471
472
473
474
function get_views_for_user($username, $query=null) {
    global $REMOTEWWWROOT, $USER;

    list ($user, $authinstance) = find_remote_user($username, $REMOTEWWWROOT);
    if (!$user) {
        return false;
    }

475
    $USER->reanimate($user->id, $authinstance->instanceid);
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
    require_once('view.php');
    $data = View::view_search($query, null, (object) array('owner' => $USER->get('id')));
    $data->displayname = display_name($user);
    if ($data->count) {
        foreach ($data->data as &$v) {
            $v['url'] = '/view/view.php?id=' . $v['id'];
            $v['fullurl'] = get_config('wwwroot') . 'view/view.php?id=' . $v['id'];
        }
    }
    return $data;
}

function submit_view_for_assessment($username, $viewid) {
    global $REMOTEWWWROOT;

    list ($user, $authinstance) = find_remote_user($username, $REMOTEWWWROOT);
    if (!$user) {
        return false;
    }

    $viewid = (int) $viewid;
    if (!$viewid) {
        return false;
    }

    require_once('view.php');
    $view = new View($viewid);

    $view->set('submittedhost', $authinstance->config['wwwroot']);

    // Create secret key
    $access = View::new_token($view->get('id'), false);

    $data = array(
        'id'          => $view->get('id'),
        'title'       => $view->get('title'),
        'description' => $view->get('description'),
        'fullurl'     => get_config('wwwroot') . 'view/view.php?id=' . $view->get('id') . '&mt=' . $access->token,
        'url'         => '/view/view.php?id=' . $view->get('id') . '&mt=' . $access->token,
        'accesskey'   => $access->token,
    );

    foreach (plugins_installed('artefact') as $plugin) {
        safe_require('artefact', $plugin->name);
        $classname = generate_class_name('artefact', $plugin->name);
        if (is_callable($classname . '::view_submit_external_data')) {
            $data[$plugin->name] = call_static_method($classname, 'view_submit_external_data', $view->get('id'));
        }
    }

    return $data;
}

function release_submitted_view($viewid, $assessmentdata, $teacherusername) {
    global $REMOTEWWWROOT, $USER;

    require_once('view.php');
    $view = new View($viewid);
    list ($teacher, $authinstance) = find_remote_user($teacherusername, $REMOTEWWWROOT);

    db_begin();
    foreach (plugins_installed('artefact') as $plugin) {
        safe_require('artefact', $plugin->name);
        $classname = generate_class_name('artefact', $plugin->name);
        if (is_callable($classname . '::view_release_external_data')) {
            call_static_method($classname, 'view_release_external_data', $view, $assessmentdata, $teacher ? $teacher->id : 0);
        }
    }

    // Release the view for editing
    $view->set('submittedhost', null);
    $view->commit();
    db_commit();
}

551
552
553
554
555
556
557
/**
 * Given a USER, get all Service Providers for that User, based on child auth
 * instances of its canonical auth instance
 */
function get_service_providers($instance) {
    static $cache = array();

558
559
560
561
    if (defined('INSTALLER')) {
        return array();
    }

562
563
564
565
    if (array_key_exists($instance, $cache)) {
        return $cache[$instance];
    }

566
    $query = "
567
568
569
570
571
572
        SELECT
            h.name,
            a.ssolandurl,
            h.wwwroot,
            aic.instance
        FROM
573
574
575
576
577
            {auth_instance_config} aic,
            {auth_instance_config} aic2,
            {auth_instance_config} aic3,
            {host} h,
            {application} a
578
        WHERE
579
580
          ((aic.value = '1' AND
            aic.field = 'theyautocreateusers' ) OR
581
           (aic.value = ?  AND
582
            aic.field = 'parent')) AND
583
584

            aic.instance = aic2.instance AND
585
            aic2.field = 'wwwroot' AND
586
587
588
            aic2.value = h.wwwroot AND

            aic.instance = aic3.instance AND
589
590
            aic3.field = 'wessoout' AND
            aic3.value = '1' AND
591

592
            a.name = h.appname";
593
594
595
596
597
598
    try {
        $results = get_records_sql_assoc($query, array('value' => $instance));
    } catch (SQLException $e) {
        // Table doesn't exist yet
        return array();
    }
599
600
601
602
603
604
605
606
607
608
609
610
611

    if (false == $results) {
        $results = array();
    }

    foreach($results as $key => $result) {
        $results[$key] = get_object_vars($result);
    }

    $cache[$instance] = $results;
    return $cache[$instance];
}

612
function get_public_key($uri, $application=null) {
613

614
615
616
617
618
619
620
    static $keyarray = array();
    if (isset($keyarray[$uri])) {
        return $keyarray[$uri];
    }

    $openssl = OpenSslRepo::singleton();

621
    if (empty($application)) {
622
        $application = 'moodle';
623
    }
624

625
    $xmlrpcserverurl = get_field('application', 'xmlrpcserverurl', 'name', $application);
626
627
628
    if (empty($xmlrpcserverurl)) {
        throw new XmlrpcClientException('Unknown application');
    } 
629
    $wwwroot = dropslash(get_config('wwwroot'));
630

631
    $rq = xmlrpc_encode_request('system/keyswap', array($wwwroot, $openssl->certificate), array("encoding" => "utf-8"));
632

633
634
635
636
637
638
639
640
    $config = array(
        CURLOPT_URL => $uri . $xmlrpcserverurl,
        CURLOPT_POST => true,
        CURLOPT_USERAGENT => 'Moodle',
        CURLOPT_POSTFIELDS => $rq,
        CURLOPT_HTTPHEADER => array("Content-Type: text/xml charset=UTF-8", 'Expect: '),
    );

641
    $result = mahara_http_request($config);
642

643
644
645
    if (!empty($result->errno)) {
        throw new XmlrpcClientException('Curl error: ' . $result->errno . ': ' . $result->error);
    }
646
    if (empty($result->data)) {
647
648
        throw new XmlrpcClientException('CURL connection failed');
    }
649

650
    $response_code        = $result->info['http_code'];
651
652
653
654
655
    $response_code_prefix = substr($response_code, 0, 1);

    if ('2' != $response_code_prefix) {
        if ('4' == $response_code_prefix) {
            throw new XmlrpcClientException('Client error code: ', $response_code);
656
        } elseif ('5' == $response_code_prefix) {
657
658
659
660
            throw new XmlrpcClientException('An error occurred at the remote server. Code: ', $response_code);
        }
    }

661
    $res = xmlrpc_decode($result->data);
662

663
664
665
    // XMLRPC error messages are returned as an array
    // We are expecting a string
    if (!is_array($res)) {
666
667
668
669
670
671
672
673
        $keyarray[$uri] = $res;
        $credentials=array();
        if (strlen(trim($keyarray[$uri]))) {
            $credentials = openssl_x509_parse($keyarray[$uri]);
            $host = $credentials['subject']['CN'];
            if (strpos($uri, $host) !== false) {
                return $keyarray[$uri];
            }
674
            throw new XmlrpcClientException('The remote site sent us a key that is valid for ' . $host . ' instead of their hostname (' . $uri . ')', 500);
675
        }
676
677
    } else {
        throw new XmlrpcClientException($res['faultString'], $res['faultCode']);
678
679
680
681
    }
    return false;
}

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/**
 * Output a valid XML-RPC error message.
 *
 * @param  string   $message              The error message
 * @param  int      $code                 Unique identifying integer
 * @return string                         An XMLRPC error doc
 */
function xmlrpc_error($message, $code) {
    echo <<<EOF
<?xml version="1.0"?>
<methodResponse>
   <fault>
      <value>
         <struct>
            <member>
               <name>faultCode</name>
               <value><int>$code</int></value>
            </member>
            <member>
               <name>faultString</name>
               <value><string>$message</string></value>
            </member>
         </struct>
      </value>
   </fault>
</methodResponse>
EOF;
}

711
function xmlenc_envelope_strip(&$xml, $oldkeyok=false) {
712
713
714
715
716
    $openssl           = OpenSslRepo::singleton();
    $payload_encrypted = true;
    $data              = base64_decode($xml->EncryptedData->CipherData->CipherValue);
    $key               = base64_decode($xml->EncryptedKey->CipherData->CipherValue);
    $payload           = '';    // Initialize payload var
717
    $payload           = $openssl->openssl_open($data, $key, $oldkeyok);
718
719
720
721
722
723
724
725
726
    $xml               = parse_payload($payload);
    return $payload;
}

function parse_payload($payload) {
    try {
        $xml = new SimpleXMLElement($payload);
        return $xml;
    } catch (Exception $e) {
Donal McMullan's avatar
Donal McMullan committed
727
        throw new MaharaException('Encrypted payload is not a valid XML document', 6002);
728
729
730
    }
}

731
function get_peer($wwwroot, $cache=true) {
732

733
734
    $wwwroot = (string)$wwwroot;
    static $peers = array();
735
736
737
    if ($cache) {
        if (isset($peers[$wwwroot])) return $peers[$wwwroot];
    }
738

739
    require_once(get_config('libroot') . 'peer.php');
740
    $peer = new Peer();
741

742
    if (!$peer->findByWwwroot($wwwroot)) {
743
        // Bootstrap unknown hosts?
744
        throw new MaharaException("We don't have a record for your webserver ($wwwroot) in our database", 6003);
745
746
747
748
749
    }
    $peers[$wwwroot] = $peer;
    return $peers[$wwwroot];
}

750
751
752
753
function get_peer_from_instanceid($authinstanceid) {
    $sql = 'SELECT
                h.*
            FROM
754
                {auth_instance_config} aic,
755
756
                {host} h
            WHERE
757
758
                aic.value = h.wwwroot AND
                aic.instance = ? AND aic.field = \'wwwroot\'';
759
760
761
    return get_record_sql($sql, array($authinstanceid));
}

762
763
764
/**
 * Check that the signature has been signed by the remote host.
 */
765
function xmldsig_envelope_strip(&$xml) {
766

767
768
769
770
771
772
    $signature      = base64_decode($xml->Signature->SignatureValue);
    $payload        = base64_decode($xml->object);
    $wwwroot        = (string)$xml->wwwroot;
    $timestamp      = $xml->timestamp;
    $peer           = get_peer($wwwroot);

773

774
775
776
777
778
779
780
781
782
    // Does the signature match the data and the public cert?
    $signature_verified = openssl_verify($payload, $signature, $peer->certificate);

    if ($signature_verified == 1) {
        // Parse the XML
        try {
            $xml = new SimpleXMLElement($payload);
            return $payload;
        } catch (Exception $e) {
Donal McMullan's avatar
Donal McMullan committed
783
            throw new MaharaException('Signed payload is not a valid XML document', 6007);
784
785
        }
    }
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
    else if ($signature_verified == 0) {
        // Maybe the remote host is using a new key?
        //$new_public_key = get_public_key($wwwroot, $peer->application->name);
        // Make a dummy request so we'll be given a new key
        log_info("Signature verification for message from $wwwroot failed, checking to see if they have a new signature for us");
        require_once(get_config('docroot') . 'api/xmlrpc/client.php');
        $client = new Client();
        $client->set_method('system/listServices')
               ->send($wwwroot);

        // Now use the new key and re-try verification
        $peer = get_peer($wwwroot, false);
        $signature_verified = openssl_verify($payload, $signature, $peer->certificate);
        if ($signature_verified == 1) {
            log_info("Succefully retrieved a new key for $wwwroot");
            // Parse the XML
            try {
                $xml = new SimpleXMLElement($payload);
                return $payload;
            } catch (Exception $e) {
                throw new MaharaException('Signed payload is not a valid XML document', 6007);
            }
        }
    }

    throw new MaharaException('An error occurred while trying to verify your message signature', 6004);
812
813
}

814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/**
 * Encrypt a message and return it in an XML-Encrypted document
 *
 * This function can encrypt any content, but it was written to provide a system
 * of encrypting XML-RPC request and response messages. The message does not 
 * need to be text - binary data should work.
 * 
 * Asymmetric keys can encrypt only small chunks of data. Usually 1023 or 2047 
 * characters, depending on the key size. So - we generate a symmetric key and 
 * use the asymmetric key to secure it for transport with the data.
 *
 * We generate a symmetric key
 * We encrypt the symmetric key with the public key of the remote host
 * We encrypt our content with the symmetric key
 * We base64 the key & message data.
 * We identify our wwwroot - this must match our certificate's CN
 *
 * Normally, the XML-RPC document will be parceled inside an XML-SIG envelope.
 * We parcel the XML-SIG document inside an XML-ENC envelope.
 *
 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
 * site
 *
 * @param  string   $message              The data you want to sign
 * @param  string   $remote_certificate   Peer's certificate in PEM format
 * @return string                         An XML-ENC document
 */
function xmlenc_envelope($message, $remote_certificate) {

    // Generate a key resource from the remote_certificate text string
    $publickey = openssl_get_publickey($remote_certificate);

    if ( gettype($publickey) != 'resource' ) {
        // Remote certificate is faulty.
Donal McMullan's avatar
Donal McMullan committed
848
        throw new MaharaException('Could not generate public key resource from certificate', 1);
849
850
851
    }

    // Initialize vars
852
    $wwwroot = dropslash(get_config('wwwroot'));
853
854
855
856
857
858
859
    $encryptedstring = '';
    $symmetric_keys = array();

    //      passed by ref ->      &$encryptedstring &$symmetric_keys
    $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey));
    $message = base64_encode($encryptedstring);
    $symmetrickey = base64_encode(array_pop($symmetric_keys));
860
    $zed = 'nothing';
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887

    return <<<EOF
<?xml version="1.0" encoding="iso-8859-1"?>
    <encryptedMessage>
        <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
            <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
                <ds:KeyName>XMLENC</ds:KeyName>
            </ds:KeyInfo>
            <CipherData>
                <CipherValue>$message</CipherValue>
            </CipherData>
        </EncryptedData>
        <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
            <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <ds:KeyName>SSLKEY</ds:KeyName>
            </ds:KeyInfo>
            <CipherData>
                <CipherValue>$symmetrickey</CipherValue>
            </CipherData>
            <ReferenceList>
                <DataReference URI="#ED"/>
            </ReferenceList>
            <CarriedKeyName>XMLENC</CarriedKeyName>
        </EncryptedKey>
888
        <wwwroot>{$wwwroot}</wwwroot>
889
        <X1>$zed</X1>
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
    </encryptedMessage>
EOF;
}

/**
 * Sign a message and return it in an XML-Signature document
 *
 * This function can sign any content, but it was written to provide a system of
 * signing XML-RPC request and response messages. The message will be base64
 * encoded, so it does not need to be text.
 *
 * We compute the SHA1 digest of the message.
 * We compute a signature on that digest with our private key.
 * We link to the public key that can be used to verify our signature.
 * We base64 the message data.
 * We identify our wwwroot - this must match our certificate's CN
 *
 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
 * signature of that document using the local private key. This signature will
 * uniquely identify the RPC document as having come from this server.
 *
 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
 * site
 *
 * @param  string   $message              The data you want to sign
 * @return string                         An XML-DSig document
 */
function xmldsig_envelope($message) {
919

920
    $openssl = OpenSslRepo::singleton();
921
    $wwwroot = dropslash(get_config('wwwroot'));
922
    $digest = sha1($message);
923

924
    $sig = base64_encode($openssl->sign_message($message));
925
926
    $message = base64_encode($message);
    $time = time();
927
    // TODO: Provide RESTful access to our public key as per KeyInfo element
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942

return <<<EOF
<?xml version="1.0" encoding="iso-8859-1"?>
    <signedMessage>
        <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
                <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
                <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>
                <Reference URI="#XMLRPC-MSG">
                    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                    <DigestValue>$digest</DigestValue>
                </Reference>
            </SignedInfo>
            <SignatureValue>$sig</SignatureValue>
            <KeyInfo>
943
                <RetrievalMethod URI="{$wwwroot}/api/xmlrpc/publickey.php"/>
944
945
946
            </KeyInfo>
        </Signature>
        <object ID="XMLRPC-MSG">$message</object>
947
        <wwwroot>{$wwwroot}</wwwroot>
948
949
950
951
952
953
        <timestamp>$time</timestamp>
    </signedMessage>
EOF;

}

954
955
956
/**
 * Good candidate to be a singleton
 */
957
class OpenSslRepo {
958
959
960

    private $keypair = array();

961
962
963
964
965
966
967
968
    /**
     * Sign a message with our private key so that peers can verify that it came
     * from us.
     *
     * @param  string   $message
     * @return string
     * @access public
     */
969
970
971
972
973
    public function sign_message($message) {
        $signature = '';
        $bool      = openssl_sign($message, $signature, $this->keypair['privatekey']);
        return $signature;
    }
974

975
976
977
978
979
980
981
982
983
    /**
     * Decrypt some data using our private key and an auxiliary symmetric key. 
     * The symmetric key encrypted the data, and then was itself encrypted with
     * our public key.
     * This is because asymmetric keys can only safely be used to encrypt 
     * relatively short messages.
     *
     * @param string   $data
     * @param string   $key
984
985
986
     * @param bool     $oldkeyok If true, we will simply return the data rather 
     *                           than complaining about the key being old (if 
     *                           we could decrypt it with an older key)
987
988
989
     * @return string
     * @access public
     */
990
    public function openssl_open($data, $key, $oldkeyok=false) {
991
992
993
994
995
996
997
        $payload = '';
        $isOpen = openssl_open($data, $payload, $key, $this->keypair['privatekey']);

        if (!empty($isOpen)) {
            return $payload;
        } else {
            // Decryption failed... let's try our archived keys
998
            $openssl_history = $this->get_history();
999
1000
1001
1002
1003
            foreach($openssl_history as $keyset) {
                $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
                $isOpen      = openssl_open($data, $payload, $key, $keyresource);
                if ($isOpen) {
                    // It's an older code, sir, but it checks out
1004
1005
1006
1007
1008
1009
1010
                    if ($oldkeyok) {
                        return $payload;
                    }
                    else {
                        // We notify the remote host that the key has changed
                        throw new CryptException($this->keypair['certificate'], 7025);
                    }
1011
1012
1013
                }
            }
        }
1014
        throw new CryptException('We know nothing about the key used to encrypt this message', 7025);
1015
1016
    }

1017
    /**
1018
     * Singleton function keeps us from generating multiple instances of this
1019
1020
1021
1022
1023
     * class
     *
     * @return object   The class instance
     * @access public
     */
1024
1025
1026
1027
1028
    public static function singleton() {
        //single instance
        static $instance;

        //if we don't have the single instance, create one
1029
        if (!isset($instance)) {
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
            $instance = new OpenSslRepo();
        }
        return($instance);
    }

    /**
     * This is a singleton - don't try to create an instance by doing:
     * $openssl = new OpenSslRepo();
     * Instead, use:
     * $openssl = OpenSslRepo::singleton();
     * 
     */
    private function __construct() {
1043
        if (empty($this->keypair)) {
1044
            $this->get_keypair();
1045
	    $this->calculate_fingerprints();
1046
1047
1048
            $this->keypair['privatekey'] = openssl_pkey_get_private($this->keypair['keypair_PEM']);
            $this->keypair['publickey']  = openssl_pkey_get_public($this->keypair['certificate']);
        }
1049
        return $this;
1050
1051
    }

1052
1053
1054
1055
1056
1057
1058
    /**
     * Utility function to get old SSL keys from the config table, or create a 
     * blank record if none exists.
     *
     * @return array    Array of keypair hashes
     * @access private
     */
1059
1060
    private function get_history() {
        $openssl_history = get_field('config', 'value', 'field', 'openssl_history');
1061
        if (empty($openssl_history)) {
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
            $openssl_history = array();
            $record = new stdClass();
            $record->field = 'openssl_history';
            $record->value = serialize($openssl_history);
            insert_record('config', $record);
        } else {
            $openssl_history = unserialize($openssl_history);
        }
        return $openssl_history;
    }

1073
1074
1075
1076
1077
1078
1079
1080
    /**
     * Utility function to stash old SSL keys in the config table. It will retain
     * a max of 'openssl_generations' which is itself a value in config.
     *
     * @param  array    Array of keypair hashes
     * @return bool
     * @access private
     */
1081
1082
    private function save_history($openssl_history) {
        $openssl_generations = get_field('config', 'value', 'field', 'openssl_generations');
1083
        if (empty($openssl_generations)) {
1084
1085
1086
            set_config('openssl_generations', 6);
            $openssl_generations = 6;
        }
1087
        if (count($openssl_history) > $openssl_generations) {
1088
1089
1090
1091
1092
            $openssl_history = array_slice($openssl_history, 0, $openssl_generations);
        }
        return set_config('openssl_history', serialize($openssl_history));
    }

1093
1094
1095
1096
1097
1098
1099
1100
1101
    /**
     * The get Overloader will let you pull out the 'certificate' and 'expires'
     * values
     *
     * @param  string    Name of the value you want
     * @return mixed     The value of the thing you asked for or null (if it 
     *                   doesn't exist or is private)
     * @access public
     */
1102
    public function __get($name) {
1103
1104
        if ('certificate' === $name) return $this->keypair['certificate'];
        if ('expires' === $name)     return $this->keypair['expires'];
1105
1106
        if ('sha1_fingerprint' === $name) return $this->keypair['sha1_fingerprint'];
        if ('md5_fingerprint' === $name ) return $this->keypair['md5_fingerprint'];
1107
1108
        return null;
    }
1109

1110
1111
1112
1113
1114
1115
1116
1117
    /**
     * Get the keypair. If it doesn't exist, create it. If it's out of date, 
     * archive it and create a fresh pair.
     *
     * @param  bool      True if you want to force fresh keys to be generated
     * @return bool     
     * @access private
     */
1118
    public function get_keypair($regenerate = null) {
1119
1120
1121
        $this->keypair = array();
        $records       = null;
        
1122
1123
1124
1125
1126
        if ($records = get_records_select_menu('config', "field IN ('openssl_keypair', 'openssl_keypair_expires')", 'field', 'field, value')) {
            list($this->keypair['certificate'], $this->keypair['keypair_PEM']) = explode('@@@@@@@@', $records['openssl_keypair']);
            $this->keypair['expires'] = $records['openssl_keypair_expires'];
            if (empty($regenerate) && $this->keypair['expires'] > time()) {
                return true;
1127
1128
1129
            }
        }

1130
1131
1132
1133
1134
        // Save out the old key
        $openssl_history = $this->get_history();
        array_unshift($openssl_history, $this->keypair);
        $this->save_history($openssl_history);

1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
        // Initialize a new set of SSL keys
        $this->keypair = array();
        $this->generate_keypair();

        // A record for the keys
        $keyrecord = new stdClass();
        $keyrecord->field = 'openssl_keypair';
        $keyrecord->value = implode('@@@@@@@@', $this->keypair);

        // A convenience record for the keys' expire time (UNIX timestamp)
        $expiresrecord        = new stdClass();
        $expiresrecord->field = 'openssl_keypair_expires';

        // Getting the expire timestamp is convoluted, but required:
        $credentials = openssl_x509_parse($this->keypair['certificate']);
1150
        if (is_array($credentials) && isset($credentials['validTo_time_t'])) {
1151
1152
1153
1154
            $expiresrecord->value = $credentials['validTo_time_t'];
            $this->keypair['expires'] = $credentials['validTo_time_t'];
        }

1155
        if (empty($records)) {
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
            db_begin();
            insert_record('config', $keyrecord);
            insert_record('config', $expiresrecord);
            db_commit();
        }
        else {
            db_begin();
            update_record('config', $keyrecord,     array('field' => 'openssl_keypair'));
            update_record('config', $expiresrecord, array('field' => 'openssl_keypair_expires'));
            db_commit();
1166
        }
1167
        log_info("New public key has been generated. It expires " . date('Y/m/d h:i:s', $credentials['validTo_time_t']));
1168
        return true;
1169
1170
    }

1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
    /**
     * Generate public/private keys and store in the config table
     *
     * Use the distinguished name provided to create a CSR, and then sign that CSR
     * with the same credentials. Store the keypair you create in the config table.
     * If a distinguished name is not provided, create one using the fullname of
     * 'the course with ID 1' as your organization name, and your hostname (as
     * detailed in $CFG->wwwroot).
     *
     * @param   array  $dn  The distinguished name of the server
     * @return  string      The signature over that text
     */
1183
    private function generate_keypair() {
1184
        $host = get_hostname_from_uri(get_config('wwwroot'));
1185
1186
1187
1188
1189
1190
1191
1192
1193

        $organization = get_config('sitename');
        $email        = get_config('noreplyaddress');
        $country      = get_config('country');
        $province     = get_config('province');
        $locality     = get_config('locality');

        //TODO: Create additional fields on site setup and read those from 
        //      config. Then remove the next 3 linez
1194
1195
1196
        if (empty($country))  $country  = 'NZ';
        if (empty($province)) $province = 'Wellington';
        if (empty($locality)) $locality = 'Te Aro';
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

        $dn = array(
           "countryName" => $country,
           "stateOrProvinceName" => $province,
           "localityName" => $locality,
           "organizationName" => $organization,
           "organizationalUnitName" => 'Mahara',
           "commonName" => get_config('wwwroot'),
           "emailAddress" => $email
        );

        // ensure we remove trailing slashes
        $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);

1211
        if (!$new_key = openssl_pkey_new()) {
1212
            throw new ConfigException(get_string('errorcouldnotgeneratenewsslkey', 'auth'));
1213
1214
1215
1216
1217
1218
        }

        if (!$csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048))) {
            // This behaviour has been observed once before, on an ubuntu hardy box. 
            // The php5-openssl package was installed but somehow openssl 
            // wasn't.
1219
            throw new ConfigException(get_string('errorcouldnotgeneratenewsslkey', 'auth'));
1220
        }
1221
        $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, 365 /*days*/);
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
        unset($csr_rsc); // Free up the resource

        // We export our self-signed certificate to a string.
        openssl_x509_export($selfSignedCert, $this->keypair['certificate']);
        openssl_x509_free($selfSignedCert);

        // Export your public/private key pair as a PEM encoded string. You
        // can protect it with an optional passphrase if you wish.
        $export = openssl_pkey_export($new_key, $this->keypair['keypair_PEM'] /* , $passphrase */);
        openssl_pkey_free($new_key);
        unset($new_key); // Free up the resource

1234
1235
        // Calculate fingerprints
        $this->calculate_fingerprints();
1236

1237
1238
        return $this;
    }
1239
1240
1241
1242
1243
1244


    /**
     * Calculates the SHA1 and MD5 fingerprints of the certificate in DER format
     * It does the same as the fingerprint commandline option in x509
     * command. For example:
1245
     *
1246
1247
1248
     *        $ openssl x509 -in cert_file -fingerprint -sha1
     *        $ openssl x509 -in cert_file -fingerprint -md5
     */
1249

1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
    private function calculate_fingerprints () {

        // Convert the certificate to DER and calculate the digest

        $pem_cert = $this->keypair['certificate'];

        $from_pos = strpos($pem_cert, "-----BEGIN CERTIFICATE-----");
        if ( $from_pos === false ) {
            throw new CryptException("Certificate not in PEM format");
        }
        $from_pos = $from_pos + 27;

        $to_pos = strpos($pem_cert, "-----END CERTIFICATE-----");
        if ( $to_pos === false ) {
            throw new CryptException("Certificate not in PEM format");
        }

        $der_cert = base64_decode(substr($pem_cert, $from_pos, $to_pos - $from_pos));
        if ( $der_cert === FALSE ) {
            throw new CryptException("Certificate not in PEM format");
        }

        $_sha1_fingerprint = sha1($der_cert);
1273
        if ( $_sha1_fingerprint === FALSE ) {
1274
1275
1276
            throw new CryptException("Error calculating sha1 fingerprint");
        }
        $_md5_fingerprint = md5($der_cert);
1277
        if ( $_md5_fingerprint === FALSE ) {
1278
1279
1280
            throw new CryptException("Error calculating md5 fingerprint");
        }

1281
        unset($der_cert);
1282

1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
        $_sha1_fingerprint = strtoupper($_sha1_fingerprint);
        $_md5_fingerprint  = strtoupper($_md5_fingerprint);

        $sha1_fingerprint = $_sha1_fingerprint[0];
        for ( $i = 1, $to = strlen($_sha1_fingerprint); $i < $to ; $i++ ) {
            if ( $i % 2 == 0 ) {
                $sha1_fingerprint .= ":" . $_sha1_fingerprint[$i];
            } else {
                $sha1_fingerprint .= $_sha1_fingerprint[$i];
            }
        }
1294
1295
1296

        $md5_fingerprint = $_md5_fingerprint[0];
        for ( $i = 1, $to = strlen($_md5_fingerprint); $i < $to ; $i++ ) {
1297
1298
1299
1300
1301
            if ( $i % 2 == 0 ) {
                $md5_fingerprint .= ":" . $_md5_fingerprint[$i];
            } else {
                $md5_fingerprint .= $_md5_fingerprint[$i];
            }