Cloudflare.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <?php
  2. namespace MGModule\DNSManager2\mgLibs\custom\dns\submodules;
  3. use MGModule\DNSManager2\mgLibs\custom\dns;
  4. use MGModule\DNSManager2\mgLibs\custom\dns\exceptions;
  5. use MGModule\DNSManager2\mgLibs\custom\dns\interfaces;
  6. use MGModule\DNSManager2\mgLibs\custom\dns\interfaces\SubmoduleDNSSecInterface;
  7. use \Exception;
  8. class Cloudflare extends dns\SubmoduleAbstract implements
  9. interfaces\SubmoduleIPInterface, interfaces\SubmoduleTTLInterface, interfaces\SubmoduleImportInterface,SubmoduleDNSSecInterface
  10. {
  11. protected $hostname = 'https://api.cloudflare.com/client/v4/';
  12. public $configFields = array(
  13. 'email' => array(
  14. 'friendlyName' => 'Email',
  15. 'validators' => array(
  16. 'required' => 'required',
  17. )
  18. ),
  19. 'key' => array(
  20. 'friendlyName' => 'API Key',
  21. 'type' => 'password'
  22. ),
  23. 'token' => [
  24. 'friendlyName' => 'API Token',
  25. 'type' => 'password'
  26. ],
  27. 'proxied' =>array (
  28. 'friendlyName' => 'Enable Proxy Option For Records',
  29. 'type'=> 'yesno',
  30. 'help' => 'For A, AAAA, CNAME records only',
  31. ),
  32. );
  33. public $availableTypes = ['A', 'AAAA', 'CAA', 'CNAME', 'DS', 'MX', 'NS', 'SRV', 'TXT'];
  34. protected $zoneid;
  35. protected $zoneObj;
  36. public function testConnection()
  37. {
  38. $info = $this->get( 'user', array() );
  39. return $info->result ? true : false;
  40. }
  41. public function zoneExists()
  42. {
  43. try {
  44. $zone = $this->getZone( $this->domain );
  45. } catch (exceptions\DNSSubmoduleException $e) {
  46. if ( $e->getCode() == dns\SubmoduleExceptionCodes::COMMAND_ERROR )
  47. {
  48. return false;
  49. }
  50. throw $e;
  51. }
  52. return ($zone) ? true : false;
  53. }
  54. public function getNameServers($index = false)
  55. {
  56. $zone = $this->getZone($this->domain);
  57. return $zone->name_servers;
  58. }
  59. public function getRecords( $recordType = false )
  60. {
  61. $out = $this->getAllRecords();
  62. $return = [];
  63. foreach( $out as $item )
  64. {
  65. $item->name = rtrim($item->name,'.').'.';
  66. $type = strtoupper((string)$item->type);
  67. if( in_array($type, $recordType !== false ? [strtoupper($recordType)] : $this->getAvailableRecordTypes(),true) )
  68. {
  69. switch( $type )
  70. {
  71. case 'MX':
  72. $record = dns\record\Record::tryToCreateFromArray((array)$item);
  73. $record->line = (string)$item->id;
  74. $record->rdata->preference = $item->priority;
  75. $record->rdata->exchange = $item->content;
  76. $return[] = $record;
  77. break;
  78. case 'SRV':
  79. $record = dns\record\Record::tryToCreateFromArray((array)$item);
  80. $record->line = (string)$item->id;
  81. $record->rdata->port = $item->data->port;
  82. $record->rdata->weight = $item->data->weight;
  83. $record->rdata->priority = $item->data->priority;
  84. $record->rdata->target = $item->data->target;
  85. $record->name = $item->data->service . '.' . $item->data->proto . '.' . $item->data->name;
  86. $record->absoluteName = false;
  87. $return[] = $record;
  88. break;
  89. case 'DS':
  90. $record = dns\record\Record::tryToCreateFromArray((array)$item);
  91. $record->line = (string)$item->id;
  92. $rdata = new dns\record\type\DS();
  93. list($rdata->keytag, $rdata->algorithm, $rdata->digesttype, $rdata->digest) = explode("\t", $item->content);
  94. $record->rdata = $rdata;
  95. $return[] = $record;
  96. break;
  97. default:
  98. $record = dns\record\Record::tryToCreateFromArray((array)$item);
  99. $record->line = (string)$item->id;
  100. $record->rdata->fromString((string)$item->content);
  101. $return[] = $record;
  102. }
  103. }
  104. }
  105. return $return;
  106. }
  107. public function processRecodParams( $record )
  108. {
  109. $params = $this->proccessMainRecordParams( $record );
  110. $method = 'process' . $record->type . 'RecordParams';
  111. $params['proxied'] = $this->isProxyEnabled();
  112. if ( method_exists( $this, $method ) )
  113. {
  114. $this->$method( $record, $params );
  115. }
  116. return $params;
  117. }
  118. public function proccessMainRecordParams( $record )
  119. {
  120. $record->recordName = $record->name;
  121. return array(
  122. 'zone' => $this->domain,
  123. 'name' => $record->nameToAbsolute( $this->domain, false ),
  124. 'ttl' => (int)$record->ttl,
  125. 'type' => $record->type,
  126. 'priority' => (int)$record->rdata->priority,
  127. 'content' => $record->rdata->toString(),
  128. );
  129. }
  130. public function processDSRecordParams( $record, &$params )
  131. {
  132. /** @var dns\record\type\DS $rdata */
  133. $rdata = $record->rdata;
  134. unset($params['content']);
  135. $params['data'] = [
  136. 'key_tag'=>(int)$rdata->keytag,
  137. 'algorithm'=>(int)$rdata->algorithm,
  138. 'digest_type'=>(int)$rdata->digesttype,
  139. 'digest'=>$rdata->digest
  140. ];
  141. }
  142. public function processNSRecordParams( $record, &$params )
  143. {
  144. $params['proxied'] = false; //cannot be proxied
  145. }
  146. public function processTXTRecordParams( $record, &$params )
  147. {
  148. $params['proxied'] = false; //cannot be proxied
  149. $params['content'] = trim($params['content'], '"');
  150. }
  151. public function processMXRecordParams( $record, &$params )
  152. {
  153. $params['content'] = $record->rdata->exchange;
  154. $params['priority'] = (int)$record->rdata->preference;
  155. $params['proxied'] = false; //cannot be proxied
  156. }
  157. public function processSRVRecordParams( $record, &$params )
  158. {
  159. $params['name'] = $record->recordName;
  160. $elemnts = $this->getSRVElements($record);
  161. $params['data'] = array(
  162. 'name' => $elemnts->name, // . $chunks[3],
  163. 'priority' => (int)$record->rdata->priority,
  164. 'weight' => (int)$record->rdata->weight,
  165. 'port' => (int)$record->rdata->port,
  166. 'target' => $record->rdata->target,
  167. 'service' => $elemnts->service,
  168. 'proto' => $elemnts->proto
  169. );
  170. $params['proxied'] = false; //cannot be proxied
  171. }
  172. private function getSRVElements( $record )
  173. {
  174. $chunks = explode( '.', $record->recordName );
  175. $elemnts = new \stdClass();
  176. $elemnts->service = $chunks[0];
  177. $elemnts->proto = $chunks[1];
  178. unset( $chunks['0'], $chunks[1] );
  179. $elemnts->name = (empty( $chunks )) ? $this->domain : implode( '.', $chunks );
  180. return $elemnts;
  181. }
  182. public function addRecord( dns\record\Record $record )
  183. {
  184. $params = $this->processRecodParams( $record );
  185. $this->get( $this->getZoneUrl( $this->getZoneID(), array('dns_records') ), $this->setPOSTparams( $params ), 'POST');
  186. sleep( 10 );
  187. }
  188. public function editRecord( dns\record\Record $record )
  189. {
  190. $recordid = $record->line;
  191. $params = $this->processRecodParams( $record );
  192. $this->get( $this->getZoneUrl( $this->getZoneID(), array('dns_records', $recordid) ), $this->setPOSTparams( $params ), 'PUT' );
  193. sleep( 20 );
  194. }
  195. public function deleteRecord( dns\record\Record $record )
  196. {
  197. $this->get( $this->getZoneUrl( $this->getZoneID(), array('dns_records', $record->line) ), array(), 'DELETE' );
  198. sleep( 10 );
  199. }
  200. public function activateZone()
  201. {
  202. $this->get( 'zones', $this->setPOSTparams( array('name' => $this->domain, 'jump_start' => false) ), 'POST' );
  203. //Wait 10 seconds for cloudflare
  204. sleep( 10 );
  205. }
  206. public function terminateZone()
  207. {
  208. $this->get( $this->getZoneUrl( $this->getZoneID() ), array(), 'DELETE' );
  209. }
  210. public function getZones()
  211. {
  212. $out = $this->getAllZones();
  213. $return = array();
  214. foreach ($out as $item) {
  215. $return[(string) $item->name] = (string) $item->name;
  216. }
  217. return $return;
  218. }
  219. public function getZone( $zone )
  220. {
  221. try {
  222. if ( !empty( $this->zoneObj[$zone] ) )
  223. {
  224. return $this->zoneObj[$zone];
  225. }
  226. $out = $this->get( 'zones', $this->setGETParams( array('name' => $zone) ) );
  227. $this->zoneObj[$zone] = $out->result[0];
  228. } catch (Exception $ex) {
  229. }
  230. return $this->zoneObj[$zone];
  231. }
  232. public function getZoneID()
  233. {
  234. if ( $this->zoneid )
  235. {
  236. return $this->zoneid;
  237. }
  238. $this->zoneid = $this->getZone( $this->domain )->id;
  239. return $this->zoneid;
  240. }
  241. protected function setGETParams( $params )
  242. {
  243. return array('GET' => $params);
  244. }
  245. protected function setPOSTparams( $params )
  246. {
  247. return array('POST' => $params);
  248. }
  249. protected function getZoneUrl( $zoneid, $additional = array() )
  250. {
  251. if ( !empty( $additional ) )
  252. {
  253. $addurl = '';
  254. foreach ($additional as $value) {
  255. $addurl .= '/' . $value;
  256. }
  257. }
  258. return 'zones/' . $zoneid . $addurl;
  259. }
  260. public function processURL( $url, $get = array() )
  261. {
  262. if ( !empty( $get ) )
  263. {
  264. $additional = '?' . http_build_query( $get );
  265. }
  266. return $this->hostname . $url . $additional;
  267. }
  268. private function get( $function, $params = array(), $type = 'GET', $debug = false )
  269. {
  270. $query = $this->processURL( $function, $params['GET'] );
  271. $curl = curl_init();
  272. curl_setopt( $curl, CURLOPT_URL, $query );
  273. curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
  274. curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
  275. curl_setopt( $curl, CURLOPT_HEADER, 0 );
  276. curl_setopt( $curl, CURLOPT_TIMEOUT, 999 );
  277. curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
  278. if ( $type )
  279. {
  280. curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, $type );
  281. }
  282. if( trim($this->config['token']) )
  283. {
  284. $auth = [
  285. 'Authorization: Bearer ' . $this->config['token'],
  286. 'Content-Type: application/json'
  287. ];
  288. }
  289. else
  290. {
  291. $auth = [
  292. 'X-Auth-Email: ' . $this->config['email'],
  293. 'X-Auth-Key: ' . $this->config['key'],
  294. 'Content-Type: application/json'
  295. ];
  296. }
  297. curl_setopt( $curl, CURLOPT_HTTPHEADER, $auth );
  298. $post = (empty( $params['POST'] )) ? array() : $params['POST'];
  299. curl_setopt( $curl, CURLOPT_POST, 1 );
  300. curl_setopt( $curl, CURLOPT_POSTFIELDS, json_encode( $post ) );
  301. $result = curl_exec( $curl );
  302. if ( $debug )
  303. {
  304. echo("<pre>" . print_r( (__LINE__ . ': ' ), true ) . print_r( $query, true ) . "</pre>");
  305. echo("<pre>" . print_r( (__LINE__ . ': ' ), true ) . print_r( $params, true ) . "</pre>");
  306. die( "<pre>" . print_r( __FILE__, true ) . print_r( __LINE__, true ) . "</pre><pre>" . print_r( $result, true ) . "</pre>" );
  307. }
  308. $out = $this->checkForErrors($curl, $result);
  309. curl_close( $curl );
  310. return $out;
  311. }
  312. private function checkForErrors( $curl, $result )
  313. {
  314. if ( curl_errno( $curl ) )
  315. {
  316. throw new exceptions\DNSSubmoduleException( "cURL Error: " . curl_errno( $curl ) . " - " . curl_error( $curl ), dns\SubmoduleExceptionCodes::CONNECTION_PROBLEM );
  317. }
  318. if ( !$result )
  319. {
  320. throw new exceptions\DNSSubmoduleException( 'Unable to retrieve response', dns\SubmoduleExceptionCodes::CONNECTION_PROBLEM );
  321. }
  322. $obj = json_decode( $result );
  323. if ( empty( $obj ) )
  324. {
  325. throw new exceptions\DNSSubmoduleException( 'Unable to parse response', dns\SubmoduleExceptionCodes::INVALID_RESPONSE );
  326. }
  327. if ( !$obj->success )
  328. {
  329. //$error = (isset( $obj->errors ) && !empty( $obj->errors )) ? (is_array( $obj->errors )) ? $obj->errors[0]->message : $obj->errors->message :
  330. // $obj->message;
  331. if(!empty($obj->error))
  332. {
  333. $error = $obj->error;
  334. }
  335. elseif(isset( $obj->errors ) && !empty( $obj->errors ))
  336. {
  337. if(is_array( $obj->errors ))
  338. {
  339. $error = $obj->errors[0]->message.(is_array($obj->errors[0]->error_chain) ? ': '.$obj->errors[0]->error_chain[0]->message : '');
  340. }
  341. else
  342. {
  343. $error = $obj->errors->message;
  344. }
  345. }
  346. else
  347. {
  348. $obj->message;
  349. }
  350. throw new exceptions\DNSSubmoduleException( $error, dns\SubmoduleExceptionCodes::COMMAND_ERROR );
  351. }
  352. return $obj;
  353. }
  354. private function isProxyEnabled()
  355. {
  356. return $this->config['proxied'] === 'on';
  357. }
  358. /**
  359. * Get sign keys
  360. */
  361. public function getSignKeys()
  362. {
  363. $dnssec = new dns\dnssec\DnsSec();
  364. $zoneid = $this->getZoneID();
  365. $result = json_decode($this->get('zones/' . $zoneid . '/dnssec'));
  366. foreach ( $result->result as $record )
  367. {
  368. $ds = new dns\record\type\DS();
  369. $ds->setKeytag($record->key_tag);
  370. $ds->setAlgorithm($record->algorithm);
  371. $ds->setDigestType($record->digest_type);
  372. $ds->setDigest($record->digest);
  373. $dnssec->addDs($ds);
  374. //CSK
  375. $dsSplitted = explode(' ', $record->ds);
  376. $dnskey = new dns\record\type\DNSKEY();
  377. $dnskey->setFlags($record->flags);
  378. $dnskey->setProtocol($dsSplitted[2]);
  379. $dnskey->setAlgorithm($record->algorithm);
  380. $dnskey->setPublicKey($record->public_key);
  381. $csk = new dns\dnssec\CSK();
  382. $csk->setId($dsSplitted[4]);
  383. // $csk->setBits();
  384. $csk->setDnsKey($dnskey);
  385. $csk->setLifetime($dsSplitted[1]);
  386. $dnssec->addKey($csk);
  387. }
  388. return $dnssec;
  389. }
  390. /**
  391. * Sign DNS zone
  392. */
  393. public function sign()
  394. {
  395. $this->changeStatus(true);
  396. }
  397. public function changeStatus( $status = true )
  398. {
  399. $status = $status ? 'active' : 'disabled';
  400. $zoneid = $this->getZoneID();
  401. $params['POST'] = [
  402. 'status' => $status
  403. ];
  404. $this->get('zones/' . $zoneid . '/dnssec', $params, 'PATCH');
  405. }
  406. /**
  407. * Unsign DNS zone
  408. */
  409. public function unsign()
  410. {
  411. $this->changeStatus(false);
  412. }
  413. /**
  414. * Rectify DNS zone
  415. */
  416. public function rectify()
  417. {
  418. // TODO: Implement rectify() method.
  419. }
  420. /**
  421. *
  422. */
  423. public function isSigned()
  424. {
  425. try
  426. {
  427. $zoneid = $this->getZoneID();
  428. $response = json_decode($this->get('zones/' . $zoneid . '/dnssec'));
  429. if ( isset($response->result) )
  430. {
  431. $status = ($response->result->status == 'active' ? true : false);
  432. }
  433. else
  434. {
  435. throw new Exception('There was problem with getting response from cloudflare');
  436. }
  437. return $status;
  438. }
  439. catch (\Exception $e)
  440. {
  441. return false;
  442. }
  443. }
  444. private function getAllZones()
  445. {
  446. $page = 1;
  447. $out = [];
  448. while( $zones = $this->get('zones', $this->setGETParams(['per_page' => 100, 'page' => $page]))->result )
  449. {
  450. $out = array_merge($out, $zones);
  451. $page++;
  452. }
  453. return $out;
  454. }
  455. private function getAllRecords()
  456. {
  457. $page = 1;
  458. $out = [];
  459. while( $records = $this->get($this->getZoneUrl($this->getZoneID(), ['dns_records']), ['GET' => ['per_page' => 100, 'page' => $page]])->result )
  460. {
  461. $out = array_merge($out, $records);
  462. $page++;
  463. }
  464. return $out;
  465. }
  466. }