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