c5eed35e850573b5a07bbcb24ed87e22282dedfd
[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 $path = 'data/PhoneBook.json';
275 $fields = array(
276 'csrf_token' => $this->getToken(),
277 'id' => $id,
278 'search' => '',
279 'phonebook_name' => $name,
280 'phonebook_vorname' => $firstname,
281 'phonebook_number_p' => $private,
282 'phonebook_number_a' => $work,
283 'phonebook_number_m' => $mobile,
284 'action' => '1'
285 );
286
287 $data = $this->sentRequest($path, $fields, true);
288 $data = $this->getValues($data['body']);
289 if ($data['status'] == 'ok') {
290 return $data;
291 }
292 else {
293 throw new RouterException('can not add/edit Phone Book Entry');
294 }
295 }
296
297 /**
298 * edit Phone Book Entry
299 *
300 * @param integer $id
301 * @param string $name
302 * @param string $firstname
303 * @param string $private
304 * @param string $work
305 * @param string $mobile
306 *
307 * @return array
308 */
309 public function changePhoneBookEntry ($id, $name, $firstname, $private, $work, $mobile) {
310 return $this->addPhoneBookEntry($name, $firstname, $private, $work, $private, $id);
311 }
312
313 /**
314 * get uptime based on online (connection) time
315 *
316 * @return string
317 */
318 public function getUptime () {
319 $data = $this->getData('LAN');
320 $data = $this->getValues($data);
321
322 return $data['days_online'];
323 }
324
325 /**
326 * return the given json as array
327 *
328 * @param string $file
329 * @return array
330 */
331 public function getData ($file) {
332 if ($file != 'Status') $this->checkLogin();
333
334 $path = 'data/'.$file.'.json';
335 $fields = array();
336 $data = $this->sentRequest($path, $fields, true);
337
338 return $data['body'];
339 }
340
341 /**
342 * get the router syslog
343 *
344 * @return array
345 */
346 public function getSyslog() {
347 $data = $this->getData('SystemMessages');
348 $data = $this->getValues($data);
349
350 if (isset($data['addmessage'])) {
351 return $data['addmessage'];
352 }
353 else {
354 return array();
355 }
356 }
357
358 /**
359 * get the Missed Calls from router
360 *
361 * @return array
362 */
363 public function getMissedCalls() {
364 $data = $this->getData('PhoneCalls');
365 $data = $this->getValues($data);
366
367 if (isset($data['addmissedcalls'])) {
368 return $data['addmissedcalls'];
369 }
370 else {
371 return array();
372 }
373 }
374
375 /**
376 * get the Taken Calls from router
377 *
378 * @return array
379 */
380 public function getTakenCalls() {
381 $data = $this->getData('PhoneCalls');
382 $data = $this->getValues($data);
383
384 if (isset($data['addtakencalls'])) {
385 return $data['addtakencalls'];
386 }
387 else {
388 return array();
389 }
390 }
391
392 /**
393 * get the Dialed Calls from router
394 *
395 * @return array
396 */
397 public function getDialedCalls() {
398 $data = $this->getData('PhoneCalls');
399 $data = $this->getValues($data);
400
401 if (isset($data['adddialedcalls'])) {
402 return $data['adddialedcalls'];
403 }
404 else {
405 return array();
406 }
407 }
408
409 /**
410 * reconnect LTE
411 *
412 * @return array
413 */
414 public function reconnectLte () {
415 $this->checkLogin();
416
417 $path = 'data/modules.json';
418 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
419 $data = $this->sentEncryptedRequest($path, $fields, true);
420
421 return $data['body'];
422 }
423
424 /**
425 * reset the router to Factory Default
426 * not tested
427 *
428 * @return array
429 */
430 public function resetToFactoryDefault () {
431 $this->checkLogin();
432
433 $path = 'data/resetAllSetting.json';
434 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
435 $data = $this->sentRequest($path, $fields, true);
436
437 return $data['body'];
438 }
439
440
441 /**
442 * check if firmware is actual
443 *
444 * @return array
445 */
446 public function checkFirmware () {
447 $this->checkLogin();
448
449 $path = 'data/checkfirmware.json';
450 $fields = array('checkfirmware' => 'true');
451 $data = $this->sentRequest($path, $fields, true);
452
453 return $data['body'];
454 }
455
456 /**
457 * decrypt data from router
458 *
459 * @param string $data
460 * @return array
461 */
462 private function decrypt ($data) {
463 $iv = hex2bin(substr($this->challenge, 16, 16));
464 $adata = hex2bin(substr($this->challenge, 32, 16));
465 $key = hex2bin($this->derivedk);
466 $enc = hex2bin($data);
467
468 $factory = new CryptLib\Cipher\Factory();
469 $aes = $factory->getBlockCipher('rijndael-128');
470 $aes->setKey($key);
471 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
472
473 $mode->decrypt($enc);
474
475 return $mode->finish();
476 }
477
478 /**
479 * decrypt data for the router
480 *
481 * @param string $data
482 * @return string
483 */
484 private function encrypt ($data) {
485 $iv = hex2bin(substr($this->challenge, 16, 16));
486 $adata = hex2bin(substr($this->challenge, 32, 16));
487 $key = hex2bin($this->derivedk);
488
489 $factory = new CryptLib\Cipher\Factory();
490 $aes = $factory->getBlockCipher('rijndael-128');
491 $aes->setKey($key);
492 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
493 $mode->encrypt($data);
494
495 return bin2hex($mode->finish());
496 }
497
498 /**
499 * get the values from array
500 *
501 * @param array $array
502 * @return array
503 */
504 private function getValues($array) {
505 $data = array();
506 foreach ($array as $item) {
507 // thank you telekom for this piece of shit
508 if ($item['vartype'] == 'template') {
509 if (is_array($item['varvalue'])) {
510 $data[$item['varid']][] = $this->getValues($item['varvalue']);
511 }
512 else {
513 // i dont know if we need this
514 $data[$item['varid']] = $item['varvalue'];
515 }
516 }
517 else {
518 if (is_array($item['varvalue'])) {
519 $data[$item['varid']] = $this->getValues($item['varvalue']);
520 }
521 else {
522 $data[$item['varid']] = $item['varvalue'];
523 }
524 }
525 }
526
527 return $data;
528 }
529
530 /**
531 * sends the encrypted request to router
532 *
533 * @param string $path
534 * @param mixed $fields
535 * @param string $cookie
536 * @return array
537 */
538 private function sentEncryptedRequest ($path, $fields, $cookie = false) {
539 $count = count($fields);
540 $fields = $this->encrypt(http_build_query($fields));
541 return $this->sentRequest($path, $fields, $cookie, $count);
542 }
543
544 /**
545 * sends the request to router
546 *
547 * @param string $path
548 * @param mixed $fields
549 * @param string $cookie
550 * @param integer $count
551 * @return array
552 */
553 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
554 $url = $this->url.$path.'?lang=en';
555 $ch = curl_init();
556 curl_setopt($ch, CURLOPT_URL, $url);
557
558 if (!empty($fields)) {
559 if (is_array($fields)) {
560 curl_setopt($ch, CURLOPT_POST, count($fields));
561 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
562 }
563 else {
564 curl_setopt($ch, CURLOPT_POST, $count);
565 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
566 }
567 }
568
569 if ($cookie === true) {
570 curl_setopt($ch, CURLOPT_COOKIE, 'challengev='.$this->challenge.'; '.$this->cookie);
571 }
572
573 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
574 curl_setopt($ch, CURLOPT_HEADER, true);
575
576 $result = curl_exec($ch);
577
578 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
579 $header = substr($result, 0, $header_size);
580 $body = substr($result, $header_size);
581 curl_close($ch);
582
583 // check if response is empty
584 if (empty($body)) {
585 throw new RouterException('empty response');
586 }
587
588 // check if body is encrypted (hex instead of json)
589 if (ctype_xdigit($body)) {
590 $body = $this->decrypt($body);
591 }
592
593 // fix invalid json
594 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
595 $body = preg_replace('/\'/i', '"', $body);
596 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
597 $body = preg_replace("/},\s+]/", "}\n]", $body);
598
599 // decode json
600 if (strpos($url, '.json') !== false) {
601 $body = json_decode($body, true);
602 }
603
604 return array('header' => $this->parse_headers($header), 'body' => $body);
605 }
606
607 /**
608 * get the csrf_token
609 *
610 * @return string
611 */
612 private function getToken () {
613 $this->checkLogin();
614
615 $path = 'html/content/overview/index.html';
616 $fields = array();
617 $data = $this->sentRequest($path, $fields, true);
618
619 $a = explode('csrf_token = "', $data['body']);
620 $a = explode('";', $a[1]);
621
622 if (isset($a[0]) && !empty($a[0])) {
623 return $a[0];
624 }
625 else {
626 throw new RouterException('unable to get csrf_token');
627 }
628 }
629
630 /**
631 * calculate the derivedk
632 *
633 * @param string $password
634 * @return string
635 */
636 private function getDerviedk ($password) {
637 $derivedk = '';
638
639 // calculate derivedk
640 if (!function_exists('hash_pbkdf2')) {
641 $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2(array('hash' => 'sha1'));
642 $derivedk = bin2hex($pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32));
643 $derivedk = substr($derivedk, 0, 32);
644 }
645 else {
646 $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
647 }
648
649 if (empty($derivedk)) {
650 throw new RouterException('unable to calculate derivedk');
651 }
652
653 return $derivedk;
654 }
655
656 /**
657 * get cookie from header data
658 *
659 * @param array $data
660 * @return string
661 */
662 private function getCookie ($data) {
663 $cookie = '';
664 if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
665 preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
666 if (isset($match[1]) && !empty($match[1])) {
667 $cookie = $match[1];
668 }
669 }
670
671 if (empty($cookie)) {
672 throw new RouterException('unable to get the session cookie from the router');
673 }
674
675 return $cookie;
676 }
677
678 /**
679 * parse the curl return header into an array
680 *
681 * @param string $response
682 * @return array
683 */
684 private function parse_headers($response) {
685 $headers = array();
686 $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
687
688 $header_text = explode("\r\n", $header_text);
689 foreach ($header_text as $i => $line) {
690 if ($i === 0) {
691 $headers['http_code'] = $line;
692 }
693 else {
694 list ($key, $value) = explode(': ', $line);
695 $headers[$key] = $value;
696 }
697 }
698
699 return $headers;
700 }
701 }