���ѧۧݧ�ӧ�� �ާ֧ߧ֧էا֧� - ���֧էѧܧ�ڧ��ӧѧ�� - /home3/cpr76684/public_html/xmlrpc.tar
���ѧ٧ѧ�
xmlparser.php 0000644 00000026037 15151174117 0007305 0 ustar 00 <?php /** * Custom XML parser for signed and/or encrypted XML Docs * * @author Donal McMullan donal@catalyst.net.nz * @version 0.0.1 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package mnet */ /** * Custom XML parser class for signed and/or encrypted XML Docs */ class mnet_encxml_parser { /** * Constructor creates and initialises parser resource and calls initialise * * @return bool True */ public function __construct() { return $this->initialise(); } /** * Old syntax of class constructor. Deprecated in PHP7. * * @deprecated since Moodle 3.1 */ public function mnet_encxml_parser() { debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER); self::__construct(); } /** * Set default element handlers and initialise properties to empty. * * @return bool True */ function initialise() { $this->parser = xml_parser_create(); xml_set_object($this->parser, $this); xml_set_element_handler($this->parser, "start_element", "end_element"); xml_set_character_data_handler($this->parser, "discard_data"); $this->tag_number = 0; // Just a unique ID for each tag $this->digest = ''; $this->remote_timestamp = ''; $this->remote_wwwroot = ''; $this->signature = ''; $this->data_object = ''; $this->key_URI = ''; $this->payload_encrypted = false; $this->cipher = array(); $this->error = array(); $this->remoteerror = null; $this->errorstarted = false; return true; } /** * Parse a block of XML text * * The XML Text will be an XML-RPC request which is wrapped in an XML doc * with a signature from the sender. This envelope may be encrypted and * delivered within another XML envelope with a symmetric key. The parser * should first decrypt this XML, and then place the XML-RPC request into * the data_object property, and the signature into the signature property. * * See the W3C's {@link http://www.w3.org/TR/xmlenc-core/ XML Encryption Syntax and Processing} * and {@link http://www.w3.org/TR/2001/PR-xmldsig-core-20010820/ XML-Signature Syntax and Processing} * guidelines for more detail on the XML. * * -----XML-Envelope--------------------------------- * | | * | Symmetric-key-------------------------- | * | |_____________________________________| | * | | * | Encrypted data------------------------- | * | | | | * | | -XML-Envelope------------------ | | * | | | | | | * | | | --Signature------------- | | | * | | | |______________________| | | | * | | | | | | * | | | --Signed-Payload-------- | | | * | | | | | | | | * | | | | XML-RPC Request | | | | * | | | |______________________| | | | * | | | | | | * | | |_____________________________| | | * | |_____________________________________| | * | | * |________________________________________________| * * @param string $data The XML that you want to parse * @return bool True on success - false on failure */ function parse($data) { $p = xml_parse($this->parser, $data); if ($p == 0) { // Parse failed $errcode = xml_get_error_code($this->parser); $errstring = xml_error_string($errcode); $lineno = xml_get_current_line_number($this->parser); if ($lineno !== false) { $error = array('lineno' => $lineno); $lineno--; // Line numbering starts at 1. while ($lineno > 0) { $data = strstr($data, "\n"); $lineno--; } $data .= "\n"; // In case there's only one line (no newline) $line = substr($data, 0, strpos($data, "\n")); $error['code'] = $errcode; $error['string'] = $errstring; $error['line'] = $line; $this->error[] = $error; } else { $this->error[] = array('code' => $errcode, 'string' => $errstring); } } if (!empty($this->remoteerror)) { return false; } if (count($this->cipher) > 0) { $this->cipher = array_values($this->cipher); $this->payload_encrypted = true; } return (bool)$p; } /** * Destroy the parser and free up any related resource. */ function free_resource() { $free = xml_parser_free($this->parser); } /** * Set the character-data handler to the right function for each element * * For each tag (element) name, this function switches the character-data * handler to the function that handles that element. Note that character * data is referred to the handler in blocks of 1024 bytes. * * @param mixed $parser The XML parser * @param string $name The name of the tag, e.g. method_call * @param array $attrs The tag's attributes (if any exist). * @return bool True */ function start_element($parser, $name, $attrs) { $this->tag_number++; $handler = 'discard_data'; switch(strtoupper($name)) { case 'DIGESTVALUE': $handler = 'parse_digest'; break; case 'SIGNATUREVALUE': $handler = 'parse_signature'; break; case 'OBJECT': $handler = 'parse_object'; break; case 'RETRIEVALMETHOD': $this->key_URI = $attrs['URI']; break; case 'TIMESTAMP': $handler = 'parse_timestamp'; break; case 'WWWROOT': $handler = 'parse_wwwroot'; break; case 'CIPHERVALUE': $this->cipher[$this->tag_number] = ''; $handler = 'parse_cipher'; break; case 'FAULT': $handler = 'parse_fault'; default: break; } xml_set_character_data_handler($this->parser, $handler); return true; } /** * Add the next chunk of character data to the remote_timestamp string * * @param mixed $parser The XML parser * @param string $data The content of the current tag (1024 byte chunk) * @return bool True */ function parse_timestamp($parser, $data) { $this->remote_timestamp .= $data; return true; } /** * Add the next chunk of character data to the cipher string for that tag * * The XML parser calls the character-data handler with 1024-character * chunks of data. This means that the handler may be called several times * for a single tag, so we use the concatenate operator (.) to build the * tag content into a string. * We should not encounter more than one of each tag type, except for the * cipher tag. We will often see two of those. We prevent the content of * these two tags being concatenated together by counting each tag, and * using its 'number' as the key to an array of ciphers. * * @param mixed $parser The XML parser * @param string $data The content of the current tag (1024 byte chunk) * @return bool True */ function parse_cipher($parser, $data) { $this->cipher[$this->tag_number] .= $data; return true; } /** * Add the next chunk of character data to the remote_wwwroot string * * @param mixed $parser The XML parser * @param string $data The content of the current tag (1024 byte chunk) * @return bool True */ function parse_wwwroot($parser, $data) { $this->remote_wwwroot .= $data; return true; } /** * Add the next chunk of character data to the digest string * * @param mixed $parser The XML parser * @param string $data The content of the current tag (1024 byte chunk) * @return bool True */ function parse_digest($parser, $data) { $this->digest .= $data; return true; } /** * Add the next chunk of character data to the signature string * * @param mixed $parser The XML parser * @param string $data The content of the current tag (1024 byte chunk) * @return bool True */ function parse_signature($parser, $data) { $this->signature .= $data; return true; } /** * Add the next chunk of character data to the data_object string * * @param mixed $parser The XML parser * @param string $data The content of the current tag (1024 byte chunk) * @return bool True */ function parse_object($parser, $data) { $this->data_object .= $data; return true; } /** * Discard the next chunk of character data * * This is used for tags that we're not interested in. * * @param mixed $parser The XML parser * @param string $data The content of the current tag (1024 byte chunk) * @return bool True */ function discard_data($parser, $data) { if (!$this->errorstarted) { // Not interested return true; } $data = trim($data); if (isset($this->errorstarted->faultstringstarted) && !empty($data)) { $this->remoteerror .= ', message: ' . $data; } else if (isset($this->errorstarted->faultcodestarted)) { $this->remoteerror = 'code: ' . $data; unset($this->errorstarted->faultcodestarted); } else if ($data == 'faultCode') { $this->errorstarted->faultcodestarted = true; } else if ($data == 'faultString') { $this->errorstarted->faultstringstarted = true; } return true; } function parse_fault($parser, $data) { $this->errorstarted = new StdClass; return true; } /** * Switch the character-data handler to ignore the next chunk of data * * @param mixed $parser The XML parser * @param string $name The name of the tag, e.g. method_call * @return bool True */ function end_element($parser, $name) { $ok = xml_set_character_data_handler($this->parser, "discard_data"); return true; } } client.php 0000644 00000041362 15151174117 0006544 0 ustar 00 <?php /** * An XML-RPC client * * @author Donal McMullan donal@catalyst.net.nz * @version 0.0.1 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package mnet */ require_once $CFG->dirroot.'/mnet/lib.php'; /** * Class representing an XMLRPC request against a remote machine */ class mnet_xmlrpc_client { var $method = ''; var $params = array(); var $timeout = 60; var $error = array(); var $response = ''; var $mnet = null; /** * Constructor */ public function __construct() { // make sure we've got this set up before we try and do anything else $this->mnet = get_mnet_environment(); } /** * Allow users to override the default timeout * @param int $timeout Request timeout in seconds * $return bool True if param is an integer or integer string */ public function set_timeout($timeout) { if (!is_integer($timeout)) { if (is_numeric($timeout)) { $this->timeout = (integer)$timeout; return true; } return false; } $this->timeout = $timeout; return true; } /** * Set the path to the method or function we want to execute on the remote * machine. Examples: * mod/scorm/functionname * auth/mnet/methodname * In the case of auth and enrolment plugins, an object will be created and * the method on that object will be called */ public function set_method($xmlrpcpath) { if (is_string($xmlrpcpath)) { $this->method = $xmlrpcpath; $this->params = array(); return true; } $this->method = ''; $this->params = array(); return false; } /** * Add a parameter to the array of parameters. * * @param string $argument A transport ID, as defined in lib.php * @param string $type The argument type, can be one of: * i4 * i8 * int * double * string * boolean * datetime | dateTime.iso8601 * base64 * null * array * struct * @return bool True on success */ public function add_param($argument, $type = 'string') { // Convert any use of the old 'datetime' to the correct 'dateTime.iso8601' one. $type = ($type === 'datetime' ? 'dateTime.iso8601' : $type); // BC fix, if some argument is array and comes as string, change type to array (sequentials) // or struct (associative). // This is the behavior of the encode_request() method from the xmlrpc extension. // Note that uses in core have been fixed, but there may be others using that. if (is_array($argument) && $type === 'string') { if (array_keys($argument) === range(0, count($argument) - 1)) { $type = 'array'; } else { $type = 'struct'; } mnet_debug('Incorrect ' . $type . ' param passed as string in mnet_xmlrpc_client->add_param(): ' . json_encode($argument)); } if (!isset(\PhpXmlRpc\Value::$xmlrpcTypes[$type])) { // Arrived here, still erong type? Let's stop. return false; } // If we are array or struct, we need to ensure that, recursively, all the elements are proper values. // or serialize, used later on send() won't work with them. Encoder::encode() provides us with that. if ($type === 'array' || $type === 'struct') { $encoder = new \PhpXmlRpc\Encoder(); $this->params[] = $encoder->encode($argument); } else { // Normal scalar case. $this->params[] = new \PhpXmlRpc\Value($argument, $type); } return true; } /** * Send the request to the server - decode and return the response * * @param object $mnet_peer A mnet_peer object with details of the * remote host we're connecting to * @return mixed A PHP variable, as returned by the */ public function send($mnet_peer) { global $CFG, $DB; if (!$this->permission_to_call($mnet_peer)) { mnet_debug("tried and wasn't allowed to call a method on $mnet_peer->wwwroot"); return false; } $request = new \PhpXmlRpc\Request($this->method, $this->params); $this->requesttext = $request->serialize('utf-8'); $this->signedrequest = mnet_sign_message($this->requesttext); $this->encryptedrequest = mnet_encrypt_message($this->signedrequest, $mnet_peer->public_key); $client = $this->prepare_http_request($mnet_peer); $timestamp_send = time(); mnet_debug("about to send the xmlrpc request"); $response = $client->send($this->encryptedrequest, $this->timeout); mnet_debug("managed to complete a xmlrpc request"); $timestamp_receive = time(); if ($response->faultCode()) { $this->error[] = $response->faultCode() .':'. $response->faultString(); return false; } $this->rawresponse = $response->value(); // Because MNet responses ARE NOT valid xmlrpc, don't try any PhpXmlRpc facility. $this->rawresponse = trim($this->rawresponse); $mnet_peer->touch(); $crypt_parser = new mnet_encxml_parser(); $crypt_parser->parse($this->rawresponse); // If we couldn't parse the message, or it doesn't seem to have encrypted contents, // give the most specific error msg available & return if (!$crypt_parser->payload_encrypted) { if (! empty($crypt_parser->remoteerror)) { $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror; } else if (! empty($crypt_parser->error)) { $crypt_parser_error = $crypt_parser->error[0]; $message = '3:XML Parse error in payload: '.$crypt_parser_error['string']."\n"; if (array_key_exists('lineno', $crypt_parser_error)) { $message .= 'At line number: '.$crypt_parser_error['lineno']."\n"; } if (array_key_exists('line', $crypt_parser_error)) { $message .= 'Which reads: '.$crypt_parser_error['line']."\n"; } $this->error[] = $message; } else { $this->error[] = '1:Payload not encrypted '; } $crypt_parser->free_resource(); return false; } $key = array_pop($crypt_parser->cipher); $data = array_pop($crypt_parser->cipher); $crypt_parser->free_resource(); // Initialize payload var $decryptedenvelope = ''; // &$decryptedenvelope $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $this->mnet->get_private_key(), 'RC4'); if (!$isOpen) { // Decryption failed... let's try our archived keys $openssl_history = get_config('mnet', 'openssl_history'); if(empty($openssl_history)) { $openssl_history = array(); set_config('openssl_history', serialize($openssl_history), 'mnet'); } else { $openssl_history = unserialize($openssl_history); } foreach($openssl_history as $keyset) { $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']); $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $keyresource, 'RC4'); if ($isOpen) { // It's an older code, sir, but it checks out break; } } } if (!$isOpen) { trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}."); $this->error[] = '3:No key match'; return false; } if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) { $sig_parser = new mnet_encxml_parser(); $sig_parser->parse($decryptedenvelope); } else { $this->error[] = '2:Payload not signed: ' . $decryptedenvelope; return false; } // Margin of error is the time it took the request to complete. $margin_of_error = $timestamp_receive - $timestamp_send; // Guess the time gap between sending the request and the remote machine // executing the time() function. Marginally better than nothing. $hysteresis = ($margin_of_error) / 2; $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis; $time_offset = $remote_timestamp - $timestamp_send; if ($time_offset > 0) { $threshold = get_config('mnet', 'drift_threshold'); if(empty($threshold)) { // We decided 15 seconds was a pretty good arbitrary threshold // for time-drift between servers, but you can customize this in // the config_plugins table. It's not advised though. set_config('drift_threshold', 15, 'mnet'); $threshold = 15; } if ($time_offset > $threshold) { $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds'; return false; } } $this->xmlrpcresponse = base64_decode($sig_parser->data_object); // Let's convert the xmlrpc back to PHP structure. $response = null; $encoder = new \PhpXmlRpc\Encoder(); $oresponse = $encoder->decodeXML($this->xmlrpcresponse); // First, to internal PhpXmlRpc\Response structure. if ($oresponse instanceof \PhpXmlRpc\Response) { // Special handling of fault responses (because value() doesn't handle them properly). if ($oresponse->faultCode()) { $response = ['faultCode' => $oresponse->faultCode(), 'faultString' => $oresponse->faultString()]; } else { $response = $encoder->decode($oresponse->value()); // Normal Response conversion to PHP. } } else { // Maybe this is just a param, let's convert it too. $response = $encoder->decode($oresponse); } $this->response = $response; // xmlrpc errors are pushed onto the $this->error stack if (is_array($this->response) && array_key_exists('faultCode', $this->response)) { // The faultCode 7025 means we tried to connect with an old SSL key // The faultString is the new key - let's save it and try again // The re_key attribute stops us from getting into a loop if($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) { mnet_debug('recieved an old-key fault, so trying to get the new key and update our records'); // If the new certificate doesn't come thru clean_param() unmolested, error out if($this->response['faultString'] != clean_param($this->response['faultString'], PARAM_PEM)) { $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } $record = new stdClass(); $record->id = $mnet_peer->id; $record->public_key = $this->response['faultString']; $details = openssl_x509_parse($record->public_key); if(!isset($details['validTo_time_t'])) { $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } $record->public_key_expires = $details['validTo_time_t']; $DB->update_record('mnet_host', $record); // Create a new peer object populated with the new info & try re-sending the request $rekeyed_mnet_peer = new mnet_peer(); $rekeyed_mnet_peer->set_id($record->id); $rekeyed_mnet_peer->re_key = true; return $this->send($rekeyed_mnet_peer); } if (!empty($CFG->mnet_rpcdebug)) { if (get_string_manager()->string_exists('error'.$this->response['faultCode'], 'mnet')) { $guidance = get_string('error'.$this->response['faultCode'], 'mnet'); } else { $guidance = ''; } } else { $guidance = ''; } $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance; } // ok, it's signed, but is it signed with the right certificate ? // do this *after* we check for an out of date key $verified = openssl_verify($this->xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key); if ($verified != 1) { $this->error[] = 'Invalid signature'; } return empty($this->error); } /** * Check that we are permitted to call method on specified peer * * @param object $mnet_peer A mnet_peer object with details of the remote host we're connecting to * @return bool True if we permit calls to method on specified peer, False otherwise. */ public function permission_to_call($mnet_peer) { global $DB, $CFG, $USER; // Executing any system method is permitted. $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices'); if (in_array($this->method, $system_methods) ) { return true; } $hostids = array($mnet_peer->id); if (!empty($CFG->mnet_all_hosts_id)) { $hostids[] = $CFG->mnet_all_hosts_id; } // At this point, we don't care if the remote host implements the // method we're trying to call. We just want to know that: // 1. The method belongs to some service, as far as OUR host knows // 2. We are allowed to subscribe to that service on this mnet_peer list($hostidsql, $hostidparams) = $DB->get_in_or_equal($hostids); $sql = "SELECT r.id FROM {mnet_remote_rpc} r INNER JOIN {mnet_remote_service2rpc} s2r ON s2r.rpcid = r.id INNER JOIN {mnet_host2service} h2s ON h2s.serviceid = s2r.serviceid WHERE r.xmlrpcpath = ? AND h2s.subscribe = ? AND h2s.hostid $hostidsql"; $params = array($this->method, 1); $params = array_merge($params, $hostidparams); if ($DB->record_exists_sql($sql, $params)) { return true; } $this->error[] = '7:User with ID '. $USER->id . ' attempted to call unauthorised method '. $this->method.' on host '. $mnet_peer->wwwroot; return false; } /** * Generate a \PhpXmlRpc\Client handle and prepare it for sending to an mnet host * * @param object $mnet_peer A mnet_peer object with details of the remote host the request will be sent to * @return \PhpXmlRpc\Client handle - the almost-ready-to-send http request */ public function prepare_http_request ($mnet_peer) { $this->uri = $mnet_peer->wwwroot . $mnet_peer->application->xmlrpc_server_url; // Instantiate the xmlrpc client to be used for the client request // and configure it the way we want. $client = new \PhpXmlRpc\Client($this->uri); $client->setUseCurl(\PhpXmlRpc\Client::USE_CURL_ALWAYS); $client->setUserAgent('Moodle'); $client->return_type = 'xml'; // Because MNet responses ARE NOT valid xmlrpc, don't try any validation. // TODO: Link this to DEBUG DEVELOPER or with MNET debugging... // $client->setdebug(1); // See a good number of complete requests and responses. $verifyhost = 0; $verifypeer = false; if ($mnet_peer->sslverification == mnet_peer::SSL_HOST_AND_PEER) { $verifyhost = 2; $verifypeer = true; } else if ($mnet_peer->sslverification == mnet_peer::SSL_HOST) { $verifyhost = 2; } $client->setSSLVerifyHost($verifyhost); $client->setSSLVerifyPeer($verifypeer); return $client; } } serverlib.php 0000644 00000065165 15151174117 0007272 0 ustar 00 <?php /** * -----XML-Envelope--------------------------------- * | | * | Encrypted-Symmetric-key---------------- | * | |_____________________________________| | * | | * | Encrypted data------------------------- | * | | | | * | | -XML-Envelope------------------ | | * | | | | | | * | | | --Signature------------- | | | * | | | |______________________| | | | * | | | | | | * | | | --Signed-Payload-------- | | | * | | | | | | | | * | | | | XML-RPC Request | | | | * | | | |______________________| | | | * | | | | | | * | | |_____________________________| | | * | |_____________________________________| | * | | * |________________________________________________| * */ /* Strip encryption envelope (if present) and decrypt data * * @param string $rawpostdata The XML that the client sent * * @throws mnet_server_exception * * @return string XML with any encryption envolope removed */ function mnet_server_strip_encryption($rawpostdata) { $remoteclient = get_mnet_remote_client(); $crypt_parser = new mnet_encxml_parser(); $crypt_parser->parse($rawpostdata); $mnet = get_mnet_environment(); if (!$crypt_parser->payload_encrypted) { return $rawpostdata; } // Make sure we know who we're talking to $host_record_exists = $remoteclient->set_wwwroot($crypt_parser->remote_wwwroot); if (false == $host_record_exists) { throw new mnet_server_exception(7020, 'wrong-wwwroot', $crypt_parser->remote_wwwroot); } // This key is symmetric, and is itself encrypted. Can be decrypted using our private key $key = array_pop($crypt_parser->cipher); // This data is symmetrically encrypted, can be decrypted using the above key $data = array_pop($crypt_parser->cipher); $crypt_parser->free_resource(); $payload = ''; // Initialize payload var // &$payload $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $mnet->get_private_key(), 'RC4'); if ($isOpen) { $remoteclient->was_encrypted(); return $payload; } // Decryption failed... let's try our archived keys $openssl_history = get_config('mnet', 'openssl_history'); if(empty($openssl_history)) { $openssl_history = array(); set_config('openssl_history', serialize($openssl_history), 'mnet'); } else { $openssl_history = unserialize($openssl_history); } foreach($openssl_history as $keyset) { $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']); $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $keyresource, 'RC4'); if ($isOpen) { // It's an older code, sir, but it checks out $remoteclient->was_encrypted(); $remoteclient->encrypted_to($keyresource); $remoteclient->set_pushkey(); return $payload; } } //If after all that we still couldn't decrypt the message, error out. throw new mnet_server_exception(7023, 'encryption-invalid'); } /* Strip signature envelope (if present), try to verify any signature using our record of remote peer's public key. * * @param string $plaintextmessage XML envelope containing XMLRPC request and signature * * @return string XMLRPC request */ function mnet_server_strip_signature($plaintextmessage) { $remoteclient = get_mnet_remote_client(); $sig_parser = new mnet_encxml_parser(); $sig_parser->parse($plaintextmessage); if ($sig_parser->signature == '') { return $plaintextmessage; } // Record that the request was signed in some way $remoteclient->was_signed(); // Load any information we have about this mnet peer $remoteclient->set_wwwroot($sig_parser->remote_wwwroot); $payload = base64_decode($sig_parser->data_object); $signature = base64_decode($sig_parser->signature); $certificate = $remoteclient->public_key; // If we don't have any certificate for the host, don't try to check the signature // Just return the parsed request if ($certificate == false) { return $payload; } // Does the signature match the data and the public cert? $signature_verified = openssl_verify($payload, $signature, $certificate); if ($signature_verified == 0) { // $signature was not generated for $payload using $certificate // Get the key the remote peer is currently publishing: $currkey = mnet_get_public_key($remoteclient->wwwroot, $remoteclient->application); // If the key the remote peer is currently publishing is different to $certificate if($currkey != $certificate) { // if pushkey is already set, it means the request was encrypted to an old key // in mnet_server_strip_encryption. // if we call refresh_key() here before pushing out our new key, // and the other site ALSO has a new key, // we'll get into an infinite keyswap loop // so push just bail here, and push out the new key. // the next request will get through to refresh_key if ($remoteclient->pushkey) { return false; } // Try and get the server's new key through trusted means $remoteclient->refresh_key(); // If we did manage to re-key, try to verify the signature again using the new public key. $certificate = $remoteclient->public_key; $signature_verified = openssl_verify($payload, $signature, $certificate); } } if ($signature_verified == 1) { $remoteclient->signature_verified(); $remoteclient->touch(); } $sig_parser->free_resource(); return $payload; } /** * Return the proper XML-RPC content to report an error in the local language. * * @param int $code The ID code of the error message * @param string $text The full string of the error message (get_string will <b>not be called</b>) * @param string $param The $a param for the error message in the lang file * @return string $text The text of the error message */ function mnet_server_fault($code, $text, $param = null) { if (!is_numeric($code)) { $code = 0; } $code = intval($code); return mnet_server_fault_xml($code, $text); } /** * Return the proper XML-RPC content to report an error. * * @param int $code The ID code of the error message * @param string $text The error message * @param resource $privatekey The private key that should be used to sign the response * @return string $text The XML text of the error message */ function mnet_server_fault_xml($code, $text, $privatekey = null) { global $CFG; // Replace illegal XML chars - is this already in a lib somewhere? $text = str_replace(array('<','>','&','"',"'"), array('<','>','&','"','''), $text); $return = mnet_server_prepare_response('<?xml version="1.0"?> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>'.$code.'</int></value> </member> <member> <name>faultString</name> <value><string>'.$text.'</string></value> </member> </struct> </value> </fault> </methodResponse>', $privatekey); if ($code != 7025) { // new key responses mnet_debug("XMLRPC Error Response $code: $text"); //mnet_debug($return); } return $return; } /** * Package a response in any required envelope, and return it to the client * * @param string $response The XMLRPC response string * @param resource $privatekey The private key to sign the response with * @return string The encoded response string */ function mnet_server_prepare_response($response, $privatekey = null) { $remoteclient = get_mnet_remote_client(); if ($remoteclient->request_was_signed) { $response = mnet_sign_message($response, $privatekey); } if ($remoteclient->request_was_encrypted) { $response = mnet_encrypt_message($response, $remoteclient->public_key); } return $response; } /** * If security checks are passed, dispatch the request to the function/method * * The config variable 'mnet_dispatcher_mode' can be: * strict: Only execute functions that are in specific files * off: The default - don't execute anything * * @param string $payload The XML-RPC request * * @throws mnet_server_exception * * @return No return val - just echo the response */ function mnet_server_dispatch($payload) { global $CFG, $DB; $remoteclient = get_mnet_remote_client(); // Decode the request to method + params. $method = null; $params = null; $encoder = new \PhpXmlRpc\Encoder(); $orequest = $encoder->decodeXML($payload); // First, to internal PhpXmlRpc\Response structure. if ($orequest && $orequest instanceof \PhpXmlRpc\Request) { $method = $orequest->method(); $numparams = $orequest->getNumParams(); for ($i = 0; $i < $numparams; $i++) { $params[] = $encoder->decode($orequest->getParam($i)); } } // $method is something like: "mod/forum/lib.php/forum_add_instance" // $params is an array of parameters. A parameter might itself be an array. // Check that the method name consists of allowed characters only. // The method name must not begin with a / - avoid absolute paths // A dot character . is only allowed in the filename, i.e. something.php if (0 == preg_match("@^[A-Za-z0-9]+/[A-Za-z0-9/_\.-]+(\.php/)?[A-Za-z0-9_-]+$@",$method)) { throw new mnet_server_exception(713, 'nosuchfunction'); } if(preg_match("/^system\./", $method)) { $callstack = explode('.', $method); } else { $callstack = explode('/', $method); // callstack will look like array('mod', 'forum', 'lib.php', 'forum_add_instance'); } /** * What has the site administrator chosen as his dispatcher setting? * strict: Only execute functions that are in specific files * off: The default - don't execute anything */ ////////////////////////////////////// OFF if (!isset($CFG->mnet_dispatcher_mode) ) { set_config('mnet_dispatcher_mode', 'off'); throw new mnet_server_exception(704, 'nosuchservice'); } elseif ('off' == $CFG->mnet_dispatcher_mode) { throw new mnet_server_exception(704, 'nosuchservice'); ////////////////////////////////////// SYSTEM METHODS } elseif ($callstack[0] == 'system') { $functionname = $callstack[1]; $xmlrpcserver = new \PhpXmlRpc\Server(); $xmlrpcserver->functions_parameters_type = 'epivals'; $xmlrpcserver->compress_response = false; // register all the system methods $systemmethods = array('listMethods', 'methodSignature', 'methodHelp', 'listServices', 'listFiles', 'retrieveFile', 'keyswap'); foreach ($systemmethods as $m) { // I'm adding the canonical xmlrpc references here, however we've // already forbidden that the period (.) should be allowed in the call // stack, so if someone tries to access our XMLRPC in the normal way, // they'll already have received a RPC server fault message. // Maybe we should allow an easement so that regular XMLRPC clients can // call our system methods, and find out what we have to offer? $handler = 'mnet_system'; if ($m == 'keyswap') { $handler = 'mnet_keyswap'; } if ($method == 'system.' . $m || $method == 'system/' . $m) { $xmlrpcserver->add_to_map($method, $handler); $xmlrpcserver->user_data = $remoteclient; $response = $xmlrpcserver->service($payload, true); $response = mnet_server_prepare_response($response); echo $response; return; } } throw new mnet_server_exception(7018, 'nosuchfunction'); //////////////////////////////////// NORMAL PLUGIN DISPATCHER } else { // anything else comes from some sort of plugin if ($rpcrecord = $DB->get_record('mnet_rpc', array('xmlrpcpath' => $method))) { $response = mnet_server_invoke_plugin_method($method, $callstack, $rpcrecord, $payload); $response = mnet_server_prepare_response($response); echo $response; return; // if the rpc record isn't found, check to see if dangerous mode is on ////////////////////////////////////// DANGEROUS } else if ('dangerous' == $CFG->mnet_dispatcher_mode && $remoteclient->plaintext_is_ok()) { $functionname = array_pop($callstack); $filename = clean_param(implode('/',$callstack), PARAM_PATH); if (0 == preg_match("/php$/", $filename)) { // Filename doesn't end in 'php'; possible attack? // Generate error response - unable to locate function throw new mnet_server_exception(7012, 'nosuchfunction'); } // The call stack holds the path to any include file $includefile = $CFG->dirroot.'/'.$filename; $response = mnet_server_invoke_dangerous_method($includefile, $functionname, $method, $payload); echo $response; return; } } throw new mnet_server_exception(7012, 'nosuchfunction'); } /** * Execute the system functions - mostly for introspection * * @param string $method XMLRPC method name, e.g. system.listMethods * @param array $params Array of parameters from the XMLRPC request * @param string $hostinfo Hostinfo object from the mnet_host table * * @throws mnet_server_exception * * @return mixed Response data - any kind of PHP variable */ function mnet_system($method, $params, $hostinfo) { global $CFG, $DB; if (empty($hostinfo)) return array(); $id_list = $hostinfo->id; if (!empty($CFG->mnet_all_hosts_id)) { $id_list .= ', '.$CFG->mnet_all_hosts_id; } if ('system.listMethods' == $method || 'system/listMethods' == $method) { $query = ' SELECT DISTINCT rpc.functionname, rpc.xmlrpcpath FROM {mnet_host2service} h2s JOIN {mnet_service2rpc} s2r ON h2s.serviceid = s2r.serviceid JOIN {mnet_rpc} rpc ON s2r.rpcid = rpc.id JOIN {mnet_service} svc ON svc.id = s2r.serviceid WHERE h2s.hostid in ('.$id_list .') AND h2s.publish = 1 AND rpc.enabled = 1 ' . ((count($params) > 0) ? 'AND svc.name = ? ' : '') . ' ORDER BY rpc.xmlrpcpath ASC'; if (count($params) > 0) { $params = array($params[0]); } $methods = array(); foreach ($DB->get_records_sql($query, $params) as $result) { $methods[] = $result->xmlrpcpath; } return $methods; } elseif (in_array($method, array('system.methodSignature', 'system/methodSignature', 'system.methodHelp', 'system/methodHelp'))) { $query = ' SELECT DISTINCT rpc.functionname, rpc.help, rpc.profile FROM {mnet_host2service} h2s, {mnet_service2rpc} s2r, {mnet_rpc} rpc WHERE rpc.xmlrpcpath = ? AND s2r.rpcid = rpc.id AND h2s.publish = 1 AND rpc.enabled = 1 AND h2s.serviceid = s2r.serviceid AND h2s.hostid in ('.$id_list .')'; $params = array($params[0]); if (!$result = $DB->get_record_sql($query, $params)) { return false; } if (strpos($method, 'methodSignature') !== false) { return unserialize($result->profile); } return $result->help; } elseif ('system.listServices' == $method || 'system/listServices' == $method) { $query = ' SELECT DISTINCT s.id, s.name, s.apiversion, h2s.publish, h2s.subscribe FROM {mnet_host2service} h2s, {mnet_service} s WHERE h2s.serviceid = s.id AND (h2s.publish = 1 OR h2s.subscribe = 1) AND h2s.hostid in ('.$id_list .') ORDER BY s.name ASC'; $params = array(); $result = $DB->get_records_sql($query, $params); $services = array(); if (is_array($result)) { foreach($result as $service) { $services[] = array('name' => $service->name, 'apiversion' => $service->apiversion, 'publish' => $service->publish, 'subscribe' => $service->subscribe); } } return $services; } throw new mnet_server_exception(7019, 'nosuchfunction'); } /** * Invoke a normal style plugin method * This will verify permissions first. * * @param string $method the full xmlrpc method that was called eg auth/mnet/auth.php/user_authorise * @param array $callstack the exploded callstack * @param stdclass $rpcrecord the record from mnet_rpc * * @return mixed the response from the invoked method */ function mnet_server_invoke_plugin_method($method, $callstack, $rpcrecord, $payload) { mnet_verify_permissions($rpcrecord); // will throw exceptions mnet_setup_dummy_method($method, $callstack, $rpcrecord); $methodname = array_pop($callstack); $xmlrpcserver = new \PhpXmlRpc\Server(); $xmlrpcserver->functions_parameters_type = 'epivals'; $xmlrpcserver->compress_response = false; $xmlrpcserver->add_to_map($method, 'mnet_server_dummy_method'); $xmlrpcserver->user_data = $methodname; $response = $xmlrpcserver->service($payload, true); return $response; } /** * Initialize the object (if necessary), execute the method or function, and * return the response * * @param string $includefile The file that contains the object definition * @param string $methodname The name of the method to execute * @param string $method The full path to the method * @param string $payload The XML-RPC request payload * @param string $class The name of the class to instantiate (or false) * * @throws mnet_server_exception * * @return string The XML-RPC response */ function mnet_server_invoke_dangerous_method($includefile, $methodname, $method, $payload) { if (file_exists($CFG->dirroot . $includefile)) { require_once $CFG->dirroot . $includefile; // $callprefix matches the rpc convention // of not having a leading slash $callprefix = preg_replace('!^/!', '', $includefile); } else { throw new mnet_server_exception(705, "nosuchfile"); } if ($functionname != clean_param($functionname, PARAM_PATH)) { throw new mnet_server_exception(7012, "nosuchfunction"); } if (!function_exists($functionname)) { throw new mnet_server_exception(7012, "nosuchfunction"); } $xmlrpcserver = new \PhpXmlRpc\Server(); $xmlrpcserver->functions_parameters_type = 'epivals'; $xmlrpcserver->compress_response = false; $xmlrpcserver->add_to_map($method, 'mnet_server_dummy_method'); $xmlrpcserver->user_data = $methodname; $response = $xmlrpcserver->service($payload, true); return $response; } /** * Accepts a public key from a new remote host and returns the public key for * this host. If 'register all hosts' is turned on, it will bootstrap a record * for the remote host in the mnet_host table (if it's not already there) * * @param string $function XML-RPC requires this but we don't... discard! * @param array $params Array of parameters * $params[0] is the remote wwwroot * $params[1] is the remote public key * @return string The XML-RPC response */ function mnet_keyswap($function, $params) { global $CFG; $return = array(); $mnet = get_mnet_environment(); if (!empty($CFG->mnet_register_allhosts)) { $mnet_peer = new mnet_peer(); list($wwwroot, $pubkey, $application) = $params; $keyok = $mnet_peer->bootstrap($wwwroot, $pubkey, $application); if ($keyok) { $mnet_peer->commit(); } } return $mnet->public_key; } /** * Verify that the requested xmlrpc method can be called * This just checks the method exists in the rpc table and is enabled. * * @param stdclass $rpcrecord the record from mnet_rpc * * @throws mnet_server_exception */ function mnet_verify_permissions($rpcrecord) { global $CFG, $DB; $remoteclient = get_mnet_remote_client(); $id_list = $remoteclient->id; if (!empty($CFG->mnet_all_hosts_id)) { $id_list .= ', '.$CFG->mnet_all_hosts_id; } // TODO: Change this to avoid the first column duplicate debugging, keeping current behaviour 100%. $sql = "SELECT r.*, h2s.publish FROM {mnet_rpc} r JOIN {mnet_service2rpc} s2r ON s2r.rpcid = r.id LEFT JOIN {mnet_host2service} h2s ON h2s.serviceid = s2r.serviceid WHERE r.id = ? AND h2s.hostid in ($id_list)"; $params = array($rpcrecord->id); if (!$permission = $DB->get_record_sql($sql, $params)) { throw new mnet_server_exception(7012, "nosuchfunction"); } else if (!$permission->publish || !$permission->enabled) { throw new mnet_server_exception(707, "nosuchfunction"); } } /** * Figure out exactly what needs to be called and stashes it in $remoteclient * Does some further verification that the method is callable * * @param string $method the full xmlrpc method that was called eg auth/mnet/auth.php/user_authorise * @param array $callstack the exploded callstack * @param stdclass $rpcrecord the record from mnet_rpc * * @throws mnet_server_exception */ function mnet_setup_dummy_method($method, $callstack, $rpcrecord) { global $CFG; $remoteclient = get_mnet_remote_client(); // verify that the callpath in the stack matches our records // callstack will look like array('mod', 'forum', 'lib.php', 'forum_add_instance'); $path = core_component::get_plugin_directory($rpcrecord->plugintype, $rpcrecord->pluginname); $path = substr($path, strlen($CFG->dirroot)+1); // this is a bit hacky and fragile, it is not guaranteed that plugins are in dirroot array_pop($callstack); $providedpath = implode('/', $callstack); if ($providedpath != $path . '/' . $rpcrecord->filename) { throw new mnet_server_exception(705, "nosuchfile"); } if (!file_exists($CFG->dirroot . '/' . $providedpath)) { throw new mnet_server_exception(705, "nosuchfile"); } require_once($CFG->dirroot . '/' . $providedpath); if (!empty($rpcrecord->classname)) { if (!class_exists($rpcrecord->classname)) { throw new mnet_server_exception(708, 'nosuchclass'); } if (!$rpcrecord->static) { try { $object = new $rpcrecord->classname; } catch (Exception $e) { throw new mnet_server_exception(709, "classerror"); } if (!is_callable(array($object, $rpcrecord->functionname))) { throw new mnet_server_exception(706, "nosuchfunction"); } $remoteclient->object_to_call($object); } else { if (!is_callable(array($rpcrecord->classname, $rpcrecord->functionname))) { throw new mnet_server_exception(706, "nosuchfunction"); } $remoteclient->static_location($rpcrecord->classname); } } } /** * Dummy function for the XML-RPC dispatcher - use to call a method on an object * or to call a function * * Translate XML-RPC's strange function call syntax into a more straightforward * PHP-friendly alternative. This dummy function will be called by the * dispatcher, and can be used to call a method on an object, or just a function * * The methodName argument (eg. mnet/testlib/mnet_concatenate_strings) * is ignored. * * @throws mnet_server_exception * * @param string $methodname We discard this - see 'functionname' * @param array $argsarray Each element is an argument to the real * function * @param string $functionname The name of the PHP function you want to call * @return mixed The return value will be that of the real * function, whatever it may be. */ function mnet_server_dummy_method($methodname, $argsarray, $functionname) { $remoteclient = get_mnet_remote_client(); try { if (is_object($remoteclient->object_to_call)) { return @call_user_func_array(array($remoteclient->object_to_call,$functionname), $argsarray); } else if (!empty($remoteclient->static_location)) { return @call_user_func_array(array($remoteclient->static_location, $functionname), $argsarray); } else { return @call_user_func_array($functionname, $argsarray); } } catch (Exception $e) { exit(mnet_server_fault($e->getCode(), $e->getMessage())); } } /** * mnet server exception. extends moodle_exception, but takes slightly different arguments. * and unlike the rest of moodle, the actual int error code is used. * this exception should only be used during an xmlrpc server request, ie, not for client requests. */ class mnet_server_exception extends moodle_exception { /** * @param int $intcode the numerical error associated with this fault. this is <b>not</b> the string errorcode * @param string $langkey the error message in full (<b>get_string will not be used</b>) * @param string $module the language module, defaults to 'mnet' * @param mixed $a params for get_string */ public function __construct($intcode, $languagekey, $module='mnet', $a=null) { parent::__construct($languagekey, $module, '', $a); $this->code = $intcode; } } server.php 0000644 00000010177 15151174117 0006574 0 ustar 00 <?php /** * An XML-RPC server * * @author Donal McMullan donal@catalyst.net.nz * @version 0.0.1 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package mnet */ // Make certain that config.php doesn't display any errors, and that it doesn't // override our do-not-display-errors setting: // disable moodle specific debug messages and any errors in output define('NO_DEBUG_DISPLAY', true); // cookies are not used, makes sure there is empty global $USER define('NO_MOODLE_COOKIES', true); define('MNET_SERVER', true); require(__DIR__.'/../../config.php'); $mnet = get_mnet_environment(); // Include MNET stuff: require_once $CFG->dirroot.'/mnet/lib.php'; require_once $CFG->dirroot.'/mnet/remote_client.php'; require_once $CFG->dirroot.'/mnet/xmlrpc/serverlib.php'; if ($CFG->mnet_dispatcher_mode === 'off') { throw new \moodle_exception('mnetdisabled', 'mnet'); } // Content type for output is not html: header('Content-type: text/xml; charset=utf-8'); $rawpostdata = file_get_contents("php://input"); mnet_debug("RAW POST DATA", 2); mnet_debug($rawpostdata, 2); if (!isset($_SERVER)) { exit(mnet_server_fault(712, get_string('phperror', 'mnet'))); } // New global variable which ONLY gets set in this server page, so you know that // if you've been called by a remote Moodle, this should be set: $remoteclient = new mnet_remote_client(); set_mnet_remote_client($remoteclient); try { $plaintextmessage = mnet_server_strip_encryption($rawpostdata); $xmlrpcrequest = mnet_server_strip_signature($plaintextmessage); } catch (Exception $e) { mnet_debug('encryption strip exception thrown: ' . $e->getMessage()); exit(mnet_server_fault($e->getCode(), $e->getMessage(), $e->a)); } mnet_debug('XMLRPC Payload', 2); mnet_debug($xmlrpcrequest, 2); if($remoteclient->pushkey == true) { // The peer used one of our older public keys, we will return a // signed/encrypted error message containing our new public key // Sign message with our old key, and encrypt to the peer's private key. mnet_debug('sending back new key'); exit(mnet_server_fault_xml(7025, $mnet->public_key, $remoteclient->useprivatekey)); } // Have a peek at what the request would be if we were to process it $encoder = new \PhpXmlRpc\Encoder(); $orequest = $encoder->decodeXML($xmlrpcrequest); // First, to internal. $method = $orequest->method(); // We just need the method. mnet_debug("incoming mnet request $method"); // One of three conditions need to be met before we continue processing this request: // 1. Request is properly encrypted and signed // 2. Request is for a keyswap (we don't mind enencrypted or unsigned requests for a public key) // 3. Request is properly signed and we're happy with it being unencrypted if ((($remoteclient->request_was_encrypted == true) && ($remoteclient->signatureok == true)) || (($method == 'system.keyswap') || ($method == 'system/keyswap')) || (($remoteclient->signatureok == true) && ($remoteclient->plaintext_is_ok() == true))) { try { // main dispatch call. will echo the response directly mnet_server_dispatch($xmlrpcrequest); mnet_debug('exiting cleanly'); exit; } catch (Exception $e) { mnet_debug('dispatch exception thrown: ' . $e->getMessage()); exit(mnet_server_fault($e->getCode(), $e->getMessage(), $e->a)); } } // if we get to here, something is wrong // so detect a few common cases and send appropriate errors if (($remoteclient->request_was_encrypted == false) && ($remoteclient->plaintext_is_ok() == false)) { mnet_debug('non encrypted request'); exit(mnet_server_fault(7021, get_string('forbidden-transport', 'mnet'))); } if ($remoteclient->request_was_signed == false) { // Request was not signed mnet_debug('non signed request'); exit(mnet_server_fault(711, get_string('verifysignature-error', 'mnet'))); } if ($remoteclient->signatureok == false) { // We were unable to verify the signature mnet_debug('non verified signature'); exit(mnet_server_fault(710, get_string('verifysignature-invalid', 'mnet'))); } mnet_debug('unknown error'); exit(mnet_server_fault(7000, get_string('unknownerror', 'mnet')));
| ver. 1.4 |
Github
|
.
| PHP 7.4.33 | ���֧ߧ֧�ѧ�ڧ� ����ѧߧڧ��: 0 |
proxy
|
phpinfo
|
���ѧ����ۧܧ�