4aa517d0d500bc55e985ec3509f0bc1dc441486a
[GitHub/Stricted/speedport-hybrid-php-api.git] / speedport.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 speedport {
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 ($password, $url = 'http://speedport.ip/') {
45 $this->url = $url;
46 $this->getChallenge();
47
48 if (empty($this->challenge)) {
49 throw new Exception('unable to get the challenge from the router');
50 }
51
52 $login = $this->login($password);
53
54 if ($login === false) {
55 throw new Exception('unable to login');
56 }
57 }
58
59 /**
60 * Requests the password-challenge from the router.
61 */
62 public function getChallenge () {
63 $path = 'data/Login.json';
64 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'challengev' => 'null');
65 $data = $this->sentRequest($path, $fields);
66 $data = json_decode($data['body'], true);
67 $data = $this->getValues($data);
68
69 if (isset($data['challengev']) && !empty($data['challengev'])) {
70 $this->challenge = $data[1]['varvalue'];
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 $path = 'data/Login.json';
82 $this->hash = hash('sha256', $this->challenge.':'.$password);
83 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash);
84 $data = $this->sentRequest($path, $fields);
85 $json = json_decode($data['body'], true);
86 $json = $this->getValues($json);
87 if (isset($json['login']) && $json['login'] == 'success') {
88 if (isset($data['header']['Set-Cookie']) && !empty($data['header']['Set-Cookie'])) {
89 preg_match('/^.*(SessionID_R3=[a-z0-9]*).*/i', $data['header']['Set-Cookie'], $match);
90 if (isset($match[1]) && !empty($match[1])) {
91 $this->session = $match[1];
92 }
93 else {
94 throw new Exception('unable to get the session cookie from the router');
95 }
96
97 // calculate derivedk
98 $this->derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
99
100 // get the csrf_token
101 $this->token = $this->getToken();
102
103 return true;
104 }
105 }
106
107 return false;
108 }
109
110 /**
111 * logout
112 *
113 * @return array
114 */
115 public function logout () {
116 $path = 'data/Login.json';
117 $fields = array('logout' => 'byby');
118 $data = $this->sentRequest($path, $fields);
119 // reset challenge and session
120 $this->challenge = '';
121 $this->session = '';
122 $this->token = "";
123
124 $json = json_decode($data['body'], true);
125
126 return $json;
127 }
128
129 /**
130 * reboot the router
131 *
132 * @return array
133 */
134 public function reboot () {
135 $path = 'data/Reboot.json';
136 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reboot_device' => 'true');
137 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
138 $data = $this->sentRequest($path, $fields, $cookie);
139
140 $json = json_decode($data['body'], true);
141
142 return $json;
143 }
144
145 /**
146 * change dsl connection status
147 *
148 * @param string $status
149 */
150 public function changeConnectionStatus ($status) {
151 $path = 'data/Connect.json';
152
153 if ($status == 'online' || $status == 'offline') {
154 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'req_connect' => $status);
155 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
156 $data = $this->sentRequest($path, $fields, $cookie);
157
158 $json = json_decode($this->decrypt($data['body']), true);
159
160 return $json;
161 }
162 else {
163 throw new Exception();
164 }
165 }
166
167 /**
168 * return the given json as array
169 *
170 * the following paths are known to be valid:
171 * /data/dsl.json
172 * /data/interfaces.json
173 * /data/arp.json
174 * /data/session.json
175 * /data/dhcp_client.json
176 * /data/dhcp_server.json
177 * /data/ipv6.json
178 * /data/dns.json
179 * /data/routing.json
180 * /data/igmp_proxy.json
181 * /data/igmp_snooping.json
182 * /data/wlan.json
183 * /data/module.json
184 * /data/memory.json
185 * /data/speed.json
186 * /data/webdav.json
187 * /data/bonding_client.json
188 * /data/bonding_tunnel.json
189 * /data/filterlist.json
190 * /data/bonding_tr181.json
191 * /data/letinfo.json
192 *
193 * /data/Status.json (No login needed)
194 *
195 * @param string $file
196 * @return array
197 */
198 public function getData ($file) {
199 $path = 'data/'.$file.'.json';
200 $fields = array();
201 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
202 $data = $this->sentRequest($path, $fields, $cookie);
203
204 if (empty($data['body'])) {
205 throw new Exception('unable to get '.$file.' data');
206 }
207
208 $json = json_decode($data['body'], true);
209
210 return $json;
211 }
212
213 /**
214 * get the router syslog
215 *
216 * @return array
217 */
218 public function getSyslog() {
219 $path = 'data/Syslog.json';
220 $fields = array('exporttype' => '0');
221 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
222 $data = $this->sentRequest($path, $fields, $cookie);
223
224 if (empty($data['body'])) {
225 throw new Exception('unable to get syslog data');
226 }
227
228 return explode("\n", $data['body']);
229 }
230
231 /**
232 * get the Missed Calls from router
233 *
234 * @return array
235 */
236 public function getMissedCalls() {
237 $path = 'data/ExportMissedCalls.json';
238 $fields = array('exporttype' => '1');
239 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
240 $data = $this->sentRequest($path, $fields, $cookie);
241
242 if (empty($data['body'])) {
243 throw new Exception('unable to get syslog data');
244 }
245
246 return explode("\n", $data['body']);
247 }
248
249 /**
250 * get the Taken Calls from router
251 *
252 * @return array
253 */
254 public function getTakenCalls() {
255 $path = 'data/ExportTakenCalls.json';
256 $fields = array('exporttype' => '2');
257 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
258 $data = $this->sentRequest($path, $fields, $cookie);
259
260 if (empty($data['body'])) {
261 throw new Exception('unable to get syslog data');
262 }
263
264 return explode("\n", $data['body']);
265 }
266
267 /**
268 * get the Dialed Calls from router
269 *
270 * @return array
271 */
272 public function getDialedCalls() {
273 $path = 'data/ExportDialedCalls.json';
274 $fields = array('exporttype' => '3');
275 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
276 $data = $this->sentRequest($path, $fields, $cookie);
277
278 if (empty($data['body'])) {
279 throw new Exception('unable to get syslog data');
280 }
281
282 return explode("\n", $data['body']);
283 }
284
285 /**
286 * reconnect LTE
287 *
288 * @return array
289 */
290 public function reconnectLte () {
291 $path = 'data/modules.json';
292 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
293 $fields = $this->encrypt($fields);
294 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
295 $data = $this->sentRequest($path, $fields, $cookie, 2);
296 $json = json_decode($data['body'], true);
297
298 return $json;
299 }
300
301 /*
302 // i dont want test this :D, feel free to test it and report if it works or not
303 public function resetToFactoryDefault () {
304 $path = 'data/resetAllSetting.json';
305 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
306 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
307 $data = $this->sentRequest($path, $fields, $cookie);
308 $json = json_decode($data['body'], true);
309
310 return $json;
311 }
312 */
313
314 /**
315 * check if firmware is actual
316 *
317 * @return array
318 */
319 public function checkFirmware () {
320 $path = 'data/checkfirmware.json';
321 $fields = array('checkfirmware' => 'true');
322 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
323 $data = $this->sentRequest($path, $fields, $cookie);
324
325 if (empty($data['body'])) {
326 throw new Exception('unable to get checkfirmware data');
327 }
328
329 $json = json_decode($data['body'], true);
330
331 return $json;
332 }
333
334 /**
335 * decrypt data from router
336 *
337 * @param string $data
338 * @return array
339 */
340 private function decrypt ($data) {
341 require_once 'CryptLib/CryptLib.php';
342 $factory = new CryptLib\Cipher\Factory();
343 $aes = $factory->getBlockCipher('rijndael-128');
344
345 $iv = hex2bin(substr($this->challenge, 16, 16));
346 $adata = hex2bin(substr($this->challenge, 32, 16));
347 $dkey = hex2bin($this->derivedk);
348 $enc = hex2bin($data);
349
350 $aes->setKey($dkey);
351 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
352
353 $mode->decrypt($enc);
354
355 return $mode->finish();
356 }
357
358 /**
359 * decrypt data for the router
360 *
361 * @param array $data
362 * @return string
363 */
364 private function encrypt ($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
373 $aes->setKey($dkey);
374 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
375 $mode->encrypt(http_build_query($data));
376
377 return bin2hex($mode->finish());
378 }
379
380 /**
381 * get the values from array
382 *
383 * @param array $array
384 * @return array
385 */
386 private function getValues($array) {
387 $data = array();
388 foreach ($array as $item) {
389 $data[$item['varid']] = $item['varvalue'];
390 }
391
392 return $data;
393 }
394
395 /**
396 * sends the request to router
397 *
398 * @param string $path
399 * @param mixed $fields
400 * @param string $cookie
401 * @param integer $count
402 * @return array
403 */
404 private function sentRequest ($path, $fields, $cookie = '', $count = 0) {
405 $url = $this->url.$path;
406 $ch = curl_init();
407 curl_setopt($ch, CURLOPT_URL, $url);
408
409 if (!empty($fields)) {
410 if (is_array($fields)) {
411 curl_setopt($ch, CURLOPT_POST, count($fields));
412 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
413 }
414 else {
415 curl_setopt($ch, CURLOPT_POST, $count);
416 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
417 }
418 }
419
420 if (!empty($cookie)) {
421 curl_setopt($ch, CURLOPT_COOKIE, $cookie);
422 }
423
424 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
425 curl_setopt($ch, CURLOPT_HEADER, true);
426
427
428 if ($cookie) {
429
430 }
431
432 $result = curl_exec($ch);
433
434 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
435 $header = substr($result, 0, $header_size);
436 $body = substr($result, $header_size);
437 curl_close($ch);
438
439 // fix invalid json
440
441 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
442 $body = preg_replace('/\'/i', '"', $body);
443 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
444 $body = preg_replace("/},\s+]/", "}\n]", $body);
445
446 return array('header' => $this->parse_headers($header), 'body' => $body);
447 }
448
449 /**
450 * get the csrf_token
451 *
452 * @return string
453 */
454 private function getToken () {
455 $path = 'html/content/overview/index.html?lang=de';
456 $fields = array();
457 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
458 $data = $this->sentRequest($path, $fields, $cookie);
459
460 if (empty($data['body'])) {
461 throw new Exception('unable to get csrf_token');
462 }
463
464 $a = explode('csrf_token = "', $data['body']);
465 $a = explode('";', $a[1]);
466
467 if (isset($a[0]) && !empty($a[0])) {
468 return $a[0];
469 }
470 else {
471 throw new Exception('unable to get csrf_token');
472 }
473 }
474
475 /**
476 * parse the curl return header into an array
477 *
478 * @param string $response
479 * @return array
480 */
481 private function parse_headers($response) {
482 $headers = array();
483 $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
484
485 foreach (explode("\r\n", $header_text) as $i => $line) {
486 if ($i === 0) {
487 $headers['http_code'] = $line;
488 }
489 else {
490 list ($key, $value) = explode(': ', $line);
491 $headers[$key] = $value;
492 }
493 }
494
495 return $headers;
496 }
497 }