add and update some stuff
[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
S
12 /**
13 *
14 *
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
S
196 */
197 public function changeConnectionStatus ($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 {
219ba661 215 throw new RouterException();
87026df3
S
216 }
217 }
218
58feafa2
S
219 /**
220 * get uptime based on online (connection) time
221 *
222 * @return string
223 */
224 public function getUptime () {
aacbbd28 225 $data = $this->getData('LAN');
58feafa2
S
226 $data = $this->getValues($data);
227
228 return $data['days_online'];
229 }
230
a91317a6
S
231 /**
232 * return the given json as array
5e44cffa 233 *
a91317a6
S
234 * @param string $file
235 * @return array
236 */
237 public function getData ($file) {
ac344b92 238 if ($file != 'Status') $this->checkLogin();
e58a96d1 239
b5a532a8 240 $path = 'data/'.$file.'.json';
a91317a6 241 $fields = array();
0dca2d61 242 $data = $this->sentRequest($path, $fields, true);
a91317a6 243
219ba661 244 return $data['body'];
a91317a6
S
245 }
246
5e44cffa
S
247 /**
248 * get the router syslog
249 *
250 * @return array
251 */
252 public function getSyslog() {
aacbbd28
S
253 $data = $this->getData('SystemMessages');
254 $data = $this->getValues($data);
255
256 if (isset($data['addmessage'])) {
257 return $data['addmessage'];
258 }
259 else {
260 return array();
261 }
5e44cffa
S
262 }
263
a35e3e67 264 /**
aacbbd28 265 * get the router syslog
a35e3e67
S
266 *
267 * @return array
268 */
aacbbd28
S
269 public function test() {
270 $data = $this->getData('NASLight');
271 $data = $this->getValues($data);
272 print_r($data);
273 /*
274 $data = $this->getValues($data);
275
276 if (isset($data['addmessage'])) {
277 return $data['addmessage'];
278 }
279 else {
280 return array();
281 }
282 */
a35e3e67
S
283 }
284
15260eeb 285 /**
aacbbd28 286 * get the Missed Calls from router
15260eeb
S
287 *
288 * @return array
289 */
aacbbd28
S
290 public function getMissedCalls() {
291 $data = $this->getData('PhoneCalls');
292 $data = $this->getValues($data);
293
294 if (isset($data['addmissedcalls'])) {
295 return $data['addmissedcalls'];
296 }
297 else {
298 return array();
299 }
15260eeb
S
300 }
301
abf641bb 302 /**
aacbbd28 303 * get the Taken Calls from router
abf641bb
S
304 *
305 * @return array
306 */
aacbbd28
S
307 public function getTakenCalls() {
308 $data = $this->getData('PhoneCalls');
309 $data = $this->getValues($data);
310
311 if (isset($data['addtakencalls'])) {
312 return $data['addtakencalls'];
313 }
314 else {
315 return array();
316 }
0dca2d61
S
317 }
318
319 /**
aacbbd28 320 * get the Dialed Calls from router
0dca2d61
S
321 *
322 * @return array
323 */
aacbbd28
S
324 public function getDialedCalls() {
325 $data = $this->getData('PhoneCalls');
326 $data = $this->getValues($data);
9bd25bb4 327
aacbbd28
S
328 if (isset($data['adddialedcalls'])) {
329 return $data['adddialedcalls'];
330 }
331 else {
332 return array();
333 }
abf641bb
S
334 }
335
809e25bd
S
336 /**
337 * reconnect LTE
338 *
339 * @return array
340 */
c9e082da 341 public function reconnectLte () {
adcedd8b 342 $this->checkLogin();
e58a96d1 343
c9e082da 344 $path = 'data/modules.json';
809e25bd 345 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
8162139f 346 $data = $this->sentEncryptedRequest($path, $fields, true);
c9e082da 347
219ba661 348 return $data['body'];
c9e082da 349 }
809e25bd 350
7f4a51d2
S
351 /**
352 * reset the router to Factory Default
353 * not tested
354 *
355 * @return array
356 */
9bd25bb4 357 public function resetToFactoryDefault () {
adcedd8b 358 $this->checkLogin();
e58a96d1 359
9bd25bb4
S
360 $path = 'data/resetAllSetting.json';
361 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
0dca2d61 362 $data = $this->sentRequest($path, $fields, true);
9bd25bb4 363
219ba661 364 return $data['body'];
9bd25bb4 365 }
7f4a51d2 366
9bd25bb4 367
4ae464d1
S
368 /**
369 * check if firmware is actual
370 *
371 * @return array
372 */
373 public function checkFirmware () {
adcedd8b 374 $this->checkLogin();
e58a96d1 375
4ae464d1
S
376 $path = 'data/checkfirmware.json';
377 $fields = array('checkfirmware' => 'true');
0dca2d61 378 $data = $this->sentRequest($path, $fields, true);
4ae464d1 379
219ba661 380 return $data['body'];
4ae464d1
S
381 }
382
14d4f286
S
383 /**
384 * decrypt data from router
385 *
386 * @param string $data
387 * @return array
388 */
c2678616 389 private function decrypt ($data) {
14d4f286
S
390 $factory = new CryptLib\Cipher\Factory();
391 $aes = $factory->getBlockCipher('rijndael-128');
392
393 $iv = hex2bin(substr($this->challenge, 16, 16));
394 $adata = hex2bin(substr($this->challenge, 32, 16));
395 $dkey = hex2bin($this->derivedk);
396 $enc = hex2bin($data);
397
398 $aes->setKey($dkey);
399 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
400
401 $mode->decrypt($enc);
402
403 return $mode->finish();
404 }
405
406 /**
407 * decrypt data for the router
408 *
409 * @param array $data
410 * @return string
411 */
c2678616 412 private function encrypt ($data) {
14d4f286
S
413 $factory = new CryptLib\Cipher\Factory();
414 $aes = $factory->getBlockCipher('rijndael-128');
415
416 $iv = hex2bin(substr($this->challenge, 16, 16));
417 $adata = hex2bin(substr($this->challenge, 32, 16));
418 $dkey = hex2bin($this->derivedk);
419
420 $aes->setKey($dkey);
421 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
422 $mode->encrypt(http_build_query($data));
423
809e25bd 424 return bin2hex($mode->finish());
14d4f286
S
425 }
426
c2678616
S
427 /**
428 * get the values from array
429 *
430 * @param array $array
431 * @return array
432 */
433 private function getValues($array) {
434 $data = array();
435 foreach ($array as $item) {
aacbbd28 436 // thank you telekom for this piece of shit
8b7e3972 437 if ($item['vartype'] == 'template') {
ec351a7d
S
438 if (is_array($item['varvalue'])) {
439 $data[$item['varid']][] = $this->getValues($item['varvalue']);
440 }
441 else {
442 $data[$item['varid']] = $item['varvalue'];
443 }
58feafa2
S
444 }
445 else {
8b7e3972
S
446 if (is_array($item['varvalue'])) {
447 $data[$item['varid']] = $this->getValues($item['varvalue']);
448 }
449 else {
450 $data[$item['varid']] = $item['varvalue'];
451 }
58feafa2 452 }
c2678616
S
453 }
454
455 return $data;
456 }
457
8162139f
S
458 /**
459 * sends the encrypted request to router
460 *
461 * @param string $path
462 * @param mixed $fields
463 * @param string $cookie
464 * @return array
465 */
466 private function sentEncryptedRequest ($path, $fields, $cookie = false) {
467 $count = count($fields);
468 $fields = $this->encrypt($fields);
469 return $this->sentRequest($path, $fields, $cookie, $count);
470 }
471
a91317a6
S
472 /**
473 * sends the request to router
5e44cffa 474 *
b5a532a8 475 * @param string $path
809e25bd 476 * @param mixed $fields
a91317a6 477 * @param string $cookie
809e25bd 478 * @param integer $count
a91317a6
S
479 * @return array
480 */
0dca2d61 481 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
49abc701 482 $url = $this->url.$path.'?lang=en';
a91317a6
S
483 $ch = curl_init();
484 curl_setopt($ch, CURLOPT_URL, $url);
485
486 if (!empty($fields)) {
809e25bd
S
487 if (is_array($fields)) {
488 curl_setopt($ch, CURLOPT_POST, count($fields));
489 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
490 }
491 else {
492 curl_setopt($ch, CURLOPT_POST, $count);
493 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
494 }
a91317a6
S
495 }
496
0dca2d61 497 if ($cookie === true) {
8b7e3972 498 curl_setopt($ch, CURLOPT_COOKIE, 'lang=en; challengev='.$this->challenge.'; '.$this->cookie);
a91317a6
S
499 }
500
501 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
502 curl_setopt($ch, CURLOPT_HEADER, true);
503
a91317a6
S
504 $result = curl_exec($ch);
505
506 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
507 $header = substr($result, 0, $header_size);
508 $body = substr($result, $header_size);
509 curl_close($ch);
510
219ba661
S
511 // check if response is empty
512 if (empty($body)) {
513 throw new RouterException('empty response');
514 }
515
8162139f
S
516 // check if body is encrypted (hex instead of json)
517 if (ctype_xdigit($body)) {
518 $body = $this->decrypt($body);
519 }
520
a91317a6
S
521 // fix invalid json
522 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
523 $body = preg_replace('/\'/i', '"', $body);
5e44cffa 524 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
dae16c50 525 $body = preg_replace("/},\s+]/", "}\n]", $body);
a91317a6 526
219ba661 527 // decode json
aacbbd28 528 if (strpos($url, '.json') !== false) {
219ba661
S
529 $body = json_decode($body, true);
530 }
531
a91317a6
S
532 return array('header' => $this->parse_headers($header), 'body' => $body);
533 }
534
809e25bd
S
535 /**
536 * get the csrf_token
537 *
538 * @return string
539 */
540 private function getToken () {
adcedd8b 541 $this->checkLogin();
e58a96d1 542
49abc701 543 $path = 'html/content/overview/index.html';
809e25bd 544 $fields = array();
0dca2d61 545 $data = $this->sentRequest($path, $fields, true);
809e25bd 546
809e25bd
S
547 $a = explode('csrf_token = "', $data['body']);
548 $a = explode('";', $a[1]);
549
550 if (isset($a[0]) && !empty($a[0])) {
551 return $a[0];
552 }
553 else {
219ba661 554 throw new RouterException('unable to get csrf_token');
809e25bd
S
555 }
556 }
557
ac344b92
S
558 /**
559 * calculate the derivedk
560 *
561 * @param string $password
562 * @return string
563 */
564 private function getDerviedk ($password) {
565 $derivedk = '';
566
567 // calculate derivedk
568 if (!function_exists('hash_pbkdf2')) {
ac344b92
S
569 $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2(array('hash' => 'sha1'));
570 $derivedk = bin2hex($pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32));
58feafa2 571 $derivedk = substr($derivedk, 0, 32);
ac344b92
S
572 }
573 else {
574 $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
575 }
576
58feafa2
S
577 if (empty($derivedk)) {
578 throw new RouterException('unable to calculate derivedk');
579 }
580
ac344b92
S
581 return $derivedk;
582 }
583
584 /**
585 * get cookie from header data
586 *
587 * @param array $data
588 * @return string
589 */
590 private function getCookie ($data) {
58feafa2 591 $cookie = '';
ac344b92
S
592 if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
593 preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
594 if (isset($match[1]) && !empty($match[1])) {
58feafa2 595 $cookie = $match[1];
ac344b92
S
596 }
597 }
598
58feafa2 599 if (empty($cookie)) {
219ba661 600 throw new RouterException('unable to get the session cookie from the router');
58feafa2
S
601 }
602
603 return $cookie;
ac344b92
S
604 }
605
a91317a6
S
606 /**
607 * parse the curl return header into an array
5e44cffa 608 *
a91317a6
S
609 * @param string $response
610 * @return array
611 */
612 private function parse_headers($response) {
613 $headers = array();
614 $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
615
7f4a51d2
S
616 $header_text = explode("\r\n", $header_text);
617 foreach ($header_text as $i => $line) {
a91317a6
S
618 if ($i === 0) {
619 $headers['http_code'] = $line;
620 }
621 else {
622 list ($key, $value) = explode(': ', $line);
623 $headers[$key] = $value;
624 }
625 }
626
627 return $headers;
628 }
7f4a51d2 629}