Змагання з програмування. Змагання з програмування Відключення XML-RPC у WordPress

  • Support for creating both xmlrpc clients and servers
  • Fully automated or fully manual, fine-grained encoding and decoding from php values ​​to xmlrpc
  • Додаток для UTF8, Latin-1 and ASCII character encodings. З php mbstring extension enabled, even more character sets are supported.
  • Support for http compression of requests and responses, cookies, proxies, basic auth and https, ntlm auth and keepalives with the php cURL extension
  • Optional validation of parameter types of incoming xmlrpc request
  • Support for system.listMethods, system.methodHelp, system.multicall and system.getCapabilities methods
  • Support for the and extensions to xmlrpc
  • Можливості для реєстру existing php function or class methods as webservices, extracting value-added information from phpdoc comments
  • A web based visual debugger is included with the library

Requirements

  • PHP 5.3.0 or later; 5.5 or later recommended
  • php "curl" extension is needed if you wish to use SSL or HTTP 1.1 to communicate with remote servers
  • php "mbstring" extension is needed to allow reception of requests/responses in character sets other than ASCII, Latin-1, UTF-8
  • php "xmlrpc" природне розширення не вимагається, але якщо він налаштований, буде не interference with operation of this library.

Download

News

  • 1st of July, 2017
    Released lib versions 4.2.0 та 3.1.0.
    The release notes є available on Github
  • 20th of January, 2016
    Released lib version 4.0.0
    Це перший час - ще - що API повідомила про великі зміни, робиться з past і starts a transition to modern-day php.
    Namespaces має бути введений, а потім значок параметра, використовуючи UTF-8; support for mbstring has been added, and much more.
    Для повного списку змін, head on to on Github
  • 19th of April, 2015
    Released lib version 3.0.1.
  • 15th of June, 2014
    Released lib version 3.0.0.
  • 15th of December, 2013
    Project moved to GitHub

    Online xmlrpc debugger

    A demo xmlrpc debugger application, побудови на стовпці цієї library, є активним at the address http://gggeek.altervista.org/sw/xmlrpc/debugger/ . Ви можете використовувати debugger to e.g. Будучи SF-демо-сервер, або розробка вашого індивідуального xmlrpc-сервер, якщо це accessible на мережі.

    Development

    DescriptionStatus - updated 2009/07/26
    Update documentation for all features added since version 2Slowly progressing...
    Add the possibility to choose formatting of the xml messagesSimilar to what the php native xmlrpc extension does
    Fix warnings emitted when running with PHP 5 in STRICT modeMight have already been done in version 3.0, abandoning php 4 compat...
    Експлуатація автоматичного php функція до методу xmlrpc wrapper до того, щоб виявити, що виключення знижок і відновлення xmlrpc error responses
    Expand автоматичний stub generator for automatically converting php functions to xmlrpc methods for PHP<= 5.0.2 look at AMFPHP code on how to do it.
    Багато вправ у версії 2.1
    Now that the server can automatically register php functions there is less need for it...
    Better support for mbstring when it"s enabledShould make e.g. charset encoding guessing faster
    Improve support for "version 1" cookies
    Add a possibility to use instead of the native error codes
    PEAR compatibility: add synonyms для функцій existing with different names in the PEAR version of the lib
    Add support for the xmlrpc extension
    Add to debugger the capability to launch complete set of validator1 tests
    Досвідчений спосіб WSDL для створення повідомлень, розміщених і перехід до/від system.methodSignature and system.describeMethodsКілька проблем exist in using an XSD to strictly define xmlrpc. Relax NG є певною мірою альтернативною, але є малою підтримкою в інших інструментах для використання її в спільній роботі з WSDL файлом...
    Support http redirects (302)
    Add to sf.net для малого database, тому що ми можемо реалізувати validator сторінку, що logs incoming users, such as is present on the xmlrpc.com site
    Add to benchmark suite capability to upload results to sf.net
    Write a php extension that will accelerate the most heavily used functions of the libSee how adodb did it for an example
    Test speed/memory gains using simplexml and relaxng instead of hand parsing of xml

    Security

    The third security breach: srpen 2005

    Це було як простір, так і сприятливе відображення до другої безпеки breach below. All use of eval() has been removed since it still a potential exploit.

    Коли library був орієнтовно написаний, versions php available at time did не включає call_user_func(), et al. So it was written within those constraints to use eval() in 2 of functions called by the xml parser. Due to this usage, the class server also used eval() since it had to parse xml using the same functions.

    Ці функції функція, і array використовується для вмісту вмісту оригіналу, має бути rewritten to construct php values ​​instead of building php code for evaluation. Це повинно скористатися будь-яким потенційним кодом execution.

    The second security breach: липень 2005

    Безпека vulnerability затверджена James Bercegay of GulfTech Security Research on the 27th of June, 2005, has caused quite a stir. Це має бути на цій сторінці Salshdot, буде mentioned на Netcraft, LWN і багато інших підприємств.

    Подібні інструкції на будівництві exploit code мають бути повідомлені на Інтернеті, і багато web hosting administrators є більшою задовільною те, що є кращим замахом плану, і скільки реальних ризиків. Here are some answers.

    Scope of the problem

    • the bug affects the 2 libraries відомі як PEAR::XMLRPC and PHPXMLRMPC.
      ІТ DOES NOT affect the xmlrpc implementation which is built-in in php and enabled at compile time with "--with-xmlrpc" option (у Unix, on windows generally it is enabled/disabled by changing the appropriate line in php. )
    • bug (execution of php-code injected by remote hosts) resides exclusivamente in the file xmlrpc.inc in the phpxmlrpc distribution and RPC.php in the PEAR distribution
    • both PEAR::XMLRPC and PHPXMLRMPC має відповідні updated versions of library that fix the problem
    • both libraries має бути використані в великій кількості php applications (see the incomplete list above).
      Залишити повну lib основи basically of 2 very simple files, everybody tends to patch them according to its own tastes/needs and bundle them when distributing their app.
      Most high-profile проекти мають дуже швидке введення нових версій своїх специфічних apps, але це буде дуже довгий час для кожного першого користувача до оновлення його системи.
      It has to be said that many applications had been shipping until recently with extremely outdated versions the phpxmlrpc library included; a first injection bug had been fixed in 2001без будь-якого apparently taking notice (...)

      Це робить його незрівнянно багатим harder для sysadmins для того, щоб легко розв'язати проблему: вони є великим шансом, що на public hosting servers the aforementioned files буде бути в багатьох різних directories і в різних versions.

    How the vulnerability is triggered

    • до trigger the bug an attacker needs to have some specially crafted xml evaluated in the creation process of xmlrpcval object. Xmlrpcval об'єкти створені при script server decodes xmlrpc requests when some php scripts acts as xmlrpc client and decodes a response sent by a server.
      Server script is specific application, and it is often named server.php (but any project- or user-chosen variant is possible), and it has include both xmlrpc.inc and xmlrpcs.inc files (for the pear version, server .php is the equivalent of xmlrpcs.inc).
    • Тільки включаючи xmlrpc.inc і xmlrpcs.inc в php scripts is (afaik...) повністю безпечні, як добре беруться за ними прямо http http, винятково тільки definition of functions, variables and classes is carried out in those two files, i.e. no immediate code execution.
    • На сервері. mind I can conjure some kind of attack involving a second php app suffering of a takeover-php-file-inclusion breach to pull them in + exploit the lib known bug)

    Means of protection

    • Give your web server process as little system privileges as you can. На Unix ця загальна безперервна робота Apache як user nobody and/or in jailrooted/chrooted environment. Since the PHP engine runs un same user as the web server, this is the first line of defense: any php code injected by attacker will run on the server as a least privileged user, and all damage it could do will be limited to disrupting the php application itself
    • Run php in safe mode. Якщо ви є громадським host і не є тим, що зміни є ваш сервер має бути rooted anyway. Ці помилки php scripts з використанням будь-якої функції ви можете продовжувати, так як system() or eval()
    • hard block: досліджувати всі існуючі phpxmlrpc файли (xmlrpc.inc and xmlrpcs.inc) and disable them (chmod 0) across the system.
      Це може бути випробувань, щоб деякі applications від роботи з вашим вимагають, щоб ваші користувачі at the time you do it.
    • Soft block: replace all copies з існуючих phpxmlrpc файлів (xmlrpc.inc and xmlrpcs.inc) with the ones coming from version 1.1.1.
      Цей метод є unfortunately not 100% guaranteed to keep all apps working. Деякі міжнародні lib об'єкти змінюються від версії 0.9 to 1.0 to 1.1 (e.g. representation of http headers stored inside xmlrpcresp object), і якщо код ви будете розміщені на ваших серверах subclasses them, it might find itself The xml sent over-the-wire має змінити те, що з іншими до versions of the lib (в particular: version 1.0.99.2 wrongly encoded chars outside the ASCII range as html entities, whereas now they are encoded as xml char. A couple of new error response codes have been added, too. Having said that, you should be 95% safe running that script and sit there waiting for users to start yelling something is broken...
    • the PHP PEAR library is upgradeable with a one-line command, so that's not really a huge problem:
      pear upgrade XML_RPC і до того, що це"буде upgraded (1.3.1 or later is OK, latest as now is 1.3.2):
      pear list | grep RPC

    Деякі extra considerations

    File xmlrpcs.inc має бути виконаний у виконанні 1.1.1 для отримання додаткових користувачів. У більш глибокій точці: зображення спеціально розроблене malformed xml до сервера може призвести до script php до виходу php помилка досліджує відновлення відповідного xml response.
    Залежно від цього, це актуально значки на " path disclosure security breach " (ie the php error message displayed usually contains sensitive information about filesystem paths), but the any single PHP script suffers of the same security problem if the sysadmin isn the ini directive display_errors=Он.
    Я також знаю, що є те, що є багато місць в xmlrpc.inc, де calling функцією з невизначеним параметром буде генерувати php warning or error, і я не маю планування до implement strict parametr check for every single function anytime soon - if y aim for that, imho, you might як добре код в java в першому місці.

    Is this the end of the world?

    I hope not.
    reason is there are tens of PHP applications out there that suffer from code injection exploits. Just take look at the security track of bulletin boards... and yet a lot of people thill think PHP is a good choice for web development.
    Remember: security is a process, не state that can be reached.

    The first security breach: september 2001

    Я отримував цей посланець від Dan Libby. With his permission it is reproduced here. Зверніть увагу, що цей розкриває fixed in revisions 1.01 і розширення XML-RPC для PHP. -- Edd Dumbill Tue Sep 24 2001 =============== PHP Security Hole: potential XML-RPC exploit ================== ========================== Abstract: Using the latest release of Useful Inc's php xmlrpc library, version 1.0, it is possible for an attacker структурувати xml в такій мірі, як trick xml-rpc library in executing php code на веб-сервері. Якщо attacker можна легко використовувати це як браузер для захисту viruses. Докладніше: Я розглянув проблему, спрямовану на зміну сервера. Ipassed the standard server code, and simply echo"d відповіді back to the client. request.I був також able to make code execute on the server, albeit requiring a slightly different syntax. Since I knew that the xml-rpc library uses eval to construct its data structures from xml input, it was just mater of structuring the input xml in such a manner that it: a) is not escaped before being passed to eval b) does no generate a php syntax error Normally, all non numeric data is escaped by the library before being passed to eval. However, it turns out that if you send a tag, що випливає з unexpected tag, such as , The escaping code will be bypassed and "raw" data will be evaluated instead. Exploiting the client: Here is a typical xml-rpc response: hello world Якщо така відповідь є eval"ed, it looks like: new xmlrpcval("hello world", "string") Here is an xml-rpc response what execute php code to echo "

    hello world

    on the client side: ", "string"); echo "

    hello world

    "; \$waste = array("
    У цьому випадку, string that will be eval"ed is: new xmlrpcval("", "string"); echo "

    hello world

    "; $waste = array("", "string") Це може бути заміна всього між "string"); and \$waste with arbitrary code of just about any length. Finally, here"s one that will print the contents of the current directory: ", "string"); echo "

    echo `ls -al`; echo

    "; exit; \$waste = array("
    Exploiting the server: The server exploit is just about the same as the client, except that the server is using a different eval command, and thus it requires slightly different begin and ending syntax to avoid php syntax errors. Тут є той самий код, що надсилається, але це буде працювати на сервері. system.listMethods ", "string")); echo "

    if you see a directory listing, I just executed php and system code via xml-rpc.

    "; echo "now I will attempt a directory listing using ls -al:\n echo `ls -al`; echo"; echo "Я можу, щоб у будь-якому випадку ввійшли в rm -rf, або писали про програму для диска і executed it (eg, a virus) або read some files. Have a nice day.

    "; exit; $waste = array(array("
    Проблема регіону: в xmlrpc.inc, є функцією, що називається xmlrpc_cd(), яка називається xml parser to handle character data. function xmlrpc_cd($parser, $data) ( global $_xh, $xmlrpc_backslash, $xmlrpc_twoslash; //if (ereg("^[\n\r \t]+$", $data)) return; // print " adding [$(data)]\n"; if ($_xh[$parser]["lv"]==1) ( $_xh[$parser]["qt"]=1; $_xh[$parser][ "lv"]=2; ) if ($_xh[$parser]["qt"]) ( // quoted string $_xh[$parser]["ac"].=str_replace("\$", "\\ $", str_replace(""", "\"", str_replace(chr(92),$xmlrpc_backslash, $data))); ) else $_xh[$parser]["ac"].=$data; ) It is the last else that is causing data to be added without escaping. It is very dangerous to have this. Це вмикається, щоб бути встановленим для numerical data, і великі штрихи є, щоб встановити і розмістити "qt" (quote) variable which turns escaping on and off. However, it not immediately apparent to me why numerical data should not be similarly escaped, and the if/else removed, such that there is zero chance for this type of exploit.

Використання XML-RPC у PHP для публікації матеріалів у LiveJournal.com (ЖЖ)

Для початку вам потрібно завантажити бібліотеку XML-RPC. Найбільш вдалою версією мені здається вільно розповсюджувана через sourceforge " ": Всі приклади нижче будуть наведені для цієї бібліотеки версії 2.2.

Що таке XML-RPC? RPC розшифровується як Remote Procedure Call, відповідно російською це можна перекласти як віддалений виклик процедур за допомогою XML. Сама методика віддаленого виклику процедури відома давно і використовується в таких технологіях як DCOM, SOAP, CORBA. RPC призначений для побудови розподілених клієнт-серверних програм. Це дає можливість будувати програми, які працюють у гетерогенних мережах, наприклад, на комп'ютерах різних систем, проводити віддалену обробку даних та керування віддаленими програмами. Зокрема, цим протоколом користується добре відомий в Росії сайт livejournal.com.

Розглянемо приклад, як можна розмістити кириличний запис (а саме із цим часто виникають проблеми) у ЖЖ. Нижче наведено працюючий код із коментарями:

new xmlrpcval($name, "string"), "password" => new xmlrpcval($password, "string"), "event" => new xmlrpcval($text, "string"), "subject" => new xmlrpcval ($subj, "string"), "lineendings" => new xmlrpcval("unix", "string"), "year" => new xmlrpcval($year, "int"), "mon" => new xmlrpcval( $mon, "int"), "day" => new xmlrpcval($day, "int"), "hour" => new xmlrpcval($hour, "int"), "min" => new xmlrpcval($min , "int"), "ver" => new xmlrpcval(2, "int")); /* на основі масиву створюємо структуру */ $post2 = array(new xmlrpcval($post, "struct")); /* створюємо XML повідомлення для сервера */ $f = new xmlrpcmsg("LJ.XMLRPC.postevent", $post2); /* описуємо сервер */ $c = new xmlrpc_client("/interface/xmlrpc", "www.livejournal.com", 80); $c->request_charset_encoding = "UTF-8"; /* за бажанням дивимося на XML-код того що відправиться на сервер */ echo nl2br(htmlentities($f->serialize())); /* надсилаємо XML повідомлення на сервер */ $r = $c->send($f); /* аналізуємо результат */ if(!$r->faultCode()) ( /* повідомлення прийнято успішно і повернувся XML-результат */ $v = php_xmlrpc_decode($r->value()); print_r($v); ) else ( /* сервер повернув помилку */ print "An error occurred: "; print "Code: ".htmlspecialchars($r->faultCode()); print "Reason: "".htmlspecialchars($r->faultString( )).""\n"; ) ?>

У даному прикладі розглянуто лише один метод LJ.XMLRPC.postevent - повний список можливих команд та їх синтаксис (англійською мовою) доступний за адресою:

З полудня суботи на моєму сервері, де хоститься близько 25 сайтів на Wordpress, почалися дикі гальма. Так як мені вдалося пережити попередні атаки (атака 1 - рівно рік тому, атака 2 - у березні) не поміченими, то я не відразу зрозумів, у чому справа.

Коли розібрався, з'ясувалося, що йде перебір паролів + безліч запитів до XMLRPC.

В результаті вдалося все це відсікти, хоча і не відразу. По катом три простих прийоми, як цього уникнути.

Ці прийоми швидше за все відомі, але я наступив на пару граблів, яких не знайшов в описах - раптом це комусь заощадить час.

1. Зупиняємо перебір, плагін Limit Login Attempts - ставимо саме його, тому що інші захисту сильно підвішують сервер, наприклад, при використанні плагіну Login Security Solution сервер помер через півгодини, плагін сильно вантажить базу.

У налаштуванні обов'язково увімкніть галочку «За проксі» - інакше він для всіх визначатиме ip вашого сервера і автоматично блокуватиме всіх.
UPDATE, дякую DarkByte , подробиці нижче в коментарях - галочку «За проксі» включаємо тільки якщо не працює визначення при включеному «Пряме підключення»

2. Відключаємо XML-RPC – плагін Disable XML-RPC (його просто активувати і все).

3. Закриваємо wp-login.php – якщо звертатися до сайту через ip, то плагін не спрацьовує і підбирачі продовжують довбати сайт. Щоб цього уникнути, в.htaccess додаємо:

Order Deny,Allow Deny from all

Файл wp-login копіюємо, перейменовуємо в будь-яке дивне ім'я, наприклад, poletnormalny.php і всередині файлу автозаміною міняємо всі написи wp-login.php на poletnormalny.php.
Все, тепер до адмінки можна звернутися лише за вашим файлом.

Після цих трьох нескладних кроків сайти знову почали літати і прийшов спокій.

Ну і раптом цікаво

Один із варіантів як подивитися, що вас атакують. Це можна побачити в логах nginx (наприклад, шлях для Debian /var/log/nginx файл access.log).
His post also shows how to do browser authentication, as below:
$request = xmlrpc_encode_request ("methodName", array("methodParam"));
$auth = base64_encode ($username . ":" . $password );
$header = (version_compare (phpversion (), "5.2.8"))
? array("Content-Type: text/xml" , "Authorization: Basic $auth " )
: "Content-Type: text/xml\r\nAuthorization: Basic$ auth "; //
$context = stream_context_create (array("http" => array(
"method" => "POST" ,
"header" => $header ,
"content" => $request
)));
$webservice = "http://www.example.com/rpc";
$file = file_get_contents ($webservice, false, $context);
$response = xmlrpc_decode ($file);
if (xmlrpc_is_fault ($response )) (
return "xmlrpc: $response [ faultString ] ($response [ faultCode ] )" ;
) else (
return $response;
}
?>
1 - EDITOR NOTE: THIS IS A FIX FROM "SandersWang dt php at gmail dot com"

16 років тому

Binary strings (set with xmlrpc_set_type) go into a ...block like you"d expect. Але після кожного 80-го характеру, це функція містить XML entity " ", який є Unicode Newline, як це спричинить line-wrap, який є належним чином.

Цілком це може бути, це причини реальних проблем для деяких XML-RPC servers, так як http://jakarta.apache.org/xmlrpc/ (nee Helma). Stripping out those entities with something like

$req = preg_replace("//", "", xmlrpc_encode_request("my.method", $args));

works around the problem.

11 років тому

Це повинно бути усвідомлено, що скасовується, що не нагадує будь-який, just specify what goes into XML header.

Будь-які проблеми з двома-накопичуваними UTF strings, які використовуються для вашого database, коли використовується ця функція, за допомогою цього apache xml-rpc servlet and storing it in mysql database. Це було вирішено, щоб налаштувати "escaping" на just "markup" і "encoding" на "UTF-8".

Це seems, що UTF-8 шифровані strings gets escaped with thes bytes as entities instead of their characters as entites.

9 років тому

Ever tried transmitting an array як following with xmlrpc?
$ var1 = array (7 => 14,9 => 18);

output array looks quite different! It will look like that:
$ var2 = array (14,18);

Тільки Solution i Found is to prepend a space to the index:
$var3=array("7"=>14,"9"=>18);

Використовуючи цей метод, ви можете отримати правильний результат. ($var1)

16 років тому

Ця функція повинна бути використана за допомогою XML-RPC клієнта для створення XML payload for XML-RPC request;

$params = "system.methodSignature" ;
$method = "system.methodHelp";
$request = xmlrpc_encode_request ($method, $params);
echo ($ request);
?>

Produces;



system.methodHelp

system.methodSignature



Second argument recognises the type of variable і генерує стратегії XML-RPC структури. See xmlrpc_encode() for more details.

12 років тому

Simple OO client with function Overload:

the php metho test_helloworld is translated to xmlrpc method test.helloworld.

class RpcClient (

Private $_methods;
private $_context;
private $_url;

Function __construct ($url, $user, $passwd) (
$auth = base64_encode(sprintf("%s:%s", $user,$passwd));
$this->_context = stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: text/xml\r\n".
"Authorization: Basic $auth" ,

)
));
$this->_url = $url;

$this->registerMethod ("Test_HelloWorld");

Function __call($methodName, $params) (
if (array_key_exists($methodName,$this->_methods)) (
// on appelle la fonction RPC
$m = str_replace("_", ".", $methodName);
$r = xmlrpc_encode_request($m, $params,array("verbosity"=>"newlines_only"));
$c = $this->_context;
stream_context_set_option($c,"http","content",$r);
$f = file_get_contents($this->_url,false,$c);
$resp = xmlrpc_decode($f);
return $resp;
) else (
// on appelle la fonction de l"objet
call_user_method_array($methodName, $this,$params);
}
}

Private function registerMethod ($method) (
$this->_methods[$method] = true;
}

Технологія XML-RPC застосовується в системі WordPress для різних приємних фішок на кшталт пінгбеків, трекбеків, віддаленого керування сайтом без входу в адмінку тощо. На жаль, зловмисники можуть використовувати її для атаки DDoS на сайти. Тобто ви створюєте красиві цікаві WP проекти для себе або на замовлення і при цьому, нічого не підозрюючи, можете бути частиною ботнета для DDoS`а. Об'єднуючи докупи десятки і сотні тисяч майданчиків, погані люди створюють потужну атаку на свою жертву. Хоча ваш сайт також страждає, т.к. навантаження йде на хостинг, де його розміщено.

Свідченням такої негативної активності можуть бути логи сервера (access.log в nginx), що містять такі рядки:

103.238.80.27 - - "POST /wp-login.php HTTP/1.0" 200 5791 "-" "-"

Але повернемося до вразливості XML-RPC. Візуально вона проявляється у повільному відкритті сайтів на вашому сервері або ж неможливістю їх завантаження взагалі (502 помилка Bad Gateway). У тех.підтримці мого хостера FASTVPS підтвердили припущення і порадили:

  1. Обновити WordPress до останньої версії разом із плагінами. Взагалі, якщо ви стежите за , то могли читати необхідність установки останньої 4.2.3. через критичні зауваження в безпеці (так само як і попередні версії). Коротше кажучи, корисно оновлюватися.
  1. Встановити плагін Disable XML-RPC Pingback.

Відключення XML-RPC у WordPress

Раніше, як мені здається, опція увімкнення/вимкнення XML-RPC була десь у налаштуваннях системи, проте зараз не можу її там знайти. Тому найпростіший спосіб позбутися від неї — використовувати відповідний плагін.

Знайти та завантажити Disable XML-RPC Pingback або встановивши його безпосередньо з адмінки системи. Вам не потрібно нічого додатково налаштовувати, модуль відразу починає працювати. Він видаляє методи pingback.ping та pingback.extensions.getPingbacks з інтерфейсу XML-RPC. Крім того, видаляє X-Pingback із HTTP заголовків.

В одному з блогів знайшов ще кілька варіантів видалення відключення XML-RPC.

1. Вимкнення XML-RPC у шаблоні.

Для цього у файл функцій теми functions.php додається рядок:

Order Deny,Allow Deny from all

Останні два методи особисто не використовував, т.к. підключив плагін Disable XML-RPC Pingback - думаю, його буде достатньо. Просто для тих, хто не любить зайві настанови, запропонував альтернативні варіанти.