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