-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMySQLSessionHandler.php
259 lines (211 loc) · 7.62 KB
/
MySQLSessionHandler.php
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
<?php
class SessionAuthException extends RuntimeException{
public function __construct($message = 'Unspecified', $code = 0, Exception $previous = null){
parent::__construct('Session could not be authenticated: ' . $message, $code, $previous);
}
}
class MySQLSessionHandler implements SessionHandlerInterface{
private $link;
private $cOptions = [
'regen_interval' => 600,
'idle_timeout' => 3600];
private $curReqTime;
private $reqSignature;
private $sesInitTime;
private $lastReqTime;
private $sesExpireTime;
private $numWrites;
private $isNew = false;
private $doExpire = false;
public function __construct(mysqli $link, bool $autoInit = true, array $cOptions = []){
$this->link = $link;
$this->curReqTime = $_SERVER['REQUEST_TIME'];
$this->reqSignature = md5($_SERVER['HTTP_USER_AGENT']);
if( $autoInit ){
session_set_save_handler($this);
}
/* TODO: $cOptions from args - possibly load from ini or from memory for ease of use/speed */
return;
}
/* TODO: discuss get/set for $this->cOptions */
/* TODO: get/set methods for custom client request signatures in a more meaningful way */
public function getInitTime(){
return $this->sesInitTime;
}
public function getCurReqTime(){
return $this->curReqTime;
}
public function getLastRequestTime(){
return $this->lastReqTime;
}
public function getExpireTime(){
return $this->sesExpireTime;
}
public function getNumWrites(){
return $this->numWrites;
}
public function setExpire(bool $doExpire = true){
$this->doExpire = $doExpire;
return;
}
public function isMarkedExpire(){
return $this->doExpire;
}
public function start(array $options = []){
try{
@session_start($options);
if( isset($this->cOptions['regen_interval']) && $this->sesInitTime < $this->curReqTime - $this->cOptions['regen_interval'] ){
$this->doExpire = true;
session_regenerate_id(false);
}
}catch(SessionAuthException $e){
/* Unable to authenticate session - setting sid to null will create a new session without destroying the old (possibly hijacked) */
session_id(null);
session_start($options);
}
}
public function open($savePath, $sessionName) : bool{
/* mysqli->ping() returns null if connection has been closed */
return @$this->link->ping() ?: false;
}
public function create_sid() : string{
$checkCollision = session_status() == PHP_SESSION_ACTIVE;
$sid_len = ini_get('session.sid_length');
$sid_bpc = ini_get('session.sid_bits_per_character');
$bytes_needed = ceil($sid_len * $sid_bpc / 8);
$mask = (1 << $sid_bpc) - 1;
$out = '';
$hexconvtab = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-';
$attempts = 0;
$maxAttempts = 5;
/* DISCUSS: adding maxAttempts to cOptions to give more control - keeping in mind that very rarely if ever will a collision occur */
do{
if( $attempts >= $maxAttempts ){
throw new Exception('Could not generate non-colliding sid after ' . $maxAttempts . ' attempts');
}
$random_input_bytes = random_bytes($bytes_needed);
$p = 0;
$q = strlen($random_input_bytes);
$w = 0;
$have = 0;
$chars_remaining = $sid_len;
while( $chars_remaining-- ){
if( $have < $sid_bpc ){
if( $p < $q ) {
$byte = ord($random_input_bytes[$p++]);
$w |= ($byte << $have);
$have += 8;
}else{
break;
}
}
$out .= $hexconvtab[$w & $mask];
$w >>= $sid_bpc;
$have -= $sid_bpc;
}
$attempts++;
}while( $checkCollision && $this->sessionExists($out) );
$this->isNew = true;
return $out;
}
public function validateId(string $sid) : bool{
/* Validate ID is called after create_sid, create_sid already checks for collision */
return $this->isNew ?: $this->sessionExists($sid);
}
private function sessionExists(string $sid) : bool{
$sid = $this->link->escape_string($sid);
$result = $this->link->query('SELECT 1 FROM `sessions` WHERE `session_id` = \'' . $sid . '\';');
if( !$result ){
throw new Exception('Could not determine if session exists: query failed');
}
return $result->num_rows;
}
public function read($sid) : string{
if( $this->isNew ){
/* New session created from self */
$this->sesInitTime = $this->curReqTime;
$this->lastReqTime = null;
$this->sesExpireTime = null;
$this->numWrites = 0;
$out = '';
}elseif( ($result = $this->querySession($sid)) ){
/* Existing session - validate now */
if( $result['request_signature'] && $this->reqSignature !== $result['request_signature'] ){
throw new SessionAuthException('Client request signature mismatch');
}elseif( $result['expire_unixtime'] && $result['expire_unixtime'] < $this->curReqTime ){
throw new SessionAuthException('Session is expired');
}
/* Valid session did not throw */
$this->sesInitTime = $result['init_unixtime'];
$this->lastReqTime = $result['last_request_unixtime'];
$this->sesExpireTime = $result['expire_unixtime'];
$this->numWrites = $result['writes'];
$out = $result['data'];
}else{
/* New session initialized elsewhere - potentially unsafe, but still no collision */
trigger_error('Potentially unsafe read from uninitialized session: see "session.use_strict_mode"', E_USER_WARNING);
$this->isNew = true;
$this->sesInitTime = $this->curReqTime;
$this->lastReqTime = null;
$this->sesExpireTime = null;
$this->numWrites = 0;
$out = '';
}
return $out;
}
private function querySession(string $sid) : ?array{
$sid = $this->link->escape_string($sid);
$result = $this->link->query('SELECT * FROM sessions WHERE session_id = \'' . $sid . '\';');
if( !$result ){
throw new Exception('Failed to import session: query failed');
}
return $result->num_rows ? $result->fetch_assoc() : null;
}
public function write($sid, $data) : bool{
/* Determine expire unixtime */
if( $this->doExpire ){
$expireTime = 0;
}elseif( is_int($this->cOptions['idle_timeout']) ){
$expireTime = $this->curReqTime + $this->cOptions['idle_timeout'];
}else{
$expireTime = 'null';
}
$sid = $this->link->escape_string($sid);
$reqSignature = $this->link->escape_string($this->reqSignature);
$data = $this->link->escape_string($data);
if( $this->isNew ){
$this->link->query(
'INSERT INTO sessions (session_id, init_unixtime, last_request_unixtime, expire_unixtime, request_signature, writes, data) '.
'VALUES(\'' . $sid . '\', ' . $this->curReqTime . ', init_unixtime, ' . $expireTime . ', \'' . $reqSignature . '\', 1, \'' . $data . '\');');
}else{
$this->link->query(
'UPDATE sessions '.
'SET last_request_unixtime = ' . $this->curReqTime . ', expire_unixtime = ' . $expireTime . ', request_signature = \'' . $reqSignature . '\', writes = writes + 1, data = \'' . $data . '\' '.
'WHERE session_id = \'' . $sid . '\';');
}
return $this->link->affected_rows > 0;
}
public function gc($maxLifetime) : bool{
return $this->link->query('DELETE FROM sessions WHERE expire_unixtime <= ' . $this->curReqTime . ';');
}
public function close() : bool{
$sesInitTime = null;
$lastReqTime = null;
$sesExpireTime = null;
$numWrites = null;
$this->isNew = false;
$this->doExpire = false;
/* Keep connection open for use - in case new session_start() or in the case of session_regenerate_id() */
return true;
}
public function destroy($sid) : bool{
$sid = $this->link->escape_string($sid);
$this->link->query('DELETE FROM sessions WHERE session_id = \'' . $sid . '\';');
return $this->link->affected_rows > 0;
}
public function __destruct(){
/* This will not be called in the case of Exception - resource handle will persist until PHP GC happens */
@$this->link->close();
}
}
?>