-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathSession.php
More file actions
316 lines (274 loc) · 9.43 KB
/
Session.php
File metadata and controls
316 lines (274 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
<?php
/**
* Bittr
*
* @license
*
* New BSD License
*
* Copyright (c) 2017, ghostff community
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the ghostff.
* 4. Neither the name of the ghostff nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ghostff ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL GHOSTFF COMMUNITY BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
declare(strict_types=1);
use Session\Save;
class Session
{
private static $initialized = [];
private static $started = false;
private static $class = null;
private static $ssl_enabled = true;
public static $write = false;
private static $custom_config = null;
public static $id = '';
private static function init()
{
$DS = DIRECTORY_SEPARATOR;
$path = __DIR__ . "{$DS}Session{$DS}";
$config = include(self::$custom_config ?? $path . 'config.php');
self::$initialized = $config;
$driver = $config['driver'];
self::$class = ucfirst($driver);
if(! is_dir($path . self::$class))
{
throw new \RuntimeException('No driver found for ' . self::$class);
}
self::$ssl_enabled = self::$initialized['encrypt_data'];
if (self::$ssl_enabled && ! extension_loaded('openssl'))
{
throw new \RuntimeException('The openssl extension is missing. Please check your PHP configuration.');
}
if (self::$class != 'File' && self::$class != 'Cookie')
{
if (! extension_loaded(self::$class))
{
throw new \RuntimeException('The ' . self::$class . ' extension is missing. Please check your PHP configuration.');
}
}
session_cache_limiter($config['cache_limiter']);
$secured = $config['secure'];
if ($secured !== true && $secured !== false && $secured !== null)
{
throw new \RuntimeException('config.secure expected value to be a boolean or null');
}
if ($secured == null)
{
$secured = (! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS'] == 'on'));
}
ini_set('session.save_handler', ($driver == 'file') ? 'files' : (($driver == 'memcached' || $driver == 'redis') ? $driver : 'user'));
ini_set('session.use_cookies', '1');
ini_set('session.gc_maxlifetime', $config['max_life_time']);
ini_set('session.gc_probability', $config['probability']);
$current = $config['expiration'];
$config['expiration'] = ($current == 0) ? 0 : time() + $current;
session_set_cookie_params($config['expiration'], $config['path'], $config['domain'], $secured, $config['http_only']);
if (self::$class == 'File')
{
$save_path = $config[$driver]['save_path'];
if (is_dir($save_path))
{
session_save_path($save_path);
}
else
{
throw new RuntimeException(sprintf('save_path (%s) does not exist', $save_path));
}
}
elseif ( self::$class == 'Memcached' || self::$class == 'Redis')
{
session_save_path($config[$driver]['save_path']);
}
$class = '\Session\\' . self::$class . '\Handler';
session_set_save_handler(new $class(self::$initialized), true);
}
/**
* Sets new session id.
*
* @param string $id
* @return string
*/
public static function id(string $id = ''): string
{
if (empty(self::$initialized))
{
self::init();
}
if ($id != '')
{
if (self::$started)
{
throw new \RuntimeException('Session is active. The session id must be set before Session::start().');
}
elseif (headers_sent($filename, $line_num))
{
throw new \RuntimeException(sprintf('ID must be set before any output is sent to the browser (file: %s, line: %s)', $filename, $line_num));
}
elseif (preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $id) < 1)
{
throw new \InvalidArgumentException('Invalid Session ID.');
}
else
{
session_id($id);
}
}
return self::$id;
}
/**
* Sets a file where config settings will be loaded from.
*
* @param string $path_to_file
*/
public static function setConfigFile(string $path_to_file)
{
if (! is_file($path_to_file))
{
throw new RuntimeException('config was not found in (' . $path_to_file . ') or not enough permission.');
}
self::$custom_config = $path_to_file;
}
/**
* starts a new session
*
* @param string $namespace
* @param bool $auto_commit (Alternative for https://github.com/Ghostff/Session/issues/4)
* @return Save
*/
public static function start(string $namespace = null, bool $auto_commit = true): Save
{
if (empty(self::$initialized))
{
self::init();
}
self::$started = true;
self::$initialized['namespace'] = $namespace ?? '__GLOBAL';
$handler = new Save(self::$initialized);
if ($auto_commit)
{
register_shutdown_function(function () use ($handler)
{
self::autoCommit($handler);
});
}
return $handler;
}
/**
* Reset all session configuration settings.
*
* @return Session
*/
public static function reset(): self
{
self::$initialized = [];
return new self;
}
/**
* Commits uncommitted changes.
*
* @param Save $handler
*/
public static function autoCommit(Save $handler)
{
if (! $handler->all_was_committed)
{
$handler->commit();
}
}
/**
* Allows error custom error handling
*
* @param callable $error_handler
*/
public static function registerErrorHandler(callable $error_handler)
{
if (empty(self::$initialized))
{
self::init();
}
self::$initialized['error_handler'] = $error_handler;
}
/**
* decrypt AES 256
*
* @param string $data
* @return string data
*/
public static function decrypt(string $data): string
{
if (! self::$initialized['encrypt_data'] || ! self::$ssl_enabled)
{
return $data;
}
$password = self::$initialized['key'];
$data = base64_decode($data);
$salt = substr($data, 0, 16);
$ct = substr($data, 16);
$rounds = 3; // depends on key length
$data00 = $password . $salt;
$hash = [];
$hash[0] = hash('sha256', $data00, true);
$result = $hash[0];
for ($i = 1; $i < $rounds; $i++)
{
$hash[$i] = hash('sha256', $hash[$i - 1] . $data00, true);
$result .= $hash[$i];
}
$key = substr($result, 0, 32);
$iv = substr($result, 32,16);
$decrypted = openssl_decrypt($ct, 'AES-256-CBC', $key, 1, $iv);
return (! $decrypted) ? '' : $decrypted;
}
/**
* crypt AES 256
*
* @param string $data
* @return string encrypted data
*/
public static function encrypt(string $data): string
{
if (! self::$initialized['encrypt_data'] || ! self::$ssl_enabled)
{
return $data;
}
$password = self::$initialized['key'];
// Set a random salt
$salt = openssl_random_pseudo_bytes(16);
$salted = '';
$dx = '';
// Salt the key(32) and iv(16) = 48
while (strlen($salted) < 48)
{
$dx = hash('sha256', $dx . $password . $salt, true);
$salted .= $dx;
}
$key = substr($salted, 0, 32);
$iv = substr($salted, 32,16);
$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, 1, $iv);
return base64_encode($salt . $encrypted_data);
}
}