simplify encryption and decryption of router requests and define own exceptions
[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.2';
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 $session = '';
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 = json_decode($data['body'], true);
65 $data = $this->getValues($data);
66
67 if (isset($data['challengev']) && !empty($data['challengev'])) {
68 $this->challenge = $data['challengev'];
69 }
70 }
71
72 /**
73 * login into the router with the given password
74 *
75 * @param string $password
76 * @return boolean
77 */
78 public function login ($password) {
79 $this->getChallenge();
80
81 if (empty($this->challenge)) {
82 throw new RouterExeption('unable to get the challenge from the router');
83 }
84
85 $path = 'data/Login.json';
86 $this->hash = hash('sha256', $this->challenge.':'.$password);
87 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash);
88 $data = $this->sentRequest($path, $fields);
89 $json = json_decode($data['body'], true);
90 $json = $this->getValues($json);
91 if (isset($json['login']) && $json['login'] == 'success') {
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 {
98 throw new RouterExeption('unable to get the session cookie from the router');
99 }
100
101 // calculate derivedk
102 if (!function_exists("hash_pbkdf2")) {
103 require_once 'CryptLib/CryptLib.php';
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);
107 }
108 else {
109 $this->derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
110 }
111
112 // get the csrf_token
113 $this->token = $this->getToken();
114
115 if ($this->checkLogin() === true) {
116 return true;
117 }
118 }
119 }
120
121 return false;
122 }
123
124 /**
125 * check if we are logged in
126 *
127 * @return boolean
128 */
129 public function checkLogin () {
130 if (empty($this->challenge) && empty($this->session)) {
131 return false;
132 }
133
134 $path = 'data/SecureStatus.json';
135 $fields = array();
136 $data = $this->sentRequest($path, $fields, true);
137
138 if (empty($data['body'])) {
139 throw new RouterExeption('unable to get SecureStatus data');
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
152 /**
153 * logout
154 *
155 * @return array
156 */
157 public function logout () {
158 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
159
160 $path = 'data/Login.json';
161 $fields = array('csrf_token' => $this->token, 'logout' => 'byby');
162 $data = $this->sentRequest($path, $fields, true);
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 {
174 throw new RouterExeption('logout failed');
175 }
176 }
177
178 /**
179 * reboot the router
180 *
181 * @return array
182 */
183 public function reboot () {
184 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
185
186 $path = 'data/Reboot.json';
187 $fields = array('csrf_token' => $this->token, 'reboot_device' => 'true');
188 $data = $this->sentEncryptedRequest($path, $fields, true);
189
190 $json = json_decode($data['body'], true);
191 $json = $this->getValues($json);
192
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 }
201 }
202
203 /**
204 * change dsl connection status
205 *
206 * @param string $status
207 */
208 public function changeConnectionStatus ($status) {
209 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
210
211 $path = 'data/Connect.json';
212
213 if ($status == 'online' || $status == 'offline') {
214 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'req_connect' => $status);
215 $data = $this->sentRequest($path, $fields, true);
216
217 $json = json_decode($data['body'], true);
218
219 return $json;
220 }
221 else {
222 throw new RouterExeption();
223 }
224 }
225
226 /**
227 * return the given json as array
228 *
229 * @param string $file
230 * @return array
231 */
232 public function getData ($file) {
233 if ($this->checkLogin() !== true && $file != "Status") throw new RouterExeption('you musst be logged in to use this method');
234
235 $path = 'data/'.$file.'.json';
236 $fields = array();
237 $data = $this->sentRequest($path, $fields, true);
238
239 if (empty($data['body'])) {
240 throw new RouterExeption('unable to get '.$file.' data');
241 }
242
243 $json = json_decode($data['body'], true);
244
245 return $json;
246 }
247
248 /**
249 * get the router syslog
250 *
251 * @return array
252 */
253 public function getSyslog() {
254 return $this->exportData('0');
255 }
256
257 /**
258 * get the Missed Calls from router
259 *
260 * @return array
261 */
262 public function getMissedCalls() {
263 return $this->exportData('1');
264 }
265
266 /**
267 * get the Taken Calls from router
268 *
269 * @return array
270 */
271 public function getTakenCalls() {
272 return $this->exportData('2');
273 }
274
275 /**
276 * get the Dialed Calls from router
277 *
278 * @return array
279 */
280 public function getDialedCalls() {
281 return $this->exportData('3');
282 }
283
284 /**
285 * export data from router
286 *
287 * @return array
288 */
289 private function exportData ($type) {
290 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
291
292 $path = 'data/Syslog.json';
293 $fields = array('exporttype' => $type);
294 $data = $this->sentRequest($path, $fields, true);
295
296 if (empty($data['body'])) {
297 throw new RouterExeption('unable to get export data');
298 }
299
300 return explode("\n", $data['body']);
301 }
302
303 /**
304 * reconnect LTE
305 *
306 * @return array
307 */
308 public function reconnectLte () {
309 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
310
311 $path = 'data/modules.json';
312 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
313 $data = $this->sentEncryptedRequest($path, $fields, true);
314 $json = json_decode($data['body'], true);
315
316 return $json;
317 }
318
319 /**
320 * reset the router to Factory Default
321 * not tested
322 *
323 * @return array
324 */
325 public function resetToFactoryDefault () {
326 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
327
328 $path = 'data/resetAllSetting.json';
329 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
330 $data = $this->sentRequest($path, $fields, true);
331 $json = json_decode($data['body'], true);
332
333 return $json;
334 }
335
336
337 /**
338 * check if firmware is actual
339 *
340 * @return array
341 */
342 public function checkFirmware () {
343 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
344
345 $path = 'data/checkfirmware.json';
346 $fields = array('checkfirmware' => 'true');
347 $data = $this->sentRequest($path, $fields, true);
348
349 if (empty($data['body'])) {
350 throw new RouterExeption('unable to get checkfirmware data');
351 }
352
353 $json = json_decode($data['body'], true);
354
355 return $json;
356 }
357
358 /**
359 * decrypt data from router
360 *
361 * @param string $data
362 * @return array
363 */
364 private function decrypt ($data) {
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 */
388 private function encrypt ($data) {
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
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 $data[$item['varid']] = $item['varvalue'];
414 }
415
416 return $data;
417 }
418
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
433 /**
434 * sends the request to router
435 *
436 * @param string $path
437 * @param mixed $fields
438 * @param string $cookie
439 * @param integer $count
440 * @return array
441 */
442 private function sentRequest ($path, $fields, $cookie = false, $count = 0) {
443 $url = $this->url.$path.'?lang=en';
444 $ch = curl_init();
445 curl_setopt($ch, CURLOPT_URL, $url);
446
447 if (!empty($fields)) {
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 }
456 }
457
458 if ($cookie === true) {
459 curl_setopt($ch, CURLOPT_COOKIE, 'challengev='.$this->challenge.'; '.$this->session);
460 }
461
462 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
463 curl_setopt($ch, CURLOPT_HEADER, true);
464
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
476 // check if body is encrypted (hex instead of json)
477 if (ctype_xdigit($body)) {
478 $body = $this->decrypt($body);
479 }
480
481 // fix invalid json
482 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
483 $body = preg_replace('/\'/i', '"', $body);
484 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
485 $body = preg_replace("/},\s+]/", "}\n]", $body);
486
487 return array('header' => $this->parse_headers($header), 'body' => $body);
488 }
489
490 /**
491 * get the csrf_token
492 *
493 * @return string
494 */
495 private function getToken () {
496 if ($this->checkLogin() !== true) throw new RouterExeption('you musst be logged in to use this method');
497
498 $path = 'html/content/overview/index.html';
499 $fields = array();
500 $data = $this->sentRequest($path, $fields, true);
501
502 if (empty($data['body'])) {
503 throw new RouterExeption('unable to get csrf_token');
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 {
513 throw new RouterExeption('unable to get csrf_token');
514 }
515 }
516
517 /**
518 * parse the curl return header into an array
519 *
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
527 $header_text = explode("\r\n", $header_text);
528 foreach ($header_text as $i => $line) {
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 }
540 }