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