MDL-9716
[moodle-linuxchix.git] / mnet / lib.php
blob9b73d88b07fb8bfa2cba3cdadc3a609522d696a1
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"));
66 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
67 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
69 $res = xmlrpc_decode(curl_exec($ch));
70 curl_close($ch);
72 if (!is_array($res)) { // ! error
73 $public_certificate = $res;
74 $credentials=array();
75 if (strlen(trim($public_certificate))) {
76 $credentials = openssl_x509_parse($public_certificate);
77 $host = $credentials['subject']['CN'];
78 if (strpos($uri, $host) !== false) {
79 mnet_set_public_key($uri, $public_certificate);
80 return $public_certificate;
84 return false;
87 /**
88 * Store a URI's public key in a static variable, or retrieve the key for a URI
90 * @param string $uri The URI of a file on the remote computer, including its
91 * https:// prefix
92 * @param mixed $key A public key to store in the array OR null. If the key
93 * is null, the function will return the previously stored
94 * key for the supplied URI, should it exist.
95 * @return mixed A public key OR true/false.
97 function mnet_set_public_key($uri, $key = null) {
98 static $keyarray = array();
99 if (isset($keyarray[$uri]) && empty($key)) {
100 return $keyarray[$uri];
101 } elseif (!empty($key)) {
102 $keyarray[$uri] = $key;
103 return true;
105 return false;
109 * Sign a message and return it in an XML-Signature document
111 * This function can sign any content, but it was written to provide a system of
112 * signing XML-RPC request and response messages. The message will be base64
113 * encoded, so it does not need to be text.
115 * We compute the SHA1 digest of the message.
116 * We compute a signature on that digest with our private key.
117 * We link to the public key that can be used to verify our signature.
118 * We base64 the message data.
119 * We identify our wwwroot - this must match our certificate's CN
121 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
122 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
123 * signature of that document using the local private key. This signature will
124 * uniquely identify the RPC document as having come from this server.
126 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
127 * site
129 * @param string $message The data you want to sign
130 * @return string An XML-DSig document
132 function mnet_sign_message($message) {
133 global $CFG, $MNET;
134 $digest = sha1($message);
135 $sig = $MNET->sign_message($message);
137 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
138 <signedMessage>
139 <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
140 <SignedInfo>
141 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
142 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>
143 <Reference URI="#XMLRPC-MSG">
144 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
145 <DigestValue>'.$digest.'</DigestValue>
146 </Reference>
147 </SignedInfo>
148 <SignatureValue>'.base64_encode($sig).'</SignatureValue>
149 <KeyInfo>
150 <RetrievalMethod URI="'.$CFG->wwwroot.'/mnet/publickey.php"/>
151 </KeyInfo>
152 </Signature>
153 <object ID="XMLRPC-MSG">'.base64_encode($message).'</object>
154 <wwwroot>'.$MNET->wwwroot.'</wwwroot>
155 <timestamp>'.time().'</timestamp>
156 </signedMessage>';
157 return $message;
161 * Encrypt a message and return it in an XML-Encrypted document
163 * This function can encrypt any content, but it was written to provide a system
164 * of encrypting XML-RPC request and response messages. The message will be
165 * base64 encoded, so it does not need to be text - binary data should work.
167 * We compute the SHA1 digest of the message.
168 * We compute a signature on that digest with our private key.
169 * We link to the public key that can be used to verify our signature.
170 * We base64 the message data.
171 * We identify our wwwroot - this must match our certificate's CN
173 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
174 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
175 * signature of that document using the local private key. This signature will
176 * uniquely identify the RPC document as having come from this server.
178 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
179 * site
181 * @param string $message The data you want to sign
182 * @param string $remote_certificate Peer's certificate in PEM format
183 * @return string An XML-ENC document
185 function mnet_encrypt_message($message, $remote_certificate) {
186 global $MNET;
188 // Generate a key resource from the remote_certificate text string
189 $publickey = openssl_get_publickey($remote_certificate);
191 if ( gettype($publickey) != 'resource' ) {
192 // Remote certificate is faulty.
193 return false;
196 // Initialize vars
197 $encryptedstring = '';
198 $symmetric_keys = array();
200 // passed by ref -> &$encryptedstring &$symmetric_keys
201 $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey));
202 $message = $encryptedstring;
203 $symmetrickey = array_pop($symmetric_keys);
205 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
206 <encryptedMessage>
207 <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
208 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
209 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
210 <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
211 <ds:KeyName>XMLENC</ds:KeyName>
212 </ds:KeyInfo>
213 <CipherData>
214 <CipherValue>'.base64_encode($message).'</CipherValue>
215 </CipherData>
216 </EncryptedData>
217 <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
218 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
219 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
220 <ds:KeyName>SSLKEY</ds:KeyName>
221 </ds:KeyInfo>
222 <CipherData>
223 <CipherValue>'.base64_encode($symmetrickey).'</CipherValue>
224 </CipherData>
225 <ReferenceList>
226 <DataReference URI="#ED"/>
227 </ReferenceList>
228 <CarriedKeyName>XMLENC</CarriedKeyName>
229 </EncryptedKey>
230 <wwwroot>'.$MNET->wwwroot.'</wwwroot>
231 </encryptedMessage>';
232 return $message;
236 * Get your SSL keys from the database, or create them (if they don't exist yet)
238 * Get your SSL keys from the database, or (if they don't exist yet) call
239 * mnet_generate_keypair to create them
241 * @param string $string The text you want to sign
242 * @return string The signature over that text
244 function mnet_get_keypair() {
245 global $CFG;
246 static $keypair = null;
247 if (!is_null($keypair)) return $keypair;
248 if ($result = get_field('config_plugins', 'value', 'plugin', 'mnet', 'name', 'openssl')) {
249 $keypair = explode('@@@@@@@@', $keypair);
250 $keypair['privatekey'] = openssl_pkey_get_private($keypair['keypair_PEM']);
251 $keypair['publickey'] = openssl_pkey_get_public($keypair['certificate']);
252 return $keypair;
253 } else {
254 $keypair = mnet_generate_keypair();
255 return $keypair;
260 * Generate public/private keys and store in the config table
262 * Use the distinguished name provided to create a CSR, and then sign that CSR
263 * with the same credentials. Store the keypair you create in the config table.
264 * If a distinguished name is not provided, create one using the fullname of
265 * 'the course with ID 1' as your organization name, and your hostname (as
266 * detailed in $CFG->wwwroot).
268 * @param array $dn The distinguished name of the server
269 * @return string The signature over that text
271 function mnet_generate_keypair($dn = null, $days=28) {
272 global $CFG, $USER;
273 $host = strtolower($CFG->wwwroot);
274 $host = ereg_replace("^http(s)?://",'',$host);
275 $break = strpos($host.'/' , '/');
276 $host = substr($host, 0, $break);
278 if ($result = get_record_select('course'," id ='".SITEID."' ")) {
279 $organization = $result->fullname;
280 } else {
281 $organization = 'None';
284 $keypair = array();
286 $country = 'NZ';
287 $province = 'Wellington';
288 $locality = 'Wellington';
289 $email = $CFG->noreplyaddress;
291 if(!empty($USER->country)) {
292 $country = $USER->country;
294 if(!empty($USER->city)) {
295 $province = $USER->city;
296 $locality = $USER->city;
298 if(!empty($USER->email)) {
299 $email = $USER->email;
302 if (is_null($dn)) {
303 $dn = array(
304 "countryName" => $country,
305 "stateOrProvinceName" => $province,
306 "localityName" => $locality,
307 "organizationName" => $organization,
308 "organizationalUnitName" => 'Moodle',
309 "commonName" => $CFG->wwwroot,
310 "emailAddress" => $email
314 // ensure we remove trailing slashes
315 $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
317 $new_key = openssl_pkey_new();
318 $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048));
319 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
320 unset($csr_rsc); // Free up the resource
322 // We export our self-signed certificate to a string.
323 openssl_x509_export($selfSignedCert, $keypair['certificate']);
324 openssl_x509_free($selfSignedCert);
326 // Export your public/private key pair as a PEM encoded string. You
327 // can protect it with an optional passphrase if you wish.
328 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'] /* , $passphrase */);
329 openssl_pkey_free($new_key);
330 unset($new_key); // Free up the resource
332 return $keypair;
336 * Check that an IP address falls within the given network/mask
337 * ok for export
339 * @param string $address Dotted quad
340 * @param string $network Dotted quad
341 * @param string $mask A number, e.g. 16, 24, 32
342 * @return bool
344 function ip_in_range($address, $network, $mask) {
345 $lnetwork = ip2long($network);
346 $laddress = ip2long($address);
348 $binnet = str_pad( decbin($lnetwork),32,"0","STR_PAD_LEFT" );
349 $firstpart = substr($binnet,0,$mask);
351 $binip = str_pad( decbin($laddress),32,"0","STR_PAD_LEFT" );
352 $firstip = substr($binip,0,$mask);
353 return(strcmp($firstpart,$firstip)==0);
357 * Check that a given function (or method) in an include file has been designated
358 * ok for export
360 * @param string $includefile The path to the include file
361 * @param string $functionname The name of the function (or method) to
362 * execute
363 * @param mixed $class A class name, or false if we're just testing
364 * a function
365 * @return int Zero (RPC_OK) if all ok - appropriate
366 * constant otherwise
368 function mnet_permit_rpc_call($includefile, $functionname, $class=false) {
369 global $CFG, $MNET_REMOTE_CLIENT;
371 if (file_exists($CFG->dirroot . $includefile)) {
372 include_once $CFG->dirroot . $includefile;
373 // $callprefix matches the rpc convention
374 // of not having a leading slash
375 $callprefix = preg_replace('!^/!', '', $includefile);
376 } else {
377 return RPC_NOSUCHFILE;
380 if ($functionname != clean_param($functionname, PARAM_PATH)) {
381 // Under attack?
382 // Todo: Should really return a much more BROKEN! response
383 return RPC_FORBIDDENMETHOD;
386 $id_list = $MNET_REMOTE_CLIENT->id;
387 if (!empty($CFG->mnet_all_hosts_id)) {
388 $id_list .= ', '.$CFG->mnet_all_hosts_id;
391 // TODO: change to left-join so we can disambiguate:
392 // 1. method doesn't exist
393 // 2. method exists but is prohibited
394 $sql = "
395 SELECT
396 count(r.id)
397 FROM
398 {$CFG->prefix}mnet_host2service h2s,
399 {$CFG->prefix}mnet_service2rpc s2r,
400 {$CFG->prefix}mnet_rpc r
401 WHERE
402 h2s.serviceid = s2r.serviceid AND
403 s2r.rpcid = r.id AND
404 r.xmlrpc_path = '$callprefix/$functionname' AND
405 h2s.hostid in ($id_list) AND
406 h2s.publish = '1'";
408 $permissionobj = record_exists_sql($sql);
410 if ($permissionobj === false) {
411 return RPC_FORBIDDENMETHOD;
414 // WE'RE LOOKING AT A CLASS/METHOD
415 if (false != $class) {
416 if (!class_exists($class)) {
417 // Generate error response - unable to locate class
418 return RPC_NOSUCHCLASS;
421 $object = new $class();
423 if (!method_exists($object, $functionname)) {
424 // Generate error response - unable to locate method
425 return RPC_NOSUCHMETHOD;
428 if (!method_exists($object, 'mnet_publishes')) {
429 // Generate error response - the class doesn't publish
430 // *any* methods, because it doesn't have an mnet_publishes
431 // method
432 return RPC_FORBIDDENMETHOD;
435 // Get the list of published services - initialise method array
436 $servicelist = $object->mnet_publishes();
437 $methodapproved = false;
439 // If the method is in the list of approved methods, set the
440 // methodapproved flag to true and break
441 foreach($servicelist as $service) {
442 if (in_array($functionname, $service['methods'])) {
443 $methodapproved = true;
444 break;
448 if (!$methodapproved) {
449 return RPC_FORBIDDENMETHOD;
452 // Stash the object so we can call the method on it later
453 $MNET_REMOTE_CLIENT->object_to_call($object);
454 // WE'RE LOOKING AT A FUNCTION
455 } else {
456 if (!function_exists($functionname)) {
457 // Generate error response - unable to locate function
458 return RPC_NOSUCHFUNCTION;
463 return RPC_OK;
466 function mnet_update_sso_access_control($username, $mnet_host_id, $accessctrl) {
467 $mnethost = get_record('mnet_host', 'id', $mnet_host_id);
468 if ($aclrecord = get_record('mnet_sso_access_control', 'username', $username, 'mnet_host_id', $mnet_host_id)) {
469 // update
470 $aclrecord->accessctrl = $accessctrl;
471 if (update_record('mnet_sso_access_control', $aclrecord)) {
472 add_to_log(SITEID, 'admin/mnet', 'update', 'admin/mnet/access_control.php',
473 "SSO ACL: $access user '$username' from {$mnethost->name}");
474 } else {
475 error(get_string('failedaclwrite','mnet', $username));
476 return false;
478 } else {
479 // insert
480 $aclrecord->username = $username;
481 $aclrecord->accessctrl = $accessctrl;
482 $aclrecord->mnet_host_id = $mnet_host_id;
483 if ($id = insert_record('mnet_sso_access_control', $aclrecord)) {
484 add_to_log(SITEID, 'admin/mnet', 'add', 'admin/mnet/access_control.php',
485 "SSO ACL: $access user '$username' from {$mnethost->name}");
486 } else {
487 error(get_string('failedaclwrite','mnet', $username));
488 return false;
491 return true;