little code style up
[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 changeConnectionStatus ($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 * get uptime based on online (connection) time
221 *
222 * @return string
223 */
224 public function getUptime () {
225 $data = $this->getData('LAN');
226 $data = $this->getValues($data);
227
228 return $data['days_online'];
229 }
230
231 /**
232 * return the given json as array
233 *
234 * @param string $file
235 * @return array
236 */
237 public function getData ($file) {
238 if ($file != 'Status') $this->checkLogin();
239
240 $path = 'data/'.$file.'.json';
241 $fields = array();
242 $data = $this->sentRequest($path, $fields, true);
243
244 return $data['body'];
245 }
246
247 /**
248 * get the router syslog
249 *
250 * @return array
251 */
252 public function getSyslog() {
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 }
262 }
263
264 /**
265 * get the Missed Calls from router
266 *
267 * @return array
268 */
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 }
279 }
280
281 /**
282 * get the Taken Calls from router
283 *
284 * @return array
285 */
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 }
296 }
297
298 /**
299 * get the Dialed Calls from router
300 *
301 * @return array
302 */
303 public function getDialedCalls() {
304 $data = $this->getData('PhoneCalls');
305 $data = $this->getValues($data);
306
307 if (isset($data['adddialedcalls'])) {
308 return $data['adddialedcalls'];
309 }
310 else {
311 return array();
312 }
313 }
314
315 /**
316 * reconnect LTE
317 *
318 * @return array
319 */
320 public function reconnectLte () {
321 $this->checkLogin();
322
323 $path = 'data/modules.json';
324 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
325 $data = $this->sentEncryptedRequest($path, $fields, true);
326
327 return $data['body'];
328 }
329
330 /**
331 * reset the router to Factory Default
332 * not tested
333 *
334 * @return array
335 */
336 public function resetToFactoryDefault () {
337 $this->checkLogin();
338
339 $path = 'data/resetAllSetting.json';
340 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
341 $data = $this->sentRequest($path, $fields, true);
342
343 return $data['body'];
344 }
345
346
347 /**
348 * check if firmware is actual
349 *
350 * @return array
351 */
352 public function checkFirmware () {
353 $this->checkLogin();
354
355 $path = 'data/checkfirmware.json';
356 $fields = array('checkfirmware' => 'true');
357 $data = $this->sentRequest($path, $fields, true);
358
359 return $data['body'];
360 }
361
362 /**
363 * decrypt data from router
364 *
365 * @param string $data
366 * @return array
367 */
368 private function decrypt ($data) {
369 $iv = hex2bin(substr($this->challenge, 16, 16));
370 $adata = hex2bin(substr($this->challenge, 32, 16));
371 $key = hex2bin($this->derivedk);
372 $enc = hex2bin($data);
373
374 $factory = new CryptLib\Cipher\Factory();
375 $aes = $factory->getBlockCipher('rijndael-128');
376 $aes->setKey($key);
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 *
387 * @param string $data
388 * @return string
389 */
390 private function encrypt ($data) {
391 $iv = hex2bin(substr($this->challenge, 16, 16));
392 $adata = hex2bin(substr($this->challenge, 32, 16));
393 $key = hex2bin($this->derivedk);
394
395 $factory = new CryptLib\Cipher\Factory();
396 $aes = $factory->getBlockCipher('rijndael-128');
397 $aes->setKey($key);
398 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
399 $mode->encrypt($data);
400
401 return bin2hex($mode->finish());
402 }
403
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) {
413 // thank you telekom for this piece of shit
414 if ($item['vartype'] == 'template') {
415 if (is_array($item['varvalue'])) {
416 $data[$item['varid']][] = $this->getValues($item['varvalue']);
417 }
418 else {
419 // i dont know if we need this
420 $data[$item['varid']] = $item['varvalue'];
421 }
422 }
423 else {
424 if (is_array($item['varvalue'])) {
425 $data[$item['varid']] = $this->getValues($item['varvalue']);
426 }
427 else {
428 $data[$item['varid']] = $item['varvalue'];
429 }
430 }
431 }
432
433 return $data;
434 }
435
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);
446 $fields = $this->encrypt(http_build_query($fields));
447 return $this->sentRequest($path, $fields, $cookie, $count);
448 }
449
450 /**
451 * sends the request to router
452 *
453 * @param string $path
454 * @param mixed $fields
455 * @param string $cookie
456 * @param integer $count
457 * @return array
458 */
459 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
460 $url = $this->url.$path.'?lang=en';
461 $ch = curl_init();
462 curl_setopt($ch, CURLOPT_URL, $url);
463
464 if (!empty($fields)) {
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 }
473 }
474
475 if ($cookie === true) {
476 curl_setopt($ch, CURLOPT_COOKIE, 'lang=en; challengev='.$this->challenge.'; '.$this->cookie);
477 }
478
479 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
480 curl_setopt($ch, CURLOPT_HEADER, true);
481
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
489 // check if response is empty
490 if (empty($body)) {
491 throw new RouterException('empty response');
492 }
493
494 // check if body is encrypted (hex instead of json)
495 if (ctype_xdigit($body)) {
496 $body = $this->decrypt($body);
497 }
498
499 // fix invalid json
500 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
501 $body = preg_replace('/\'/i', '"', $body);
502 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
503 $body = preg_replace("/},\s+]/", "}\n]", $body);
504
505 // decode json
506 if (strpos($url, '.json') !== false) {
507 $body = json_decode($body, true);
508 }
509
510 return array('header' => $this->parse_headers($header), 'body' => $body);
511 }
512
513 /**
514 * get the csrf_token
515 *
516 * @return string
517 */
518 private function getToken () {
519 $this->checkLogin();
520
521 $path = 'html/content/overview/index.html';
522 $fields = array();
523 $data = $this->sentRequest($path, $fields, true);
524
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 {
532 throw new RouterException('unable to get csrf_token');
533 }
534 }
535
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')) {
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));
549 $derivedk = substr($derivedk, 0, 32);
550 }
551 else {
552 $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
553 }
554
555 if (empty($derivedk)) {
556 throw new RouterException('unable to calculate derivedk');
557 }
558
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) {
569 $cookie = '';
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])) {
573 $cookie = $match[1];
574 }
575 }
576
577 if (empty($cookie)) {
578 throw new RouterException('unable to get the session cookie from the router');
579 }
580
581 return $cookie;
582 }
583
584 /**
585 * parse the curl return header into an array
586 *
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
594 $header_text = explode("\r\n", $header_text);
595 foreach ($header_text as $i => $line) {
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 }
607 }