Follow-up fix for Bug MDL-8617 "Implement groupings & course modules..." internal...
[moodle-pu.git] / mnet / lib.php
blobff5aca1fb260c90e087e46a607fe590f017e080a
1 <?php
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) {
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 $rq = xmlrpc_encode_request('system/keyswap', array($CFG->wwwroot, $MNET->public_key), array("encoding" => "utf-8"));
58 $ch = curl_init($uri.'/mnet/xmlrpc/server.php');
60 curl_setopt($ch, CURLOPT_TIMEOUT, 60);
61 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
62 curl_setopt($ch, CURLOPT_POST, true);
63 curl_setopt($ch, CURLOPT_USERAGENT, 'Moodle');
64 curl_setopt($ch, CURLOPT_POSTFIELDS, $rq);
65 curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml charset=UTF-8"));
67 $res = xmlrpc_decode(curl_exec($ch));
68 curl_close($ch);
70 if (!is_array($res)) { // ! error
71 $public_certificate = $res;
72 $credentials=array();
73 if (strlen(trim($public_certificate))) {
74 $credentials = openssl_x509_parse($public_certificate);
75 $host = $credentials['subject']['CN'];
76 if (strpos($uri, $host) !== false) {
77 mnet_set_public_key($uri, $public_certificate);
78 return $public_certificate;
82 return false;
85 /**
86 * Store a URI's public key in a static variable, or retrieve the key for a URI
88 * @param string $uri The URI of a file on the remote computer, including its
89 * https:// prefix
90 * @param mixed $key A public key to store in the array OR null. If the key
91 * is null, the function will return the previously stored
92 * key for the supplied URI, should it exist.
93 * @return mixed A public key OR true/false.
95 function mnet_set_public_key($uri, $key = null) {
96 static $keyarray = array();
97 if (isset($keyarray[$uri]) && empty($key)) {
98 return $keyarray[$uri];
99 } elseif (!empty($key)) {
100 $keyarray[$uri] = $key;
101 return true;
103 return false;
107 * Sign a message and return it in an XML-Signature document
109 * This function can sign any content, but it was written to provide a system of
110 * signing XML-RPC request and response messages. The message will be base64
111 * encoded, so it does not need to be text.
113 * We compute the SHA1 digest of the message.
114 * We compute a signature on that digest with our private key.
115 * We link to the public key that can be used to verify our signature.
116 * We base64 the message data.
117 * We identify our wwwroot - this must match our certificate's CN
119 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
120 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
121 * signature of that document using the local private key. This signature will
122 * uniquely identify the RPC document as having come from this server.
124 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
125 * site
127 * @param string $message The data you want to sign
128 * @return string An XML-DSig document
130 function mnet_sign_message($message) {
131 global $CFG, $MNET;
132 $digest = sha1($message);
133 $sig = $MNET->sign_message($message);
135 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
136 <signedMessage>
137 <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
138 <SignedInfo>
139 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
140 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>
141 <Reference URI="#XMLRPC-MSG">
142 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
143 <DigestValue>'.$digest.'</DigestValue>
144 </Reference>
145 </SignedInfo>
146 <SignatureValue>'.base64_encode($sig).'</SignatureValue>
147 <KeyInfo>
148 <RetrievalMethod URI="'.$CFG->wwwroot.'/mnet/publickey.php"/>
149 </KeyInfo>
150 </Signature>
151 <object ID="XMLRPC-MSG">'.base64_encode($message).'</object>
152 <wwwroot>'.$MNET->wwwroot.'</wwwroot>
153 <timestamp>'.time().'</timestamp>
154 </signedMessage>';
155 return $message;
159 * Encrypt a message and return it in an XML-Encrypted document
161 * This function can encrypt any content, but it was written to provide a system
162 * of encrypting XML-RPC request and response messages. The message will be
163 * base64 encoded, so it does not need to be text - binary data should work.
165 * We compute the SHA1 digest of the message.
166 * We compute a signature on that digest with our private key.
167 * We link to the public key that can be used to verify our signature.
168 * We base64 the message data.
169 * We identify our wwwroot - this must match our certificate's CN
171 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
172 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
173 * signature of that document using the local private key. This signature will
174 * uniquely identify the RPC document as having come from this server.
176 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
177 * site
179 * @param string $message The data you want to sign
180 * @param string $remote_certificate Peer's certificate in PEM format
181 * @return string An XML-ENC document
183 function mnet_encrypt_message($message, $remote_certificate) {
184 global $MNET;
186 // Generate a key resource from the remote_certificate text string
187 $publickey = openssl_get_publickey($remote_certificate);
189 if ( gettype($publickey) != 'resource' ) {
190 // Remote certificate is faulty.
191 return false;
194 // Initialize vars
195 $encryptedstring = '';
196 $symmetric_keys = array();
198 // passed by ref -> &$encryptedstring &$symmetric_keys
199 $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey));
200 $message = $encryptedstring;
201 $symmetrickey = array_pop($symmetric_keys);
203 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
204 <encryptedMessage>
205 <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
206 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
207 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
208 <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
209 <ds:KeyName>XMLENC</ds:KeyName>
210 </ds:KeyInfo>
211 <CipherData>
212 <CipherValue>'.base64_encode($message).'</CipherValue>
213 </CipherData>
214 </EncryptedData>
215 <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
216 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
217 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
218 <ds:KeyName>SSLKEY</ds:KeyName>
219 </ds:KeyInfo>
220 <CipherData>
221 <CipherValue>'.base64_encode($symmetrickey).'</CipherValue>
222 </CipherData>
223 <ReferenceList>
224 <DataReference URI="#ED"/>
225 </ReferenceList>
226 <CarriedKeyName>XMLENC</CarriedKeyName>
227 </EncryptedKey>
228 <wwwroot>'.$MNET->wwwroot.'</wwwroot>
229 </encryptedMessage>';
230 return $message;
234 * Get your SSL keys from the database, or create them (if they don't exist yet)
236 * Get your SSL keys from the database, or (if they don't exist yet) call
237 * mnet_generate_keypair to create them
239 * @param string $string The text you want to sign
240 * @return string The signature over that text
242 function mnet_get_keypair() {
243 global $CFG;
244 static $keypair = null;
245 if (!is_null($keypair)) return $keypair;
246 if ($result = get_field('config_plugins', 'value', 'plugin', 'mnet', 'name', 'openssl')) {
247 $keypair = explode('@@@@@@@@', $keypair);
248 $keypair['privatekey'] = openssl_pkey_get_private($keypair['keypair_PEM']);
249 $keypair['publickey'] = openssl_pkey_get_public($keypair['certificate']);
250 return $keypair;
251 } else {
252 $keypair = mnet_generate_keypair();
253 return $keypair;
258 * Generate public/private keys and store in the config table
260 * Use the distinguished name provided to create a CSR, and then sign that CSR
261 * with the same credentials. Store the keypair you create in the config table.
262 * If a distinguished name is not provided, create one using the fullname of
263 * 'the course with ID 1' as your organization name, and your hostname (as
264 * detailed in $CFG->wwwroot).
266 * @param array $dn The distinguished name of the server
267 * @return string The signature over that text
269 function mnet_generate_keypair($dn = null, $days=28) {
270 global $CFG, $USER;
271 $host = strtolower($CFG->wwwroot);
272 $host = ereg_replace("^http(s)?://",'',$host);
273 $break = strpos($host.'/' , '/');
274 $host = substr($host, 0, $break);
276 if ($result = get_record_select('course'," id ='".SITEID."' ")) {
277 $organization = $result->fullname;
278 } else {
279 $organization = 'None';
282 $keypair = array();
284 $country = 'NZ';
285 $province = 'Wellington';
286 $locality = 'Wellington';
287 $email = $CFG->noreplyaddress;
289 if(!empty($USER->country)) {
290 $country = $USER->country;
292 if(!empty($USER->city)) {
293 $province = $USER->city;
294 $locality = $USER->city;
296 if(!empty($USER->email)) {
297 $email = $USER->email;
300 if (is_null($dn)) {
301 $dn = array(
302 "countryName" => $country,
303 "stateOrProvinceName" => $province,
304 "localityName" => $locality,
305 "organizationName" => $organization,
306 "organizationalUnitName" => 'Moodle',
307 "commonName" => $CFG->wwwroot,
308 "emailAddress" => $email
312 // ensure we remove trailing slashes
313 $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
315 $new_key = openssl_pkey_new();
316 $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048));
317 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
318 unset($csr_rsc); // Free up the resource
320 // We export our self-signed certificate to a string.
321 openssl_x509_export($selfSignedCert, $keypair['certificate']);
322 openssl_x509_free($selfSignedCert);
324 // Export your public/private key pair as a PEM encoded string. You
325 // can protect it with an optional passphrase if you wish.
326 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'] /* , $passphrase */);
327 openssl_pkey_free($new_key);
328 unset($new_key); // Free up the resource
330 return $keypair;
334 * Check that an IP address falls within the given network/mask
335 * ok for export
337 * @param string $address Dotted quad
338 * @param string $network Dotted quad
339 * @param string $mask A number, e.g. 16, 24, 32
340 * @return bool
342 function ip_in_range($address, $network, $mask) {
343 $lnetwork = ip2long($network);
344 $laddress = ip2long($address);
346 $binnet = str_pad( decbin($lnetwork),32,"0","STR_PAD_LEFT" );
347 $firstpart = substr($binnet,0,$mask);
349 $binip = str_pad( decbin($laddress),32,"0","STR_PAD_LEFT" );
350 $firstip = substr($binip,0,$mask);
351 return(strcmp($firstpart,$firstip)==0);
355 * Check that a given function (or method) in an include file has been designated
356 * ok for export
358 * @param string $includefile The path to the include file
359 * @param string $functionname The name of the function (or method) to
360 * execute
361 * @param mixed $class A class name, or false if we're just testing
362 * a function
363 * @return int Zero (RPC_OK) if all ok - appropriate
364 * constant otherwise
366 function mnet_permit_rpc_call($includefile, $functionname, $class=false) {
367 global $CFG, $MNET_REMOTE_CLIENT;
369 if (file_exists($CFG->dirroot . $includefile)) {
370 include_once $CFG->dirroot . $includefile;
371 // $callprefix matches the rpc convention
372 // of not having a leading slash
373 $callprefix = preg_replace('!^/!', '', $includefile);
374 } else {
375 return RPC_NOSUCHFILE;
378 if ($functionname != clean_param($functionname, PARAM_PATH)) {
379 // Under attack?
380 // Todo: Should really return a much more BROKEN! response
381 return RPC_FORBIDDENMETHOD;
384 $id_list = $MNET_REMOTE_CLIENT->id;
385 if (!empty($CFG->mnet_all_hosts_id)) {
386 $id_list .= ', '.$CFG->mnet_all_hosts_id;
389 // TODO: change to left-join so we can disambiguate:
390 // 1. method doesn't exist
391 // 2. method exists but is prohibited
392 $sql = "
393 SELECT
394 count(r.id)
395 FROM
396 {$CFG->prefix}mnet_host2service h2s,
397 {$CFG->prefix}mnet_service2rpc s2r,
398 {$CFG->prefix}mnet_rpc r
399 WHERE
400 h2s.serviceid = s2r.serviceid AND
401 s2r.rpcid = r.id AND
402 r.xmlrpc_path = '$callprefix/$functionname' AND
403 h2s.hostid in ($id_list) AND
404 h2s.publish = '1'";
406 $permissionobj = record_exists_sql($sql);
408 if ($permissionobj === false) {
409 return RPC_FORBIDDENMETHOD;
412 // WE'RE LOOKING AT A CLASS/METHOD
413 if (false != $class) {
414 if (!class_exists($class)) {
415 // Generate error response - unable to locate class
416 return RPC_NOSUCHCLASS;
419 $object = new $class();
421 if (!method_exists($object, $functionname)) {
422 // Generate error response - unable to locate method
423 return RPC_NOSUCHMETHOD;
426 if (!method_exists($object, 'mnet_publishes')) {
427 // Generate error response - the class doesn't publish
428 // *any* methods, because it doesn't have an mnet_publishes
429 // method
430 return RPC_FORBIDDENMETHOD;
433 // Get the list of published services - initialise method array
434 $servicelist = $object->mnet_publishes();
435 $methodapproved = false;
437 // If the method is in the list of approved methods, set the
438 // methodapproved flag to true and break
439 foreach($servicelist as $service) {
440 if (in_array($functionname, $service['methods'])) {
441 $methodapproved = true;
442 break;
446 if (!$methodapproved) {
447 return RPC_FORBIDDENMETHOD;
450 // Stash the object so we can call the method on it later
451 $MNET_REMOTE_CLIENT->object_to_call($object);
452 // WE'RE LOOKING AT A FUNCTION
453 } else {
454 if (!function_exists($functionname)) {
455 // Generate error response - unable to locate function
456 return RPC_NOSUCHFUNCTION;
461 return RPC_OK;
464 function mnet_update_sso_access_control($username, $mnet_host_id, $accessctrl) {
465 $mnethost = get_record('mnet_host', 'id', $mnet_host_id);
466 if ($aclrecord = get_record('mnet_sso_access_control', 'username', $username, 'mnet_host_id', $mnet_host_id)) {
467 // update
468 $aclrecord->accessctrl = $accessctrl;
469 if (update_record('mnet_sso_access_control', $aclrecord)) {
470 add_to_log(SITEID, 'admin/mnet', 'update', 'admin/mnet/access_control.php',
471 "SSO ACL: $access user '$username' from {$mnethost->name}");
472 } else {
473 error(get_string('failedaclwrite','mnet', $username));
474 return false;
476 } else {
477 // insert
478 $aclrecord->username = $username;
479 $aclrecord->accessctrl = $accessctrl;
480 $aclrecord->mnet_host_id = $mnet_host_id;
481 if ($id = insert_record('mnet_sso_access_control', $aclrecord)) {
482 add_to_log(SITEID, 'admin/mnet', 'add', 'admin/mnet/access_control.php',
483 "SSO ACL: $access user '$username' from {$mnethost->name}");
484 } else {
485 error(get_string('failedaclwrite','mnet', $username));
486 return false;
489 return true;