"MDL-8642, setting of auto scrolling"
[moodle-linuxchix.git] / mnet / lib.php
blobbf3e1cb0d6f04adb7f1303d6308cea3181706d89
1 <?php // $Id$
2 /**
3 * Library functions for mnet
5 * @author Donal McMullan donal@catalyst.net.nz
6 * @version 0.0.1
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
8 * @package mnet
9 */
10 require_once $CFG->dirroot.'/mnet/xmlrpc/xmlparser.php';
11 require_once $CFG->dirroot.'/mnet/peer.php';
12 require_once $CFG->dirroot.'/mnet/environment.php';
14 /// CONSTANTS ///////////////////////////////////////////////////////////
16 define('RPC_OK', 0);
17 define('RPC_NOSUCHFILE', 1);
18 define('RPC_NOSUCHCLASS', 2);
19 define('RPC_NOSUCHFUNCTION', 3);
20 define('RPC_FORBIDDENFUNCTION', 4);
21 define('RPC_NOSUCHMETHOD', 5);
22 define('RPC_FORBIDDENMETHOD', 6);
24 $MNET = new mnet_environment();
25 $MNET->init();
27 /**
28 * Strip extraneous detail from a URL or URI and return the hostname
30 * @param string $uri The URI of a file on the remote computer, optionally
31 * including its http:// prefix like
32 * http://www.example.com/index.html
33 * @return string Just the hostname
35 function mnet_get_hostname_from_uri($uri = null) {
36 $count = preg_match("@^(?:http[s]?://)?([A-Z0-9\-\.]+).*@i", $uri, $matches);
37 if ($count > 0) return $matches[1];
38 return false;
41 /**
42 * Get the remote machine's SSL Cert
44 * @param string $uri The URI of a file on the remote computer, including
45 * its http:// or https:// prefix
46 * @return string A PEM formatted SSL Certificate.
48 function mnet_get_public_key($uri, $application=null) {
49 global $CFG, $MNET;
50 // The key may be cached in the mnet_set_public_key function...
51 // check this first
52 $key = mnet_set_public_key($uri);
53 if ($key != false) {
54 return $key;
57 if (empty($application)) {
58 $application = get_record('mnet_application', 'name', 'moodle');
61 $rq = xmlrpc_encode_request('system/keyswap', array($CFG->wwwroot, $MNET->public_key, $application->name), array("encoding" => "utf-8"));
62 $ch = curl_init($uri . $application->xmlrpc_server_url);
64 curl_setopt($ch, CURLOPT_TIMEOUT, 60);
65 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
66 curl_setopt($ch, CURLOPT_POST, true);
67 curl_setopt($ch, CURLOPT_USERAGENT, 'Moodle');
68 curl_setopt($ch, CURLOPT_POSTFIELDS, $rq);
69 curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml charset=UTF-8"));
70 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
71 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
73 $res = xmlrpc_decode(curl_exec($ch));
74 curl_close($ch);
76 if (!is_array($res)) { // ! error
77 $public_certificate = $res;
78 $credentials=array();
79 if (strlen(trim($public_certificate))) {
80 $credentials = openssl_x509_parse($public_certificate);
81 $host = $credentials['subject']['CN'];
82 if (strpos($uri, $host) !== false) {
83 mnet_set_public_key($uri, $public_certificate);
84 return $public_certificate;
88 return false;
91 /**
92 * Store a URI's public key in a static variable, or retrieve the key for a URI
94 * @param string $uri The URI of a file on the remote computer, including its
95 * https:// prefix
96 * @param mixed $key A public key to store in the array OR null. If the key
97 * is null, the function will return the previously stored
98 * key for the supplied URI, should it exist.
99 * @return mixed A public key OR true/false.
101 function mnet_set_public_key($uri, $key = null) {
102 static $keyarray = array();
103 if (isset($keyarray[$uri]) && empty($key)) {
104 return $keyarray[$uri];
105 } elseif (!empty($key)) {
106 $keyarray[$uri] = $key;
107 return true;
109 return false;
113 * Sign a message and return it in an XML-Signature document
115 * This function can sign any content, but it was written to provide a system of
116 * signing XML-RPC request and response messages. The message will be base64
117 * encoded, so it does not need to be text.
119 * We compute the SHA1 digest of the message.
120 * We compute a signature on that digest with our private key.
121 * We link to the public key that can be used to verify our signature.
122 * We base64 the message data.
123 * We identify our wwwroot - this must match our certificate's CN
125 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
126 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
127 * signature of that document using the local private key. This signature will
128 * uniquely identify the RPC document as having come from this server.
130 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
131 * site
133 * @param string $message The data you want to sign
134 * @param resource $privatekey The private key to sign the response with
135 * @return string An XML-DSig document
137 function mnet_sign_message($message, $privatekey = null) {
138 global $CFG, $MNET;
139 $digest = sha1($message);
141 // If the user hasn't supplied a private key (for example, one of our older,
142 // expired private keys, we get the current default private key and use that.
143 if ($privatekey == null) {
144 $privatekey = $MNET->get_private_key();
147 // The '$sig' value below is returned by reference.
148 // We initialize it first to stop my IDE from complaining.
149 $sig = '';
150 $bool = openssl_sign($message, $sig, $privatekey); // TODO: On failure?
152 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
153 <signedMessage>
154 <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
155 <SignedInfo>
156 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
157 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>
158 <Reference URI="#XMLRPC-MSG">
159 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
160 <DigestValue>'.$digest.'</DigestValue>
161 </Reference>
162 </SignedInfo>
163 <SignatureValue>'.base64_encode($sig).'</SignatureValue>
164 <KeyInfo>
165 <RetrievalMethod URI="'.$CFG->wwwroot.'/mnet/publickey.php"/>
166 </KeyInfo>
167 </Signature>
168 <object ID="XMLRPC-MSG">'.base64_encode($message).'</object>
169 <wwwroot>'.$MNET->wwwroot.'</wwwroot>
170 <timestamp>'.time().'</timestamp>
171 </signedMessage>';
172 return $message;
176 * Encrypt a message and return it in an XML-Encrypted document
178 * This function can encrypt any content, but it was written to provide a system
179 * of encrypting XML-RPC request and response messages. The message will be
180 * base64 encoded, so it does not need to be text - binary data should work.
182 * We compute the SHA1 digest of the message.
183 * We compute a signature on that digest with our private key.
184 * We link to the public key that can be used to verify our signature.
185 * We base64 the message data.
186 * We identify our wwwroot - this must match our certificate's CN
188 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
189 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
190 * signature of that document using the local private key. This signature will
191 * uniquely identify the RPC document as having come from this server.
193 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
194 * site
196 * @param string $message The data you want to sign
197 * @param string $remote_certificate Peer's certificate in PEM format
198 * @return string An XML-ENC document
200 function mnet_encrypt_message($message, $remote_certificate) {
201 global $MNET;
203 // Generate a key resource from the remote_certificate text string
204 $publickey = openssl_get_publickey($remote_certificate);
206 if ( gettype($publickey) != 'resource' ) {
207 // Remote certificate is faulty.
208 return false;
211 // Initialize vars
212 $encryptedstring = '';
213 $symmetric_keys = array();
215 // passed by ref -> &$encryptedstring &$symmetric_keys
216 $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey));
217 $message = $encryptedstring;
218 $symmetrickey = array_pop($symmetric_keys);
220 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
221 <encryptedMessage>
222 <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
223 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
224 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
225 <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
226 <ds:KeyName>XMLENC</ds:KeyName>
227 </ds:KeyInfo>
228 <CipherData>
229 <CipherValue>'.base64_encode($message).'</CipherValue>
230 </CipherData>
231 </EncryptedData>
232 <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
233 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
234 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
235 <ds:KeyName>SSLKEY</ds:KeyName>
236 </ds:KeyInfo>
237 <CipherData>
238 <CipherValue>'.base64_encode($symmetrickey).'</CipherValue>
239 </CipherData>
240 <ReferenceList>
241 <DataReference URI="#ED"/>
242 </ReferenceList>
243 <CarriedKeyName>XMLENC</CarriedKeyName>
244 </EncryptedKey>
245 <wwwroot>'.$MNET->wwwroot.'</wwwroot>
246 </encryptedMessage>';
247 return $message;
251 * Get your SSL keys from the database, or create them (if they don't exist yet)
253 * Get your SSL keys from the database, or (if they don't exist yet) call
254 * mnet_generate_keypair to create them
256 * @param string $string The text you want to sign
257 * @return string The signature over that text
259 function mnet_get_keypair() {
260 global $CFG;
261 static $keypair = null;
262 if (!is_null($keypair)) return $keypair;
263 if ($result = get_field('config_plugins', 'value', 'plugin', 'mnet', 'name', 'openssl')) {
264 list($keypair['certificate'], $keypair['keypair_PEM']) = explode('@@@@@@@@', $result);
265 $keypair['privatekey'] = openssl_pkey_get_private($keypair['keypair_PEM']);
266 $keypair['publickey'] = openssl_pkey_get_public($keypair['certificate']);
267 return $keypair;
268 } else {
269 $keypair = mnet_generate_keypair();
270 return $keypair;
275 * Generate public/private keys and store in the config table
277 * Use the distinguished name provided to create a CSR, and then sign that CSR
278 * with the same credentials. Store the keypair you create in the config table.
279 * If a distinguished name is not provided, create one using the fullname of
280 * 'the course with ID 1' as your organization name, and your hostname (as
281 * detailed in $CFG->wwwroot).
283 * @param array $dn The distinguished name of the server
284 * @return string The signature over that text
286 function mnet_generate_keypair($dn = null, $days=28) {
287 global $CFG, $USER;
288 $host = strtolower($CFG->wwwroot);
289 $host = ereg_replace("^http(s)?://",'',$host);
290 $break = strpos($host.'/' , '/');
291 $host = substr($host, 0, $break);
293 if ($result = get_record_select('course'," id ='".SITEID."' ")) {
294 $organization = $result->fullname;
295 } else {
296 $organization = 'None';
299 $keypair = array();
301 $country = 'NZ';
302 $province = 'Wellington';
303 $locality = 'Wellington';
304 $email = $CFG->noreplyaddress;
306 if(!empty($USER->country)) {
307 $country = $USER->country;
309 if(!empty($USER->city)) {
310 $province = $USER->city;
311 $locality = $USER->city;
313 if(!empty($USER->email)) {
314 $email = $USER->email;
317 if (is_null($dn)) {
318 $dn = array(
319 "countryName" => $country,
320 "stateOrProvinceName" => $province,
321 "localityName" => $locality,
322 "organizationName" => $organization,
323 "organizationalUnitName" => 'Moodle',
324 "commonName" => $CFG->wwwroot,
325 "emailAddress" => $email
329 // ensure we remove trailing slashes
330 $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
332 $new_key = openssl_pkey_new();
333 $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048));
334 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
335 unset($csr_rsc); // Free up the resource
337 // We export our self-signed certificate to a string.
338 openssl_x509_export($selfSignedCert, $keypair['certificate']);
339 openssl_x509_free($selfSignedCert);
341 // Export your public/private key pair as a PEM encoded string. You
342 // can protect it with an optional passphrase if you wish.
343 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'] /* , $passphrase */);
344 openssl_pkey_free($new_key);
345 unset($new_key); // Free up the resource
347 return $keypair;
351 * Check that an IP address falls within the given network/mask
352 * ok for export
354 * @param string $address Dotted quad
355 * @param string $network Dotted quad
356 * @param string $mask A number, e.g. 16, 24, 32
357 * @return bool
359 function ip_in_range($address, $network, $mask) {
360 $lnetwork = ip2long($network);
361 $laddress = ip2long($address);
363 $binnet = str_pad( decbin($lnetwork),32,"0","STR_PAD_LEFT" );
364 $firstpart = substr($binnet,0,$mask);
366 $binip = str_pad( decbin($laddress),32,"0","STR_PAD_LEFT" );
367 $firstip = substr($binip,0,$mask);
368 return(strcmp($firstpart,$firstip)==0);
372 * Check that a given function (or method) in an include file has been designated
373 * ok for export
375 * @param string $includefile The path to the include file
376 * @param string $functionname The name of the function (or method) to
377 * execute
378 * @param mixed $class A class name, or false if we're just testing
379 * a function
380 * @return int Zero (RPC_OK) if all ok - appropriate
381 * constant otherwise
383 function mnet_permit_rpc_call($includefile, $functionname, $class=false) {
384 global $CFG, $MNET_REMOTE_CLIENT;
386 if (file_exists($CFG->dirroot . $includefile)) {
387 include_once $CFG->dirroot . $includefile;
388 // $callprefix matches the rpc convention
389 // of not having a leading slash
390 $callprefix = preg_replace('!^/!', '', $includefile);
391 } else {
392 return RPC_NOSUCHFILE;
395 if ($functionname != clean_param($functionname, PARAM_PATH)) {
396 // Under attack?
397 // Todo: Should really return a much more BROKEN! response
398 return RPC_FORBIDDENMETHOD;
401 $id_list = $MNET_REMOTE_CLIENT->id;
402 if (!empty($CFG->mnet_all_hosts_id)) {
403 $id_list .= ', '.$CFG->mnet_all_hosts_id;
406 // TODO: change to left-join so we can disambiguate:
407 // 1. method doesn't exist
408 // 2. method exists but is prohibited
409 $sql = "
410 SELECT
411 count(r.id)
412 FROM
413 {$CFG->prefix}mnet_host2service h2s,
414 {$CFG->prefix}mnet_service2rpc s2r,
415 {$CFG->prefix}mnet_rpc r
416 WHERE
417 h2s.serviceid = s2r.serviceid AND
418 s2r.rpcid = r.id AND
419 r.xmlrpc_path = '$callprefix/$functionname' AND
420 h2s.hostid in ($id_list) AND
421 h2s.publish = '1'";
423 $permissionobj = record_exists_sql($sql);
425 if ($permissionobj === false && 'dangerous' != $CFG->mnet_dispatcher_mode) {
426 return RPC_FORBIDDENMETHOD;
429 // WE'RE LOOKING AT A CLASS/METHOD
430 if (false != $class) {
431 if (!class_exists($class)) {
432 // Generate error response - unable to locate class
433 return RPC_NOSUCHCLASS;
436 $object = new $class();
438 if (!method_exists($object, $functionname)) {
439 // Generate error response - unable to locate method
440 return RPC_NOSUCHMETHOD;
443 if (!method_exists($object, 'mnet_publishes')) {
444 // Generate error response - the class doesn't publish
445 // *any* methods, because it doesn't have an mnet_publishes
446 // method
447 return RPC_FORBIDDENMETHOD;
450 // Get the list of published services - initialise method array
451 $servicelist = $object->mnet_publishes();
452 $methodapproved = false;
454 // If the method is in the list of approved methods, set the
455 // methodapproved flag to true and break
456 foreach($servicelist as $service) {
457 if (in_array($functionname, $service['methods'])) {
458 $methodapproved = true;
459 break;
463 if (!$methodapproved) {
464 return RPC_FORBIDDENMETHOD;
467 // Stash the object so we can call the method on it later
468 $MNET_REMOTE_CLIENT->object_to_call($object);
469 // WE'RE LOOKING AT A FUNCTION
470 } else {
471 if (!function_exists($functionname)) {
472 // Generate error response - unable to locate function
473 return RPC_NOSUCHFUNCTION;
478 return RPC_OK;
481 function mnet_update_sso_access_control($username, $mnet_host_id, $accessctrl) {
482 $mnethost = get_record('mnet_host', 'id', $mnet_host_id);
483 if ($aclrecord = get_record('mnet_sso_access_control', 'username', $username, 'mnet_host_id', $mnet_host_id)) {
484 // update
485 $aclrecord->accessctrl = $accessctrl;
486 if (update_record('mnet_sso_access_control', $aclrecord)) {
487 add_to_log(SITEID, 'admin/mnet', 'update', 'admin/mnet/access_control.php',
488 "SSO ACL: $accessctrl user '$username' from {$mnethost->name}");
489 } else {
490 print_error('failedaclwrite', 'mnet', '', $username);
491 return false;
493 } else {
494 // insert
495 $aclrecord->username = $username;
496 $aclrecord->accessctrl = $accessctrl;
497 $aclrecord->mnet_host_id = $mnet_host_id;
498 if ($id = insert_record('mnet_sso_access_control', $aclrecord)) {
499 add_to_log(SITEID, 'admin/mnet', 'add', 'admin/mnet/access_control.php',
500 "SSO ACL: $accessctrl user '$username' from {$mnethost->name}");
501 } else {
502 print_error('failedaclwrite', 'mnet', '', $username);
503 return false;
506 return true;