remove debug code
[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
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
344 /**
345 * get uptime based on online (connection) time
346 *
347 * @return string
348 */
349 public function getUptime () {
350 $data = $this->getData('LAN');
351 $data = $this->getValues($data);
352
353 return $data['days_online'];
354 }
355
356 /**
357 * return the given json as array
358 *
359 * @param string $file
360 * @return array
361 */
362 public function getData ($file) {
363 if ($file != 'Status') $this->checkLogin();
364
365 $path = 'data/'.$file.'.json';
366 $fields = array();
367 $data = $this->sentRequest($path, $fields, true);
368
369 return $data['body'];
370 }
371
372 /**
373 * get the router syslog
374 *
375 * @return array
376 */
377 public function getSyslog() {
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 }
387 }
388
389 /**
390 * get the Missed Calls from router
391 *
392 * @return array
393 */
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 }
404 }
405
406 /**
407 * get the Taken Calls from router
408 *
409 * @return array
410 */
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 }
421 }
422
423 /**
424 * get the Dialed Calls from router
425 *
426 * @return array
427 */
428 public function getDialedCalls() {
429 $data = $this->getData('PhoneCalls');
430 $data = $this->getValues($data);
431
432 if (isset($data['adddialedcalls'])) {
433 return $data['adddialedcalls'];
434 }
435 else {
436 return array();
437 }
438 }
439
440 /**
441 * reconnect LTE
442 *
443 * @return array
444 */
445 public function reconnectLte () {
446 $this->checkLogin();
447
448 $path = 'data/modules.json';
449 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
450 $data = $this->sentEncryptedRequest($path, $fields, true);
451
452 return $data['body'];
453 }
454
455 /**
456 * reset the router to Factory Default
457 * not tested
458 *
459 * @return array
460 */
461 public function resetToFactoryDefault () {
462 $this->checkLogin();
463
464 $path = 'data/resetAllSetting.json';
465 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
466 $data = $this->sentRequest($path, $fields, true);
467
468 return $data['body'];
469 }
470
471
472 /**
473 * check if firmware is actual
474 *
475 * @return array
476 */
477 public function checkFirmware () {
478 $this->checkLogin();
479
480 $path = 'data/checkfirmware.json';
481 $fields = array('checkfirmware' => 'true');
482 $data = $this->sentRequest($path, $fields, true);
483
484 return $data['body'];
485 }
486
487 /**
488 * decrypt data from router
489 *
490 * @param string $data
491 * @return array
492 */
493 private function decrypt ($data) {
494 $iv = hex2bin(substr($this->challenge, 16, 16));
495 $adata = hex2bin(substr($this->challenge, 32, 16));
496 $key = hex2bin($this->derivedk);
497 $enc = hex2bin($data);
498
499 $factory = new CryptLib\Cipher\Factory();
500 $aes = $factory->getBlockCipher('rijndael-128');
501 $aes->setKey($key);
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 *
512 * @param string $data
513 * @return string
514 */
515 private function encrypt ($data) {
516 $iv = hex2bin(substr($this->challenge, 16, 16));
517 $adata = hex2bin(substr($this->challenge, 32, 16));
518 $key = hex2bin($this->derivedk);
519
520 $factory = new CryptLib\Cipher\Factory();
521 $aes = $factory->getBlockCipher('rijndael-128');
522 $aes->setKey($key);
523 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
524 $mode->encrypt($data);
525
526 return bin2hex($mode->finish());
527 }
528
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) {
538 // thank you telekom for this piece of shit
539 if ($item['vartype'] == 'template') {
540 if (is_array($item['varvalue'])) {
541 $data[$item['varid']][] = $this->getValues($item['varvalue']);
542 }
543 else {
544 // i dont know if we need this
545 $data[$item['varid']] = $item['varvalue'];
546 }
547 }
548 else {
549 if (is_array($item['varvalue'])) {
550 $data[$item['varid']] = $this->getValues($item['varvalue']);
551 }
552 else {
553 $data[$item['varid']] = $item['varvalue'];
554 }
555 }
556 }
557
558 return $data;
559 }
560
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);
571 $fields = $this->encrypt(http_build_query($fields));
572 return $this->sentRequest($path, $fields, $cookie, $count);
573 }
574
575 /**
576 * sends the request to router
577 *
578 * @param string $path
579 * @param mixed $fields
580 * @param string $cookie
581 * @param integer $count
582 * @return array
583 */
584 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
585 $url = $this->url.$path.'?lang=en';
586 $ch = curl_init();
587 curl_setopt($ch, CURLOPT_URL, $url);
588
589 if (!empty($fields)) {
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 }
598 }
599
600 if ($cookie === true) {
601 curl_setopt($ch, CURLOPT_COOKIE, 'challengev='.$this->challenge.'; '.$this->cookie);
602 }
603
604 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
605 curl_setopt($ch, CURLOPT_HEADER, true);
606
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
614 // check if response is empty
615 if (empty($body)) {
616 throw new RouterException('empty response');
617 }
618
619 // check if body is encrypted (hex instead of json)
620 if (ctype_xdigit($body)) {
621 $body = $this->decrypt($body);
622 }
623
624 // fix invalid json
625 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
626 $body = preg_replace('/\'/i', '"', $body);
627 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
628 $body = preg_replace("/},\s+]/", "}\n]", $body);
629
630 // decode json
631 if (strpos($url, '.json') !== false) {
632 $body = json_decode($body, true);
633 }
634
635 return array('header' => $this->parse_headers($header), 'body' => $body);
636 }
637
638 /**
639 * get the csrf_token
640 *
641 * @return string
642 */
643 private function getToken () {
644 $this->checkLogin();
645
646 $path = 'html/content/overview/index.html';
647 $fields = array();
648 $data = $this->sentRequest($path, $fields, true);
649
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 {
657 throw new RouterException('unable to get csrf_token');
658 }
659 }
660
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')) {
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));
674 $derivedk = substr($derivedk, 0, 32);
675 }
676 else {
677 $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
678 }
679
680 if (empty($derivedk)) {
681 throw new RouterException('unable to calculate derivedk');
682 }
683
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) {
694 $cookie = '';
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])) {
698 $cookie = $match[1];
699 }
700 }
701
702 if (empty($cookie)) {
703 throw new RouterException('unable to get the session cookie from the router');
704 }
705
706 return $cookie;
707 }
708
709 /**
710 * parse the curl return header into an array
711 *
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
719 $header_text = explode("\r\n", $header_text);
720 foreach ($header_text as $i => $line) {
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 }
732 }