fix for php < 5.5.0
[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 ($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['challengev'];
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 if (version_compare(phpversion(), '5.5.0', '<')) {
99 require_once 'CryptLib/CryptLib.php';
100 $pbkdf2 = new CryptLib\Key\Derivation\PBKDF\PBKDF2();
101 $this->derivedk = $pbkdf2->derive(hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
102 }
103 else {
104 $this->derivedk = hash_pbkdf2('sha1', hash('sha256', $password), substr($this->challenge, 0, 16), 1000, 32);
105 }
106
107 // get the csrf_token
108 $this->token = $this->getToken();
109
110 return true;
111 }
112 }
113
114 return false;
115 }
116
117 /**
118 * logout
119 *
120 * @return array
121 */
122 public function logout () {
123 $path = 'data/Login.json';
124 $fields = array('logout' => 'byby');
125 $data = $this->sentRequest($path, $fields);
126 // reset challenge and session
127 $this->challenge = '';
128 $this->session = '';
129 $this->token = "";
130
131 $json = json_decode($data['body'], true);
132
133 return $json;
134 }
135
136 /**
137 * reboot the router
138 *
139 * @return array
140 */
141 public function reboot () {
142 $path = 'data/Reboot.json';
143 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reboot_device' => 'true');
144 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
145 $data = $this->sentRequest($path, $fields, $cookie);
146
147 $json = json_decode($data['body'], true);
148
149 return $json;
150 }
151
152 /**
153 * change dsl connection status
154 *
155 * @param string $status
156 */
157 public function changeConnectionStatus ($status) {
158 $path = 'data/Connect.json';
159
160 if ($status == 'online' || $status == 'offline') {
161 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'req_connect' => $status);
162 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
163 $data = $this->sentRequest($path, $fields, $cookie);
164
165 $json = json_decode($this->decrypt($data['body']), true);
166
167 return $json;
168 }
169 else {
170 throw new Exception();
171 }
172 }
173
174 /**
175 * return the given json as array
176 *
177 * @param string $file
178 * @return array
179 */
180 public function getData ($file) {
181 $path = 'data/'.$file.'.json';
182 $fields = array();
183 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
184 $data = $this->sentRequest($path, $fields, $cookie);
185
186 if (empty($data['body'])) {
187 throw new Exception('unable to get '.$file.' data');
188 }
189
190 $json = json_decode($data['body'], true);
191
192 return $json;
193 }
194
195 /**
196 * get the router syslog
197 *
198 * @return array
199 */
200 public function getSyslog() {
201 $path = 'data/Syslog.json';
202 $fields = array('exporttype' => '0');
203 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
204 $data = $this->sentRequest($path, $fields, $cookie);
205
206 if (empty($data['body'])) {
207 throw new Exception('unable to get syslog data');
208 }
209
210 return explode("\n", $data['body']);
211 }
212
213 /**
214 * get the Missed Calls from router
215 *
216 * @return array
217 */
218 public function getMissedCalls() {
219 $path = 'data/ExportMissedCalls.json';
220 $fields = array('exporttype' => '1');
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 Taken Calls from router
233 *
234 * @return array
235 */
236 public function getTakenCalls() {
237 $path = 'data/ExportTakenCalls.json';
238 $fields = array('exporttype' => '2');
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 Dialed Calls from router
251 *
252 * @return array
253 */
254 public function getDialedCalls() {
255 $path = 'data/ExportDialedCalls.json';
256 $fields = array('exporttype' => '3');
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 * reconnect LTE
269 *
270 * @return array
271 */
272 public function reconnectLte () {
273 $path = 'data/modules.json';
274 $fields = array('csrf_token' => $this->token, 'lte_reconn' => '1');
275 $fields = $this->encrypt($fields);
276 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
277 $data = $this->sentRequest($path, $fields, $cookie, 2);
278 $json = json_decode($data['body'], true);
279
280 return $json;
281 }
282
283 /**
284 * reset the router to Factory Default
285 * not tested
286 *
287 * @return array
288 */
289 public function resetToFactoryDefault () {
290 $path = 'data/resetAllSetting.json';
291 $fields = array('csrf_token' => 'nulltoken', 'showpw' => 0, 'password' => $this->hash, 'reset_all' => 'true');
292 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
293 $data = $this->sentRequest($path, $fields, $cookie);
294 $json = json_decode($data['body'], true);
295
296 return $json;
297 }
298
299
300 /**
301 * check if firmware is actual
302 *
303 * @return array
304 */
305 public function checkFirmware () {
306 $path = 'data/checkfirmware.json';
307 $fields = array('checkfirmware' => 'true');
308 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
309 $data = $this->sentRequest($path, $fields, $cookie);
310
311 if (empty($data['body'])) {
312 throw new Exception('unable to get checkfirmware data');
313 }
314
315 $json = json_decode($data['body'], true);
316
317 return $json;
318 }
319
320 /**
321 * decrypt data from router
322 *
323 * @param string $data
324 * @return array
325 */
326 private function decrypt ($data) {
327 require_once 'CryptLib/CryptLib.php';
328 $factory = new CryptLib\Cipher\Factory();
329 $aes = $factory->getBlockCipher('rijndael-128');
330
331 $iv = hex2bin(substr($this->challenge, 16, 16));
332 $adata = hex2bin(substr($this->challenge, 32, 16));
333 $dkey = hex2bin($this->derivedk);
334 $enc = hex2bin($data);
335
336 $aes->setKey($dkey);
337 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
338
339 $mode->decrypt($enc);
340
341 return $mode->finish();
342 }
343
344 /**
345 * decrypt data for the router
346 *
347 * @param array $data
348 * @return string
349 */
350 private function encrypt ($data) {
351 require_once 'CryptLib/CryptLib.php';
352 $factory = new CryptLib\Cipher\Factory();
353 $aes = $factory->getBlockCipher('rijndael-128');
354
355 $iv = hex2bin(substr($this->challenge, 16, 16));
356 $adata = hex2bin(substr($this->challenge, 32, 16));
357 $dkey = hex2bin($this->derivedk);
358
359 $aes->setKey($dkey);
360 $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]);
361 $mode->encrypt(http_build_query($data));
362
363 return bin2hex($mode->finish());
364 }
365
366 /**
367 * get the values from array
368 *
369 * @param array $array
370 * @return array
371 */
372 private function getValues($array) {
373 $data = array();
374 foreach ($array as $item) {
375 $data[$item['varid']] = $item['varvalue'];
376 }
377
378 return $data;
379 }
380
381 /**
382 * sends the request to router
383 *
384 * @param string $path
385 * @param mixed $fields
386 * @param string $cookie
387 * @param integer $count
388 * @return array
389 */
390 private function sentRequest ($path, $fields, $cookie = '', $count = 0) {
391 $url = $this->url.$path;
392 $ch = curl_init();
393 curl_setopt($ch, CURLOPT_URL, $url);
394
395 if (!empty($fields)) {
396 if (is_array($fields)) {
397 curl_setopt($ch, CURLOPT_POST, count($fields));
398 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
399 }
400 else {
401 curl_setopt($ch, CURLOPT_POST, $count);
402 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
403 }
404 }
405
406 if (!empty($cookie)) {
407 curl_setopt($ch, CURLOPT_COOKIE, $cookie);
408 }
409
410 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
411 curl_setopt($ch, CURLOPT_HEADER, true);
412
413 if ($cookie) {
414
415 }
416
417 $result = curl_exec($ch);
418
419 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
420 $header = substr($result, 0, $header_size);
421 $body = substr($result, $header_size);
422 curl_close($ch);
423
424 // fix invalid json
425
426 $body = preg_replace("/(\r\n)|(\r)/", "\n", $body);
427 $body = preg_replace('/\'/i', '"', $body);
428 $body = preg_replace("/\[\s+\]/i", '[ {} ]', $body);
429 $body = preg_replace("/},\s+]/", "}\n]", $body);
430
431 return array('header' => $this->parse_headers($header), 'body' => $body);
432 }
433
434 /**
435 * get the csrf_token
436 *
437 * @return string
438 */
439 private function getToken () {
440 $path = 'html/content/overview/index.html?lang=de';
441 $fields = array();
442 $cookie = 'challengev='.$this->challenge.'; '.$this->session;
443 $data = $this->sentRequest($path, $fields, $cookie);
444
445 if (empty($data['body'])) {
446 throw new Exception('unable to get csrf_token');
447 }
448
449 $a = explode('csrf_token = "', $data['body']);
450 $a = explode('";', $a[1]);
451
452 if (isset($a[0]) && !empty($a[0])) {
453 return $a[0];
454 }
455 else {
456 throw new Exception('unable to get csrf_token');
457 }
458 }
459
460 /**
461 * parse the curl return header into an array
462 *
463 * @param string $response
464 * @return array
465 */
466 private function parse_headers($response) {
467 $headers = array();
468 $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
469
470 $header_text = explode("\r\n", $header_text);
471 foreach ($header_text as $i => $line) {
472 if ($i === 0) {
473 $headers['http_code'] = $line;
474 }
475 else {
476 list ($key, $value) = explode(': ', $line);
477 $headers[$key] = $value;
478 }
479 }
480
481 return $headers;
482 }
483 }