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