See Release Notes
Long Term Support Release
Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]
1 <?php 2 /** 3 * An XML-RPC client 4 * 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 11 require_once $CFG->dirroot.'/mnet/lib.php'; 12 13 /** 14 * Class representing an XMLRPC request against a remote machine 15 */ 16 class mnet_xmlrpc_client { 17 18 var $method = ''; 19 var $params = array(); 20 var $timeout = 60; 21 var $error = array(); 22 var $response = ''; 23 var $mnet = null; 24 25 /** 26 * Constructor 27 */ 28 public function __construct() { 29 // make sure we've got this set up before we try and do anything else 30 $this->mnet = get_mnet_environment(); 31 } 32 33 /** 34 * Allow users to override the default timeout 35 * @param int $timeout Request timeout in seconds 36 * $return bool True if param is an integer or integer string 37 */ 38 public function set_timeout($timeout) { 39 if (!is_integer($timeout)) { 40 if (is_numeric($timeout)) { 41 $this->timeout = (integer)$timeout; 42 return true; 43 } 44 return false; 45 } 46 $this->timeout = $timeout; 47 return true; 48 } 49 50 /** 51 * Set the path to the method or function we want to execute on the remote 52 * machine. Examples: 53 * mod/scorm/functionname 54 * auth/mnet/methodname 55 * In the case of auth and enrolment plugins, an object will be created and 56 * the method on that object will be called 57 */ 58 public function set_method($xmlrpcpath) { 59 if (is_string($xmlrpcpath)) { 60 $this->method = $xmlrpcpath; 61 $this->params = array(); 62 return true; 63 } 64 $this->method = ''; 65 $this->params = array(); 66 return false; 67 } 68 69 /** 70 * Add a parameter to the array of parameters. 71 * 72 * @param string $argument A transport ID, as defined in lib.php 73 * @param string $type The argument type, can be one of: 74 * i4 75 * i8 76 * int 77 * double 78 * string 79 * boolean 80 * datetime | dateTime.iso8601 81 * base64 82 * null 83 * array 84 * struct 85 * @return bool True on success 86 */ 87 public function add_param($argument, $type = 'string') { 88 89 // Convert any use of the old 'datetime' to the correct 'dateTime.iso8601' one. 90 $type = ($type === 'datetime' ? 'dateTime.iso8601' : $type); 91 92 // BC fix, if some argument is array and comes as string, change type to array (sequentials) 93 // or struct (associative). 94 // This is the behavior of the encode_request() method from the xmlrpc extension. 95 // Note that uses in core have been fixed, but there may be others using that. 96 if (is_array($argument) && $type === 'string') { 97 if (array_keys($argument) === range(0, count($argument) - 1)) { 98 $type = 'array'; 99 } else { 100 $type = 'struct'; 101 } 102 mnet_debug('Incorrect ' . $type . ' param passed as string in mnet_xmlrpc_client->add_param(): ' . 103 json_encode($argument)); 104 } 105 106 if (!isset(\PhpXmlRpc\Value::$xmlrpcTypes[$type])) { // Arrived here, still erong type? Let's stop. 107 return false; 108 } 109 110 // If we are array or struct, we need to ensure that, recursively, all the elements are proper values. 111 // or serialize, used later on send() won't work with them. Encoder::encode() provides us with that. 112 if ($type === 'array' || $type === 'struct') { 113 $encoder = new \PhpXmlRpc\Encoder(); 114 $this->params[] = $encoder->encode($argument); 115 } else { 116 // Normal scalar case. 117 $this->params[] = new \PhpXmlRpc\Value($argument, $type); 118 } 119 return true; 120 } 121 122 /** 123 * Send the request to the server - decode and return the response 124 * 125 * @param object $mnet_peer A mnet_peer object with details of the 126 * remote host we're connecting to 127 * @return mixed A PHP variable, as returned by the 128 */ 129 public function send($mnet_peer) { 130 global $CFG, $DB; 131 132 if (!$this->permission_to_call($mnet_peer)) { 133 mnet_debug("tried and wasn't allowed to call a method on $mnet_peer->wwwroot"); 134 return false; 135 } 136 137 $request = new \PhpXmlRpc\Request($this->method, $this->params); 138 $this->requesttext = $request->serialize('utf-8'); 139 140 $this->signedrequest = mnet_sign_message($this->requesttext); 141 $this->encryptedrequest = mnet_encrypt_message($this->signedrequest, $mnet_peer->public_key); 142 143 $client = $this->prepare_http_request($mnet_peer); 144 145 $timestamp_send = time(); 146 mnet_debug("about to send the xmlrpc request"); 147 $response = $client->send($this->encryptedrequest, $this->timeout); 148 mnet_debug("managed to complete a xmlrpc request"); 149 $timestamp_receive = time(); 150 151 if ($response->faultCode()) { 152 $this->error[] = $response->faultCode() .':'. $response->faultString(); 153 return false; 154 } 155 156 $this->rawresponse = $response->value(); // Because MNet responses ARE NOT valid xmlrpc, don't try any PhpXmlRpc facility. 157 $this->rawresponse = trim($this->rawresponse); 158 159 $mnet_peer->touch(); 160 161 $crypt_parser = new mnet_encxml_parser(); 162 $crypt_parser->parse($this->rawresponse); 163 164 // If we couldn't parse the message, or it doesn't seem to have encrypted contents, 165 // give the most specific error msg available & return 166 if (!$crypt_parser->payload_encrypted) { 167 if (! empty($crypt_parser->remoteerror)) { 168 $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror; 169 } else if (! empty($crypt_parser->error)) { 170 $crypt_parser_error = $crypt_parser->error[0]; 171 172 $message = '3:XML Parse error in payload: '.$crypt_parser_error['string']."\n"; 173 if (array_key_exists('lineno', $crypt_parser_error)) { 174 $message .= 'At line number: '.$crypt_parser_error['lineno']."\n"; 175 } 176 if (array_key_exists('line', $crypt_parser_error)) { 177 $message .= 'Which reads: '.$crypt_parser_error['line']."\n"; 178 } 179 $this->error[] = $message; 180 } else { 181 $this->error[] = '1:Payload not encrypted '; 182 } 183 184 $crypt_parser->free_resource(); 185 return false; 186 } 187 188 $key = array_pop($crypt_parser->cipher); 189 $data = array_pop($crypt_parser->cipher); 190 191 $crypt_parser->free_resource(); 192 193 // Initialize payload var 194 $decryptedenvelope = ''; 195 196 // &$decryptedenvelope 197 $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), 198 $this->mnet->get_private_key(), 'RC4'); 199 200 if (!$isOpen) { 201 // Decryption failed... let's try our archived keys 202 $openssl_history = get_config('mnet', 'openssl_history'); 203 if(empty($openssl_history)) { 204 $openssl_history = array(); 205 set_config('openssl_history', serialize($openssl_history), 'mnet'); 206 } else { 207 $openssl_history = unserialize($openssl_history); 208 } 209 foreach($openssl_history as $keyset) { 210 $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']); 211 $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $keyresource, 'RC4'); 212 if ($isOpen) { 213 // It's an older code, sir, but it checks out 214 break; 215 } 216 } 217 } 218 219 if (!$isOpen) { 220 trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}."); 221 $this->error[] = '3:No key match'; 222 return false; 223 } 224 225 if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) { 226 $sig_parser = new mnet_encxml_parser(); 227 $sig_parser->parse($decryptedenvelope); 228 } else { 229 $this->error[] = '2:Payload not signed: ' . $decryptedenvelope; 230 return false; 231 } 232 233 // Margin of error is the time it took the request to complete. 234 $margin_of_error = $timestamp_receive - $timestamp_send; 235 236 // Guess the time gap between sending the request and the remote machine 237 // executing the time() function. Marginally better than nothing. 238 $hysteresis = ($margin_of_error) / 2; 239 240 $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis; 241 $time_offset = $remote_timestamp - $timestamp_send; 242 if ($time_offset > 0) { 243 $threshold = get_config('mnet', 'drift_threshold'); 244 if(empty($threshold)) { 245 // We decided 15 seconds was a pretty good arbitrary threshold 246 // for time-drift between servers, but you can customize this in 247 // the config_plugins table. It's not advised though. 248 set_config('drift_threshold', 15, 'mnet'); 249 $threshold = 15; 250 } 251 if ($time_offset > $threshold) { 252 $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds'; 253 return false; 254 } 255 } 256 257 $this->xmlrpcresponse = base64_decode($sig_parser->data_object); 258 // Let's convert the xmlrpc back to PHP structure. 259 $response = null; 260 $encoder = new \PhpXmlRpc\Encoder(); 261 $oresponse = $encoder->decodeXML($this->xmlrpcresponse); // First, to internal PhpXmlRpc\Response structure. 262 if ($oresponse instanceof \PhpXmlRpc\Response) { 263 // Special handling of fault responses (because value() doesn't handle them properly). 264 if ($oresponse->faultCode()) { 265 $response = ['faultCode' => $oresponse->faultCode(), 'faultString' => $oresponse->faultString()]; 266 } else { 267 $response = $encoder->decode($oresponse->value()); // Normal Response conversion to PHP. 268 } 269 } else { 270 // Maybe this is just a param, let's convert it too. 271 $response = $encoder->decode($oresponse); 272 } 273 $this->response = $response; 274 275 // xmlrpc errors are pushed onto the $this->error stack 276 if (is_array($this->response) && array_key_exists('faultCode', $this->response)) { 277 // The faultCode 7025 means we tried to connect with an old SSL key 278 // The faultString is the new key - let's save it and try again 279 // The re_key attribute stops us from getting into a loop 280 if($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) { 281 mnet_debug('recieved an old-key fault, so trying to get the new key and update our records'); 282 // If the new certificate doesn't come thru clean_param() unmolested, error out 283 if($this->response['faultString'] != clean_param($this->response['faultString'], PARAM_PEM)) { 284 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; 285 } 286 $record = new stdClass(); 287 $record->id = $mnet_peer->id; 288 $record->public_key = $this->response['faultString']; 289 $details = openssl_x509_parse($record->public_key); 290 if(!isset($details['validTo_time_t'])) { 291 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; 292 } 293 $record->public_key_expires = $details['validTo_time_t']; 294 $DB->update_record('mnet_host', $record); 295 296 // Create a new peer object populated with the new info & try re-sending the request 297 $rekeyed_mnet_peer = new mnet_peer(); 298 $rekeyed_mnet_peer->set_id($record->id); 299 $rekeyed_mnet_peer->re_key = true; 300 return $this->send($rekeyed_mnet_peer); 301 } 302 if (!empty($CFG->mnet_rpcdebug)) { 303 if (get_string_manager()->string_exists('error'.$this->response['faultCode'], 'mnet')) { 304 $guidance = get_string('error'.$this->response['faultCode'], 'mnet'); 305 } else { 306 $guidance = ''; 307 } 308 } else { 309 $guidance = ''; 310 } 311 $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance; 312 } 313 314 // ok, it's signed, but is it signed with the right certificate ? 315 // do this *after* we check for an out of date key 316 $verified = openssl_verify($this->xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key); 317 if ($verified != 1) { 318 $this->error[] = 'Invalid signature'; 319 } 320 321 return empty($this->error); 322 } 323 324 /** 325 * Check that we are permitted to call method on specified peer 326 * 327 * @param object $mnet_peer A mnet_peer object with details of the remote host we're connecting to 328 * @return bool True if we permit calls to method on specified peer, False otherwise. 329 */ 330 public function permission_to_call($mnet_peer) { 331 global $DB, $CFG, $USER; 332 333 // Executing any system method is permitted. 334 $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices'); 335 if (in_array($this->method, $system_methods) ) { 336 return true; 337 } 338 339 $hostids = array($mnet_peer->id); 340 if (!empty($CFG->mnet_all_hosts_id)) { 341 $hostids[] = $CFG->mnet_all_hosts_id; 342 } 343 // At this point, we don't care if the remote host implements the 344 // method we're trying to call. We just want to know that: 345 // 1. The method belongs to some service, as far as OUR host knows 346 // 2. We are allowed to subscribe to that service on this mnet_peer 347 348 list($hostidsql, $hostidparams) = $DB->get_in_or_equal($hostids); 349 350 $sql = "SELECT r.id 351 FROM {mnet_remote_rpc} r 352 INNER JOIN {mnet_remote_service2rpc} s2r ON s2r.rpcid = r.id 353 INNER JOIN {mnet_host2service} h2s ON h2s.serviceid = s2r.serviceid 354 WHERE r.xmlrpcpath = ? 355 AND h2s.subscribe = ? 356 AND h2s.hostid $hostidsql"; 357 358 $params = array($this->method, 1); 359 $params = array_merge($params, $hostidparams); 360 361 if ($DB->record_exists_sql($sql, $params)) { 362 return true; 363 } 364 365 $this->error[] = '7:User with ID '. $USER->id . 366 ' attempted to call unauthorised method '. 367 $this->method.' on host '. 368 $mnet_peer->wwwroot; 369 return false; 370 } 371 372 /** 373 * Generate a \PhpXmlRpc\Client handle and prepare it for sending to an mnet host 374 * 375 * @param object $mnet_peer A mnet_peer object with details of the remote host the request will be sent to 376 * @return \PhpXmlRpc\Client handle - the almost-ready-to-send http request 377 */ 378 public function prepare_http_request ($mnet_peer) { 379 $this->uri = $mnet_peer->wwwroot . $mnet_peer->application->xmlrpc_server_url; 380 381 // Instantiate the xmlrpc client to be used for the client request 382 // and configure it the way we want. 383 $client = new \PhpXmlRpc\Client($this->uri); 384 $client->setUseCurl(\PhpXmlRpc\Client::USE_CURL_ALWAYS); 385 $client->setUserAgent('Moodle'); 386 $client->return_type = 'xml'; // Because MNet responses ARE NOT valid xmlrpc, don't try any validation. 387 388 // TODO: Link this to DEBUG DEVELOPER or with MNET debugging... 389 // $client->setdebug(1); // See a good number of complete requests and responses. 390 391 $verifyhost = 0; 392 $verifypeer = false; 393 if ($mnet_peer->sslverification == mnet_peer::SSL_HOST_AND_PEER) { 394 $verifyhost = 2; 395 $verifypeer = true; 396 } else if ($mnet_peer->sslverification == mnet_peer::SSL_HOST) { 397 $verifyhost = 2; 398 } 399 $client->setSSLVerifyHost($verifyhost); 400 $client->setSSLVerifyPeer($verifypeer); 401 402 return $client; 403 } 404 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body