apply small fix for syslos
[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');
4
1d934afe
S
5/**
6 * @author Jan Altensen (Stricted)
7 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
8 * @copyright 2015 Jan Altensen (Stricted)
9 */
21f877e4 10class SpeedportHybrid {
0dca2d61
S
11 /**
12 *
13 *
14 */
219ba661 15 const VERSION = '1.0.3';
0dca2d61 16
a91317a6
S
17 /**
18 * password-challenge
19 * @var string
20 */
21 private $challenge = '';
22
809e25bd
S
23 /**
24 * csrf_token
25 * @var string
26 */
27 private $token = '';
28
a91317a6
S
29 /**
30 * hashed password
31 * @var string
32 */
33 private $hash = '';
34
35 /**
36 * session cookie
37 * @var string
38 */
ac344b92 39 private $cookie = '';
a91317a6
S
40
41 /**
42 * router url
43 * @var string
44 */
b5a532a8 45 private $url = '';
a91317a6 46
c9e082da
S
47 /**
48 * derivedk cookie
49 * @var string
50 */
51 private $derivedk = '';
52
e58a96d1 53 public function __construct ($url = 'http://speedport.ip/') {
b5a532a8 54 $this->url = $url;
a91317a6
S
55 }
56
57 /**
58 * Requests the password-challenge from the router.
59 */
e58a96d1 60 private function getChallenge () {
b5a532a8 61 $path = 'data/Login.json';
a91317a6 62 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'challengev' => 'null');
b5a532a8 63 $data = $this->sentRequest($path, $fields);
219ba661 64 $data = $this->getValues($data['body']);
c2678616
S
65
66 if (isset($data['challengev']) && !empty($data['challengev'])) {
ac344b92
S
67 return $data['challengev'];
68 }
69 else {
219ba661 70 throw new RouterException('unable to get the challenge from the router');
a91317a6
S
71 }
72 }
73
74 /**
75 * login into the router with the given password
5e44cffa 76 *
a91317a6
S
77 * @param string $password
78 * @return boolean
79 */
80 public function login ($password) {
ac344b92 81 $this->challenge = $this->getChallenge();
e58a96d1 82
b5a532a8 83 $path = 'data/Login.json';
a91317a6
S
84 $this->hash = hash('sha256', $this->challenge.':'.$password);
85 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash);
b5a532a8 86 $data = $this->sentRequest($path, $fields);
219ba661 87 $json = $this->getValues($data['body']);
ac344b92 88
c2678616 89 if (isset($json['login']) && $json['login'] == 'success') {
ac344b92
S
90 $this->cookie = $this->getCookie($data);
91
92 $this->derivedk = $this->getDerviedk($password);
93
94 // get the csrf_token
95 $this->token = $this->getToken();
96
97 if ($this->checkLogin(false) === true) {
98 return true;
a91317a6
S
99 }
100 }
101
102 return false;
103 }
104
df1e1394
S
105 /**
106 * check if we are logged in
107 *
adcedd8b
S
108 * @param boolean $exception
109 * @return boolean
df1e1394 110 */
adcedd8b 111 public function checkLogin ($exception = true) {
ac344b92
S
112 // check if challenge or session is empty
113 if (empty($this->challenge) || empty($this->cookie)) {
adcedd8b 114 if ($exception === true) {
219ba661 115 throw new RouterException('you musst be logged in to use this method');
adcedd8b
S
116 }
117
0dca2d61
S
118 return false;
119 }
120
34701575 121 $path = 'data/SecureStatus.json';
df1e1394 122 $fields = array();
0dca2d61 123 $data = $this->sentRequest($path, $fields, true);
219ba661 124 $data = $this->getValues($data['body']);
df1e1394 125
219ba661 126 if ($data['loginstate'] != 1) {
adcedd8b 127 if ($exception === true) {
219ba661 128 throw new RouterException('you musst be logged in to use this method');
adcedd8b
S
129 }
130
df1e1394
S
131 return false;
132 }
133
134 return true;
135 }
136
a91317a6
S
137 /**
138 * logout
5e44cffa 139 *
58feafa2 140 * @return boolean
a91317a6
S
141 */
142 public function logout () {
adcedd8b 143 $this->checkLogin();
e58a96d1 144
b5a532a8 145 $path = 'data/Login.json';
df1e1394 146 $fields = array('csrf_token' => $this->token, 'logout' => 'byby');
219ba661
S
147 $data = $this->sentRequest($path, $fields, true);
148 $data = $this->getValues($data['body']);
149 if ((isset($data['status']) && $data['status'] == 'ok') && $this->checkLogin(false) === false) {
df1e1394
S
150 // reset challenge and session
151 $this->challenge = '';
ac344b92
S
152 $this->cookie = '';
153 $this->token = '';
154 $this->derivedk = '';
df1e1394 155
58feafa2 156 return true;
df1e1394 157 }
58feafa2
S
158
159 return false;
a91317a6
S
160 }
161
162 /**
163 * reboot the router
5e44cffa 164 *
58feafa2 165 * @return boolean
a91317a6
S
166 */
167 public function reboot () {
adcedd8b 168 $this->checkLogin();
e58a96d1 169
b5a532a8 170 $path = 'data/Reboot.json';
8162139f
S
171 $fields = array('csrf_token' => $this->token, 'reboot_device' => 'true');
172 $data = $this->sentEncryptedRequest($path, $fields, true);
219ba661 173 $data = $this->getValues($data['body']);
14d4f286 174
219ba661 175 if ($data['status'] == 'ok') {
8162139f
S
176 // throw an exception because router is unavailable for other tasks
177 // like $this->logout() or $this->checkLogin
178 throw new RebootException('Router Reboot');
179 }
58feafa2
S
180
181 return false;
a91317a6
S
182 }
183
87026df3
S
184 /**
185 * change dsl connection status
5e44cffa 186 *
87026df3 187 * @param string $status
58feafa2 188 * @return boolean
87026df3
S
189 */
190 public function changeConnectionStatus ($status) {
adcedd8b 191 $this->checkLogin();
e58a96d1 192
b5a532a8 193 $path = 'data/Connect.json';
87026df3
S
194
195 if ($status == 'online' || $status == 'offline') {
196 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'req_connect' => $status);
0dca2d61 197 $data = $this->sentRequest($path, $fields, true);
219ba661 198 $data = $this->getValues($data['body']);
c2678616 199
219ba661 200 if ($data['status'] == 'ok') {
58feafa2
S
201 return true;
202 }
203 else {
204 return false;
205 }
87026df3
S
206 }
207 else {
219ba661 208 throw new RouterException();
87026df3
S
209 }
210 }
211
58feafa2
S
212 /**
213 * get uptime based on online (connection) time
214 *
215 * @return string
216 */
217 public function getUptime () {
218 // TODO: search for a better solution, calling Connect.json need some time
219 $data = $this->getData('Connect');
220 $data = $this->getValues($data);
221
222 return $data['days_online'];
223 }
224
a91317a6
S
225 /**
226 * return the given json as array
5e44cffa 227 *
a91317a6
S
228 * @param string $file
229 * @return array
230 */
231 public function getData ($file) {
ac344b92 232 if ($file != 'Status') $this->checkLogin();
e58a96d1 233
b5a532a8 234 $path = 'data/'.$file.'.json';
a91317a6 235 $fields = array();
0dca2d61 236 $data = $this->sentRequest($path, $fields, true);
a91317a6 237
219ba661 238 return $data['body'];
a91317a6
S
239 }
240
5e44cffa
S
241 /**
242 * get the router syslog
243 *
244 * @return array
245 */
246 public function getSyslog() {
0dca2d61 247 return $this->exportData('0');
5e44cffa
S
248 }
249
a35e3e67
S
250 /**
251 * get the Missed Calls from router
252 *
253 * @return array
254 */
255 public function getMissedCalls() {
0dca2d61 256 return $this->exportData('1');
a35e3e67
S
257 }
258
15260eeb
S
259 /**
260 * get the Taken Calls from router
261 *
262 * @return array
263 */
264 public function getTakenCalls() {
0dca2d61 265 return $this->exportData('2');
15260eeb
S
266 }
267
abf641bb
S
268 /**
269 * get the Dialed Calls from router
270 *
271 * @return array
272 */
273 public function getDialedCalls() {
0dca2d61
S
274 return $this->exportData('3');
275 }
276
277 /**
278 * export data from router
279 *
280 * @return array
281 */
282 private function exportData ($type) {
adcedd8b 283 $this->checkLogin();
e58a96d1 284
b383ace1 285 $path = 'data/Syslog.json';
0dca2d61
S
286 $fields = array('exporttype' => $type);
287 $data = $this->sentRequest($path, $fields, true);
9bd25bb4 288
abf641bb
S
289 return explode("\n", $data['body']);
290 }
291
809e25bd
S
292 /**
293 * reconnect LTE
294 *
295 * @return array
296 */
c9e082da 297 public function reconnectLte () {
adcedd8b 298 $this->checkLogin();
e58a96d1 299
c9e082da 300 $path = 'data/modules.json';
809e25bd 301 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
8162139f 302 $data = $this->sentEncryptedRequest($path, $fields, true);
c9e082da 303
219ba661 304 return $data['body'];
c9e082da 305 }
809e25bd 306
7f4a51d2
S
307 /**
308 * reset the router to Factory Default
309 * not tested
310 *
311 * @return array
312 */
9bd25bb4 313 public function resetToFactoryDefault () {
adcedd8b 314 $this->checkLogin();
e58a96d1 315
9bd25bb4
S
316 $path = 'data/resetAllSetting.json';
317 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
0dca2d61 318 $data = $this->sentRequest($path, $fields, true);
9bd25bb4 319
219ba661 320 return $data['body'];
9bd25bb4 321 }
7f4a51d2 322
9bd25bb4 323
4ae464d1
S
324 /**
325 * check if firmware is actual
326 *
327 * @return array
328 */
329 public function checkFirmware () {
adcedd8b 330 $this->checkLogin();
e58a96d1 331
4ae464d1
S
332 $path = 'data/checkfirmware.json';
333 $fields = array('checkfirmware' => 'true');
0dca2d61 334 $data = $this->sentRequest($path, $fields, true);
4ae464d1 335
219ba661 336 return $data['body'];
4ae464d1
S
337 }
338
14d4f286
S
339 /**
340 * decrypt data from router
341 *
342 * @param string $data
343 * @return array
344 */
c2678616 345 private function decrypt ($data) {
14d4f286
S
346 require_once 'CryptLib/CryptLib.php';
347 $factory = new CryptLib\Cipher\Factory();
348 $aes = $factory->getBlockCipher('rijndael-128');
349
350 $iv = hex2bin(substr($this->challenge, 16, 16));
351 $adata = hex2bin(substr($this->challenge, 32, 16));
352 $dkey = hex2bin($this->derivedk);
353 $enc = hex2bin($data);
354
355 $aes->setKey($dkey);
356 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
357
358 $mode->decrypt($enc);
359
360 return $mode->finish();
361 }
362
363 /**
364 * decrypt data for the router
365 *
366 * @param array $data
367 * @return string
368 */
c2678616 369 private function encrypt ($data) {
14d4f286
S
370 require_once 'CryptLib/CryptLib.php';
371 $factory = new CryptLib\Cipher\Factory();
372 $aes = $factory->getBlockCipher('rijndael-128');
373
374 $iv = hex2bin(substr($this->challenge, 16, 16));
375 $adata = hex2bin(substr($this->challenge, 32, 16));
376 $dkey = hex2bin($this->derivedk);
377
378 $aes->setKey($dkey);
379 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
380 $mode->encrypt(http_build_query($data));
381
809e25bd 382 return bin2hex($mode->finish());
14d4f286
S
383 }
384
c2678616
S
385 /**
386 * get the values from array
387 *
388 * @param array $array
389 * @return array
390 */
391 private function getValues($array) {
392 $data = array();
393 foreach ($array as $item) {
8b7e3972
S
394 // thank you telekom for this piece of bullshit
395 if ($item['vartype'] == 'template') {
58feafa2
S
396 $data[$item['varid']] = $this->getValues($item['varvalue']);
397 }
398 else {
8b7e3972
S
399 if (is_array($item['varvalue'])) {
400 $data[$item['varid']] = $this->getValues($item['varvalue']);
401 }
402 else {
403 $data[$item['varid']] = $item['varvalue'];
404 }
58feafa2 405 }
c2678616
S
406 }
407
408 return $data;
409 }
410
8162139f
S
411 /**
412 * sends the encrypted request to router
413 *
414 * @param string $path
415 * @param mixed $fields
416 * @param string $cookie
417 * @return array
418 */
419 private function sentEncryptedRequest ($path, $fields, $cookie = false) {
420 $count = count($fields);
421 $fields = $this->encrypt($fields);
422 return $this->sentRequest($path, $fields, $cookie, $count);
423 }
424
a91317a6
S
425 /**
426 * sends the request to router
5e44cffa 427 *
b5a532a8 428 * @param string $path
809e25bd 429 * @param mixed $fields
a91317a6 430 * @param string $cookie
809e25bd 431 * @param integer $count
a91317a6
S
432 * @return array
433 */
0dca2d61 434 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
49abc701 435 $url = $this->url.$path.'?lang=en';
a91317a6
S
436 $ch = curl_init();
437 curl_setopt($ch, CURLOPT_URL, $url);
438
439 if (!empty($fields)) {
809e25bd
S
440 if (is_array($fields)) {
441 curl_setopt($ch, CURLOPT_POST, count($fields));
442 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
443 }
444 else {
445 curl_setopt($ch, CURLOPT_POST, $count);
446 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
447 }
a91317a6
S
448 }
449
0dca2d61 450 if ($cookie === true) {
8b7e3972 451 curl_setopt($ch, CURLOPT_COOKIE, 'lang=en; challengev='.$this->challenge.'; '.$this->cookie);
a91317a6
S
452 }
453
454 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
455 curl_setopt($ch, CURLOPT_HEADER, true);
456
a91317a6
S
457 if ($cookie) {
458
459 }
460
461 $result = curl_exec($ch);
462
463 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
464 $header = substr($result, 0, $header_size);
465 $body = substr($result, $header_size);
466 curl_close($ch);
467
219ba661
S
468 // check if response is empty
469 if (empty($body)) {
470 throw new RouterException('empty response');
471 }
472
8162139f
S
473 // check if body is encrypted (hex instead of json)
474 if (ctype_xdigit($body)) {
475 $body = $this->decrypt($body);
476 }
477
a91317a6
S
478 // fix invalid json
479 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
480 $body = preg_replace('/\'/i', '"', $body);
5e44cffa 481 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
dae16c50 482 $body = preg_replace("/},\s+]/", "}\n]", $body);
a91317a6 483
219ba661 484 // decode json
8b7e3972 485 if (strpos($url, '.json') !== false && strpos($url, 'Syslog.json') === false) {
219ba661
S
486 $body = json_decode($body, true);
487 }
488
a91317a6
S
489 return array('header' => $this->parse_headers($header), 'body' => $body);
490 }
491
809e25bd
S
492 /**
493 * get the csrf_token
494 *
495 * @return string
496 */
497 private function getToken () {
adcedd8b 498 $this->checkLogin();
e58a96d1 499
49abc701 500 $path = 'html/content/overview/index.html';
809e25bd 501 $fields = array();
0dca2d61 502 $data = $this->sentRequest($path, $fields, true);
809e25bd 503
809e25bd
S
504 $a = explode('csrf_token = "', $data['body']);
505 $a = explode('";', $a[1]);
506
507 if (isset($a[0]) && !empty($a[0])) {
508 return $a[0];
509 }
510 else {
219ba661 511 throw new RouterException('unable to get csrf_token');
809e25bd
S
512 }
513 }
514
ac344b92
S
515 /**
516 * calculate the derivedk
517 *
518 * @param string $password
519 * @return string
520 */
521 private function getDerviedk ($password) {
522 $derivedk = '';
523
524 // calculate derivedk
525 if (!function_exists('hash_pbkdf2')) {
526 require_once 'CryptLib/CryptLib.php';
527 $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2(array('hash' => 'sha1'));
528 $derivedk = bin2hex($pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32));
58feafa2 529 $derivedk = substr($derivedk, 0, 32);
ac344b92
S
530 }
531 else {
532 $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
533 }
534
58feafa2
S
535 if (empty($derivedk)) {
536 throw new RouterException('unable to calculate derivedk');
537 }
538
ac344b92
S
539 return $derivedk;
540 }
541
542 /**
543 * get cookie from header data
544 *
545 * @param array $data
546 * @return string
547 */
548 private function getCookie ($data) {
58feafa2 549 $cookie = '';
ac344b92
S
550 if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
551 preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
552 if (isset($match[1]) && !empty($match[1])) {
58feafa2 553 $cookie = $match[1];
ac344b92
S
554 }
555 }
556
58feafa2 557 if (empty($cookie)) {
219ba661 558 throw new RouterException('unable to get the session cookie from the router');
58feafa2
S
559 }
560
561 return $cookie;
ac344b92
S
562 }
563
a91317a6
S
564 /**
565 * parse the curl return header into an array
5e44cffa 566 *
a91317a6
S
567 * @param string $response
568 * @return array
569 */
570 private function parse_headers($response) {
571 $headers = array();
572 $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
573
7f4a51d2
S
574 $header_text = explode("\r\n", $header_text);
575 foreach ($header_text as $i => $line) {
a91317a6
S
576 if ($i === 0) {
577 $headers['http_code'] = $line;
578 }
579 else {
580 list ($key, $value) = explode(': ', $line);
581 $headers[$key] = $value;
582 }
583 }
584
585 return $headers;
586 }
7f4a51d2 587}