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