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