remove my test function
[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 *
14 *
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();
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 $factory = new CryptLib\Cipher\Factory();
370 $aes = $factory->getBlockCipher('rijndael-128');
371
372 $iv = hex2bin(substr($this->challenge, 16, 16));
373 $adata = hex2bin(substr($this->challenge, 32, 16));
374 $dkey = hex2bin($this->derivedk);
375 $enc = hex2bin($data);
376
377 $aes->setKey($dkey);
378 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
379
380 $mode->decrypt($enc);
381
382 return $mode->finish();
383 }
384
385 /**
386 * decrypt data for the router
387 *
388 * @param array $data
389 * @return string
390 */
391 private function encrypt ($data) {
392 $factory = new CryptLib\Cipher\Factory();
393 $aes = $factory->getBlockCipher('rijndael-128');
394
395 $iv = hex2bin(substr($this->challenge, 16, 16));
396 $adata = hex2bin(substr($this->challenge, 32, 16));
397 $dkey = hex2bin($this->derivedk);
398
399 $aes->setKey($dkey);
400 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
401 $mode->encrypt(http_build_query($data));
402
403 return bin2hex($mode->finish());
404 }
405
406 /**
407 * get the values from array
408 *
409 * @param array $array
410 * @return array
411 */
412 private function getValues($array) {
413 $data = array();
414 foreach ($array as $item) {
415 // thank you telekom for this piece of shit
416 if ($item['vartype'] == 'template') {
417 if (is_array($item['varvalue'])) {
418 $data[$item['varid']][] = $this->getValues($item['varvalue']);
419 }
420 else {
421 $data[$item['varid']] = $item['varvalue'];
422 }
423 }
424 else {
425 if (is_array($item['varvalue'])) {
426 $data[$item['varid']] = $this->getValues($item['varvalue']);
427 }
428 else {
429 $data[$item['varid']] = $item['varvalue'];
430 }
431 }
432 }
433
434 return $data;
435 }
436
437 /**
438 * sends the encrypted request to router
439 *
440 * @param string $path
441 * @param mixed $fields
442 * @param string $cookie
443 * @return array
444 */
445 private function sentEncryptedRequest ($path, $fields, $cookie = false) {
446 $count = count($fields);
447 $fields = $this->encrypt($fields);
448 return $this->sentRequest($path, $fields, $cookie, $count);
449 }
450
451 /**
452 * sends the request to router
453 *
454 * @param string $path
455 * @param mixed $fields
456 * @param string $cookie
457 * @param integer $count
458 * @return array
459 */
460 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
461 $url = $this->url.$path.'?lang=en';
462 $ch = curl_init();
463 curl_setopt($ch, CURLOPT_URL, $url);
464
465 if (!empty($fields)) {
466 if (is_array($fields)) {
467 curl_setopt($ch, CURLOPT_POST, count($fields));
468 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
469 }
470 else {
471 curl_setopt($ch, CURLOPT_POST, $count);
472 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
473 }
474 }
475
476 if ($cookie === true) {
477 curl_setopt($ch, CURLOPT_COOKIE, 'lang=en; challengev='.$this->challenge.'; '.$this->cookie);
478 }
479
480 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
481 curl_setopt($ch, CURLOPT_HEADER, true);
482
483 $result = curl_exec($ch);
484
485 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
486 $header = substr($result, 0, $header_size);
487 $body = substr($result, $header_size);
488 curl_close($ch);
489
490 // check if response is empty
491 if (empty($body)) {
492 throw new RouterException('empty response');
493 }
494
495 // check if body is encrypted (hex instead of json)
496 if (ctype_xdigit($body)) {
497 $body = $this->decrypt($body);
498 }
499
500 // fix invalid json
501 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
502 $body = preg_replace('/\'/i', '"', $body);
503 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
504 $body = preg_replace("/},\s+]/", "}\n]", $body);
505
506 // decode json
507 if (strpos($url, '.json') !== false) {
508 $body = json_decode($body, true);
509 }
510
511 return array('header' => $this->parse_headers($header), 'body' => $body);
512 }
513
514 /**
515 * get the csrf_token
516 *
517 * @return string
518 */
519 private function getToken () {
520 $this->checkLogin();
521
522 $path = 'html/content/overview/index.html';
523 $fields = array();
524 $data = $this->sentRequest($path, $fields, true);
525
526 $a = explode('csrf_token = "', $data['body']);
527 $a = explode('";', $a[1]);
528
529 if (isset($a[0]) && !empty($a[0])) {
530 return $a[0];
531 }
532 else {
533 throw new RouterException('unable to get csrf_token');
534 }
535 }
536
537 /**
538 * calculate the derivedk
539 *
540 * @param string $password
541 * @return string
542 */
543 private function getDerviedk ($password) {
544 $derivedk = '';
545
546 // calculate derivedk
547 if (!function_exists('hash_pbkdf2')) {
548 $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2(array('hash' => 'sha1'));
549 $derivedk = bin2hex($pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32));
550 $derivedk = substr($derivedk, 0, 32);
551 }
552 else {
553 $derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
554 }
555
556 if (empty($derivedk)) {
557 throw new RouterException('unable to calculate derivedk');
558 }
559
560 return $derivedk;
561 }
562
563 /**
564 * get cookie from header data
565 *
566 * @param array $data
567 * @return string
568 */
569 private function getCookie ($data) {
570 $cookie = '';
571 if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
572 preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
573 if (isset($match[1]) && !empty($match[1])) {
574 $cookie = $match[1];
575 }
576 }
577
578 if (empty($cookie)) {
579 throw new RouterException('unable to get the session cookie from the router');
580 }
581
582 return $cookie;
583 }
584
585 /**
586 * parse the curl return header into an array
587 *
588 * @param string $response
589 * @return array
590 */
591 private function parse_headers($response) {
592 $headers = array();
593 $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
594
595 $header_text = explode("\r\n", $header_text);
596 foreach ($header_text as $i => $line) {
597 if ($i === 0) {
598 $headers['http_code'] = $line;
599 }
600 else {
601 list ($key, $value) = explode(': ', $line);
602 $headers[$key] = $value;
603 }
604 }
605
606 return $headers;
607 }
608 }