remove debug code
[GitHub/Stricted/speedport-hybrid-php-api.git] / SpeedportHybrid.class.php
CommitLineData
a91317a6 1<?php
8162139f
S
2require_once('RebootException.class.php');
3require_once('RouterException.class.php');
aacbbd28 4require_once('CryptLib/CryptLib.php');
8162139f 5
1d934afe
S
6/**
7 * @author Jan Altensen (Stricted)
8 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
9 * @copyright 2015 Jan Altensen (Stricted)
10 */
21f877e4 11class SpeedportHybrid {
0dca2d61 12 /**
23cc0061
S
13 * class version
14 * @const string
0dca2d61 15 */
219ba661 16 const VERSION = '1.0.3';
0dca2d61 17
a91317a6
S
18 /**
19 * password-challenge
20 * @var string
21 */
22 private $challenge = '';
23
809e25bd
S
24 /**
25 * csrf_token
26 * @var string
27 */
28 private $token = '';
29
a91317a6
S
30 /**
31 * hashed password
32 * @var string
33 */
34 private $hash = '';
35
36 /**
37 * session cookie
38 * @var string
39 */
ac344b92 40 private $cookie = '';
a91317a6
S
41
42 /**
43 * router url
44 * @var string
45 */
b5a532a8 46 private $url = '';
a91317a6 47
c9e082da
S
48 /**
49 * derivedk cookie
50 * @var string
51 */
52 private $derivedk = '';
53
e58a96d1 54 public function __construct ($url = 'http://speedport.ip/') {
b5a532a8 55 $this->url = $url;
a91317a6
S
56 }
57
58 /**
59 * Requests the password-challenge from the router.
60 */
e58a96d1 61 private function getChallenge () {
b5a532a8 62 $path = 'data/Login.json';
a91317a6 63 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'challengev' => 'null');
b5a532a8 64 $data = $this->sentRequest($path, $fields);
219ba661 65 $data = $this->getValues($data['body']);
c2678616
S
66
67 if (isset($data['challengev']) && !empty($data['challengev'])) {
ac344b92
S
68 return $data['challengev'];
69 }
70 else {
219ba661 71 throw new RouterException('unable to get the challenge from the router');
a91317a6
S
72 }
73 }
74
75 /**
76 * login into the router with the given password
5e44cffa 77 *
a91317a6
S
78 * @param string $password
79 * @return boolean
80 */
81 public function login ($password) {
ac344b92 82 $this->challenge = $this->getChallenge();
e58a96d1 83
b5a532a8 84 $path = 'data/Login.json';
a91317a6
S
85 $this->hash = hash('sha256', $this->challenge.':'.$password);
86 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash);
b5a532a8 87 $data = $this->sentRequest($path, $fields);
219ba661 88 $json = $this->getValues($data['body']);
ac344b92 89
c2678616 90 if (isset($json['login']) && $json['login'] == 'success') {
ac344b92
S
91 $this->cookie = $this->getCookie($data);
92
93 $this->derivedk = $this->getDerviedk($password);
94
95 // get the csrf_token
96 $this->token = $this->getToken();
97
98 if ($this->checkLogin(false) === true) {
99 return true;
a91317a6
S
100 }
101 }
102
103 return false;
104 }
105
df1e1394
S
106 /**
107 * check if we are logged in
108 *
adcedd8b
S
109 * @param boolean $exception
110 * @return boolean
df1e1394 111 */
adcedd8b 112 public function checkLogin ($exception = true) {
ac344b92
S
113 // check if challenge or session is empty
114 if (empty($this->challenge) || empty($this->cookie)) {
adcedd8b 115 if ($exception === true) {
219ba661 116 throw new RouterException('you musst be logged in to use this method');
adcedd8b
S
117 }
118
0dca2d61
S
119 return false;
120 }
121
34701575 122 $path = 'data/SecureStatus.json';
df1e1394 123 $fields = array();
0dca2d61 124 $data = $this->sentRequest($path, $fields, true);
219ba661 125 $data = $this->getValues($data['body']);
df1e1394 126
219ba661 127 if ($data['loginstate'] != 1) {
adcedd8b 128 if ($exception === true) {
219ba661 129 throw new RouterException('you musst be logged in to use this method');
adcedd8b
S
130 }
131
df1e1394
S
132 return false;
133 }
134
135 return true;
136 }
137
a91317a6
S
138 /**
139 * logout
5e44cffa 140 *
58feafa2 141 * @return boolean
a91317a6
S
142 */
143 public function logout () {
adcedd8b 144 $this->checkLogin();
e58a96d1 145
b5a532a8 146 $path = 'data/Login.json';
df1e1394 147 $fields = array('csrf_token' => $this->token, 'logout' => 'byby');
219ba661
S
148 $data = $this->sentRequest($path, $fields, true);
149 $data = $this->getValues($data['body']);
150 if ((isset($data['status']) && $data['status'] == 'ok') && $this->checkLogin(false) === false) {
df1e1394
S
151 // reset challenge and session
152 $this->challenge = '';
ac344b92
S
153 $this->cookie = '';
154 $this->token = '';
155 $this->derivedk = '';
df1e1394 156
58feafa2 157 return true;
df1e1394 158 }
58feafa2
S
159
160 return false;
a91317a6
S
161 }
162
163 /**
164 * reboot the router
5e44cffa 165 *
58feafa2 166 * @return boolean
a91317a6
S
167 */
168 public function reboot () {
adcedd8b 169 $this->checkLogin();
e58a96d1 170
b5a532a8 171 $path = 'data/Reboot.json';
8162139f
S
172 $fields = array('csrf_token' => $this->token, 'reboot_device' => 'true');
173 $data = $this->sentEncryptedRequest($path, $fields, true);
219ba661 174 $data = $this->getValues($data['body']);
14d4f286 175
219ba661 176 if ($data['status'] == 'ok') {
aacbbd28
S
177 // reset challenge and session
178 $this->challenge = '';
179 $this->cookie = '';
180 $this->token = '';
181 $this->derivedk = '';
182
8162139f
S
183 // throw an exception because router is unavailable for other tasks
184 // like $this->logout() or $this->checkLogin
185 throw new RebootException('Router Reboot');
186 }
58feafa2
S
187
188 return false;
a91317a6
S
189 }
190
87026df3
S
191 /**
192 * change dsl connection status
5e44cffa 193 *
87026df3 194 * @param string $status
58feafa2 195 * @return boolean
87026df3 196 */
655c9abd 197 public function changeDSLStatus ($status) {
adcedd8b 198 $this->checkLogin();
e58a96d1 199
b5a532a8 200 $path = 'data/Connect.json';
87026df3
S
201
202 if ($status == 'online' || $status == 'offline') {
203 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'req_connect' => $status);
0dca2d61 204 $data = $this->sentRequest($path, $fields, true);
219ba661 205 $data = $this->getValues($data['body']);
c2678616 206
219ba661 207 if ($data['status'] == 'ok') {
58feafa2
S
208 return true;
209 }
210 else {
211 return false;
212 }
87026df3
S
213 }
214 else {
23cc0061 215 throw new RouterException('unknown status');
87026df3
S
216 }
217 }
218
655c9abd
S
219 /**
220 * change lte connection status
221 *
222 * @param string $status
223 * @return boolean
224 */
225 public function changeLTEStatus ($status) {
226 throw new Exception('unstable funtion');
227 $path = 'data/Modules.json';
228
229 if ($status == '0' || $status == '1' || $status == 'yes' || $status == 'no') {
230 if ($status == 'yes') $status = '1';
231 else if ($status == 'no') $status = '0';
232
233 $fields = array('csrf_token' => $this->token, 'use_lte' => $status);
234 $data = $this->sentEncryptedRequest($path, $fields, true);
235
236 // debug only
237 return $data;
238 }
239 else {
240 throw new RouterException('unknown status');
241 }
242 }
243
f94e171e
S
244 /**
245 * get phone book entrys
246 *
247 * @return array
248 */
249 public function getPhoneBookEntrys () {
250 $data = $this->getData('PhoneBook');
251 $data = $this->getValues($data);
252
253 if (isset($data['addbookentry'])) {
254 return $data['addbookentry'];
255 }
256 else {
257 return array();
258 }
259 }
260
559c5be7
S
261 /**
262 * add Phone Book Entry
263 *
264 * @param string $name
265 * @param string $firstname
266 * @param string $private
267 * @param string $work
268 * @param string $mobile
269 * @param integer $id
270 *
271 * @return array
272 */
273 public function addPhoneBookEntry ($name, $firstname, $private, $work, $mobile, $id = -1) {
5e5d7118
S
274 $this->checkLogin();
275
559c5be7
S
276 $path = 'data/PhoneBook.json';
277 $fields = array(
278 'csrf_token' => $this->getToken(),
279 'id' => $id,
280 'search' => '',
281 'phonebook_name' => $name,
282 'phonebook_vorname' => $firstname,
283 'phonebook_number_p' => $private,
284 'phonebook_number_a' => $work,
5e5d7118 285 'phonebook_number_m' => $mobile
559c5be7
S
286 );
287
288 $data = $this->sentRequest($path, $fields, true);
289 $data = $this->getValues($data['body']);
5e5d7118 290
559c5be7
S
291 if ($data['status'] == 'ok') {
292 return $data;
293 }
294 else {
295 throw new RouterException('can not add/edit Phone Book Entry');
296 }
297 }
298
299 /**
300 * edit Phone Book Entry
301 *
302 * @param integer $id
303 * @param string $name
304 * @param string $firstname
305 * @param string $private
306 * @param string $work
307 * @param string $mobile
308 *
309 * @return array
310 */
311 public function changePhoneBookEntry ($id, $name, $firstname, $private, $work, $mobile) {
312 return $this->addPhoneBookEntry($name, $firstname, $private, $work, $private, $id);
313 }
314
5e5d7118
S
315 /**
316 * delete Phone Book Entry
317 *
318 * @param integer $id
319 *
320 * @return array
321 */
322 public function deletePhoneBookEntry ($id) {
323 $this->checkLogin();
324
325 $path = 'data/PhoneBook.json';
326 $fields = array(
327 'csrf_token' => $this->getToken(),
328 'id' => $id,
329 'deleteEntry' => 'delete'
330 );
331
332 $data = $this->sentRequest($path, $fields, true);
333 $data = $this->getValues($data['body']);
5e5d7118
S
334
335 if ($data['status'] == 'ok') {
336 return $data;
337 }
338 else {
339 throw new RouterException('can not delete Phone Book Entry');
340 }
341
342 }
343
58feafa2
S
344 /**
345 * get uptime based on online (connection) time
346 *
347 * @return string
348 */
349 public function getUptime () {
aacbbd28 350 $data = $this->getData('LAN');
58feafa2
S
351 $data = $this->getValues($data);
352
353 return $data['days_online'];
354 }
355
a91317a6
S
356 /**
357 * return the given json as array
5e44cffa 358 *
a91317a6
S
359 * @param string $file
360 * @return array
361 */
362 public function getData ($file) {
ac344b92 363 if ($file != 'Status') $this->checkLogin();
e58a96d1 364
b5a532a8 365 $path = 'data/'.$file.'.json';
a91317a6 366 $fields = array();
0dca2d61 367 $data = $this->sentRequest($path, $fields, true);
a91317a6 368
219ba661 369 return $data['body'];
a91317a6
S
370 }
371
5e44cffa
S
372 /**
373 * get the router syslog
374 *
375 * @return array
376 */
377 public function getSyslog() {
aacbbd28
S
378 $data = $this->getData('SystemMessages');
379 $data = $this->getValues($data);
380
381 if (isset($data['addmessage'])) {
382 return $data['addmessage'];
383 }
384 else {
385 return array();
386 }
5e44cffa
S
387 }
388
15260eeb 389 /**
aacbbd28 390 * get the Missed Calls from router
15260eeb
S
391 *
392 * @return array
393 */
aacbbd28
S
394 public function getMissedCalls() {
395 $data = $this->getData('PhoneCalls');
396 $data = $this->getValues($data);
397
398 if (isset($data['addmissedcalls'])) {
399 return $data['addmissedcalls'];
400 }
401 else {
402 return array();
403 }
15260eeb
S
404 }
405
abf641bb 406 /**
aacbbd28 407 * get the Taken Calls from router
abf641bb
S
408 *
409 * @return array
410 */
aacbbd28
S
411 public function getTakenCalls() {
412 $data = $this->getData('PhoneCalls');
413 $data = $this->getValues($data);
414
415 if (isset($data['addtakencalls'])) {
416 return $data['addtakencalls'];
417 }
418 else {
419 return array();
420 }
0dca2d61
S
421 }
422
423 /**
aacbbd28 424 * get the Dialed Calls from router
0dca2d61
S
425 *
426 * @return array
427 */
aacbbd28
S
428 public function getDialedCalls() {
429 $data = $this->getData('PhoneCalls');
430 $data = $this->getValues($data);
9bd25bb4 431
aacbbd28
S
432 if (isset($data['adddialedcalls'])) {
433 return $data['adddialedcalls'];
434 }
435 else {
436 return array();
437 }
abf641bb
S
438 }
439
809e25bd
S
440 /**
441 * reconnect LTE
442 *
443 * @return array
444 */
c9e082da 445 public function reconnectLte () {
adcedd8b 446 $this->checkLogin();
e58a96d1 447
c9e082da 448 $path = 'data/modules.json';
809e25bd 449 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
8162139f 450 $data = $this->sentEncryptedRequest($path, $fields, true);
c9e082da 451
219ba661 452 return $data['body'];
c9e082da 453 }
809e25bd 454
7f4a51d2
S
455 /**
456 * reset the router to Factory Default
457 * not tested
458 *
459 * @return array
460 */
9bd25bb4 461 public function resetToFactoryDefault () {
adcedd8b 462 $this->checkLogin();
e58a96d1 463
9bd25bb4
S
464 $path = 'data/resetAllSetting.json';
465 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
0dca2d61 466 $data = $this->sentRequest($path, $fields, true);
9bd25bb4 467
219ba661 468 return $data['body'];
9bd25bb4 469 }
7f4a51d2 470
9bd25bb4 471
4ae464d1
S
472 /**
473 * check if firmware is actual
474 *
475 * @return array
476 */
477 public function checkFirmware () {
adcedd8b 478 $this->checkLogin();
e58a96d1 479
4ae464d1
S
480 $path = 'data/checkfirmware.json';
481 $fields = array('checkfirmware' => 'true');
0dca2d61 482 $data = $this->sentRequest($path, $fields, true);
4ae464d1 483
219ba661 484 return $data['body'];
4ae464d1
S
485 }
486
14d4f286
S
487 /**
488 * decrypt data from router
489 *
490 * @param string $data
491 * @return array
492 */
c2678616 493 private function decrypt ($data) {
14d4f286
S
494 $iv = hex2bin(substr($this->challenge, 16, 16));
495 $adata = hex2bin(substr($this->challenge, 32, 16));
23cc0061 496 $key = hex2bin($this->derivedk);
14d4f286
S
497 $enc = hex2bin($data);
498
23cc0061
S
499 $factory = new CryptLib\Cipher\Factory();
500 $aes = $factory->getBlockCipher('rijndael-128');
501 $aes->setKey($key);
14d4f286
S
502 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
503
504 $mode->decrypt($enc);
505
506 return $mode->finish();
507 }
508
509 /**
510 * decrypt data for the router
511 *
23cc0061 512 * @param string $data
14d4f286
S
513 * @return string
514 */
c2678616 515 private function encrypt ($data) {
14d4f286
S
516 $iv = hex2bin(substr($this->challenge, 16, 16));
517 $adata = hex2bin(substr($this->challenge, 32, 16));
23cc0061 518 $key = hex2bin($this->derivedk);
14d4f286 519
23cc0061
S
520 $factory = new CryptLib\Cipher\Factory();
521 $aes = $factory->getBlockCipher('rijndael-128');
522 $aes->setKey($key);
14d4f286 523 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
23cc0061 524 $mode->encrypt($data);
14d4f286 525
809e25bd 526 return bin2hex($mode->finish());
14d4f286
S
527 }
528
c2678616
S
529 /**
530 * get the values from array
531 *
532 * @param array $array
533 * @return array
534 */
535 private function getValues($array) {
536 $data = array();
537 foreach ($array as $item) {
aacbbd28 538 // thank you telekom for this piece of shit
8b7e3972 539 if ($item['vartype'] == 'template') {
ec351a7d
S
540 if (is_array($item['varvalue'])) {
541 $data[$item['varid']][] = $this->getValues($item['varvalue']);
542 }
543 else {
23cc0061 544 // i dont know if we need this
ec351a7d
S
545 $data[$item['varid']] = $item['varvalue'];
546 }
58feafa2
S
547 }
548 else {
8b7e3972
S
549 if (is_array($item['varvalue'])) {
550 $data[$item['varid']] = $this->getValues($item['varvalue']);
551 }
552 else {
553 $data[$item['varid']] = $item['varvalue'];
554 }
58feafa2 555 }
c2678616
S
556 }
557
558 return $data;
559 }
560
8162139f
S
561 /**
562 * sends the encrypted request to router
563 *
564 * @param string $path
565 * @param mixed $fields
566 * @param string $cookie
567 * @return array
568 */
569 private function sentEncryptedRequest ($path, $fields, $cookie = false) {
570 $count = count($fields);
23cc0061 571 $fields = $this->encrypt(http_build_query($fields));
8162139f
S
572 return $this->sentRequest($path, $fields, $cookie, $count);
573 }
574
a91317a6
S
575 /**
576 * sends the request to router
5e44cffa 577 *
b5a532a8 578 * @param string $path
809e25bd 579 * @param mixed $fields
a91317a6 580 * @param string $cookie
809e25bd 581 * @param integer $count
a91317a6
S
582 * @return array
583 */
0dca2d61 584 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
49abc701 585 $url = $this->url.$path.'?lang=en';
a91317a6
S
586 $ch = curl_init();
587 curl_setopt($ch, CURLOPT_URL, $url);
588
589 if (!empty($fields)) {
809e25bd
S
590 if (is_array($fields)) {
591 curl_setopt($ch, CURLOPT_POST, count($fields));
592 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
593 }
594 else {
595 curl_setopt($ch, CURLOPT_POST, $count);
596 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
597 }
a91317a6
S
598 }
599
0dca2d61 600 if ($cookie === true) {
559c5be7 601 curl_setopt($ch, CURLOPT_COOKIE, 'challengev='.$this->challenge.'; '.$this->cookie);
a91317a6
S
602 }
603
604 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
605 curl_setopt($ch, CURLOPT_HEADER, true);
606
a91317a6
S
607 $result = curl_exec($ch);
608
609 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
610 $header = substr($result, 0, $header_size);
611 $body = substr($result, $header_size);
612 curl_close($ch);
613
219ba661
S
614 // check if response is empty
615 if (empty($body)) {
616 throw new RouterException('empty response');
617 }
618
8162139f
S
619 // check if body is encrypted (hex instead of json)
620 if (ctype_xdigit($body)) {
621 $body = $this->decrypt($body);
622 }
623
a91317a6
S
624 // fix invalid json
625 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
626 $body = preg_replace('/\'/i', '"', $body);
5e44cffa 627 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
dae16c50 628 $body = preg_replace("/},\s+]/", "}\n]", $body);
a91317a6 629
219ba661 630 // decode json
aacbbd28 631 if (strpos($url, '.json') !== false) {
219ba661
S
632 $body = json_decode($body, true);
633 }
634
a91317a6
S
635 return array('header' => $this->parse_headers($header), 'body' => $body);
636 }
637
809e25bd
S
638 /**
639 * get the csrf_token
640 *
641 * @return string
642 */
643 private function getToken () {
adcedd8b 644 $this->checkLogin();
e58a96d1 645
49abc701 646 $path = 'html/content/overview/index.html';
809e25bd 647 $fields = array();
0dca2d61 648 $data = $this->sentRequest($path, $fields, true);
809e25bd 649
809e25bd
S
650 $a = explode('csrf_token = "', $data['body']);
651 $a = explode('";', $a[1]);
652
653 if (isset($a[0]) && !empty($a[0])) {
654 return $a[0];
655 }
656 else {
219ba661 657 throw new RouterException('unable to get csrf_token');
809e25bd
S
658 }
659 }
660
ac344b92
S
661 /**
662 * calculate the derivedk
663 *
664 * @param string $password
665 * @return string
666 */
667 private function getDerviedk ($password) {
668 $derivedk = '';
669
670 // calculate derivedk
671 if (!function_exists('hash_pbkdf2')) {
ac344b92
S
672 $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2(array('hash' => 'sha1'));
673 $derivedk = bin2hex($pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32));
58feafa2 674 $derivedk = substr($derivedk, 0, 32);
ac344b92
S
675 }
676 else {
677 $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
678 }
679
58feafa2
S
680 if (empty($derivedk)) {
681 throw new RouterException('unable to calculate derivedk');
682 }
683
ac344b92
S
684 return $derivedk;
685 }
686
687 /**
688 * get cookie from header data
689 *
690 * @param array $data
691 * @return string
692 */
693 private function getCookie ($data) {
58feafa2 694 $cookie = '';
ac344b92
S
695 if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
696 preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
697 if (isset($match[1]) && !empty($match[1])) {
58feafa2 698 $cookie = $match[1];
ac344b92
S
699 }
700 }
701
58feafa2 702 if (empty($cookie)) {
219ba661 703 throw new RouterException('unable to get the session cookie from the router');
58feafa2
S
704 }
705
706 return $cookie;
ac344b92
S
707 }
708
a91317a6
S
709 /**
710 * parse the curl return header into an array
5e44cffa 711 *
a91317a6
S
712 * @param string $response
713 * @return array
714 */
715 private function parse_headers($response) {
716 $headers = array();
717 $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
718
7f4a51d2
S
719 $header_text = explode("\r\n", $header_text);
720 foreach ($header_text as $i => $line) {
a91317a6
S
721 if ($i === 0) {
722 $headers['http_code'] = $line;
723 }
724 else {
725 list ($key, $value) = explode(': ', $line);
726 $headers[$key] = $value;
727 }
728 }
729
730 return $headers;
731 }
7f4a51d2 732}