/
session.php
268 lines (213 loc) · 9.01 KB
/
session.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
260
261
262
263
264
265
266
267
268
<?php
/*
Copyright (c) 2015-2024, Maximilian Doerr, Internet Archive
This file is part of IABot's Framework.
IABot is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
InternetArchiveBot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with InternetArchiveBot. If not, see <https://www.gnu.org/licenses/agpl-3.0.html>.
*/
class Session {
protected static $cookieSent = false;
protected $sessionDBObject = false;
public function __construct() {
global $sessionHttpOnly, $sessionLifeTime, $sessionSecure, $sessionUseDB;
@ini_set( "session.gc_maxlifetime", strtotime( $sessionLifeTime ) - time() );
@ini_set( "session.cookie_lifetime", strtotime( $sessionLifeTime ) - time() );
@ini_set( "session.cookie_httponly", $sessionHttpOnly );
if( $sessionUseDB !== false ) {
// set our custom session functions.
@session_set_save_handler( [ $this, 'open' ], [ $this, 'close' ], [ $this, 'read' ], [ $this, 'write' ],
[ $this, 'destroy' ], [ $this, 'gc' ]
);
// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function( 'session_write_close' );
// Hash algorithm to use for the session. (use hash_algos() to get a list of available hashes.)
$session_hash = 'sha512';
// Check if hash is available
if( in_array( $session_hash, hash_algos() ) ) {
// Set the has function.
@ini_set( 'session.hash_function', $session_hash );
}
// How many bits per character of the hash.
// The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").
@ini_set( 'session.hash_bits_per_character', 5 );
// Force the session to only use cookies, not URL variables.
@ini_set( 'session.use_only_cookies', 1 );
}
@session_name( "IABotManagementConsole" );
//Do some pathway magic to make cookies work in sub-paths
if( !empty( $_SERVER["SCRIPT_NAME"] ) ) {
$startPath = dirname( $_SERVER['SCRIPT_NAME'] );
} elseif( !empty( $_SERVER["DOCUMENT_URI"] ) ) $startPath = dirname( $_SERVER['DOCUMENT_URI'] );
else $startPath = '/';
if( isset( $_SERVER['SCRIPT_FILENAME'] ) && isset( $_SERVER['DOCUMENT_ROOT'] ) ) {
$filterString = dirname( $_SERVER['SCRIPT_FILENAME'] );
$filterString = str_replace( $_SERVER['DOCUMENT_ROOT'], '', $filterString );
} else $filterString = '';
$filterString = str_replace( '\\', '/', $filterString );
$path = str_replace( $filterString, '', $startPath );
if( empty( $path ) ) $path = '/';
// The Cache-Control header affects whether form data is saved, and whether changes to the HTML are re-fetched.
@session_cache_limiter( '' );
@header( 'Cache-Control: private, no-store, must-revalidate' );
// Get session cookie parameters
$cookieParams = session_get_cookie_params();
//session_regenerate_id( true );
@session_set_cookie_params( strtotime( $sessionLifeTime ) - time(), $path,
$cookieParams["domain"], $sessionSecure, $sessionHttpOnly
);
}
public function start() {
global $sessionHttpOnly, $sessionLifeTime, $sessionSecure;
@session_start();
/*
header( 'Cache-Control: no-store, must-revalidate', true );
//Do some pathway magic to make cookies work in sub-paths
if( !empty( $_SERVER["SCRIPT_NAME"] ) ) {
$startPath = dirname( $_SERVER['SCRIPT_NAME'] );
} elseif( !empty( $_SERVER["DOCUMENT_URI"] ) ) $startPath = dirname( $_SERVER['DOCUMENT_URI'] );
else $startPath = '/';
if( isset( $_SERVER['SCRIPT_FILENAME'] ) && isset( $_SERVER['DOCUMENT_ROOT'] ) ) {
$filterString = dirname( $_SERVER['SCRIPT_FILENAME'] );
$filterString = str_replace( $_SERVER['DOCUMENT_ROOT'], '', $filterString );
} else $filterString = '';
$filterString = str_replace( '\\', '/', $filterString );
$path = str_replace( $filterString, '', $startPath );
$cookieParams = session_get_cookie_params();
if( self::$cookieSent === false ) {
setcookie( session_name(), session_id(), strtotime( $sessionLifeTime ), $path, $cookieParams["domain"],
$sessionSecure, $sessionHttpOnly
);
self::$cookieSent = true;
}
*/
}
public function open() {
global $sessionDB, $sessionHost, $sessionPort, $sessionPass, $sessionUser, $sessionSSL;
$this->sessionDBObject = mysqli_init();
mysqli_real_connect( $this->sessionDBObject, $sessionHost, $sessionUser, $sessionPass, $sessionDB, $sessionPort,
'', ( $sessionSSL ?
MYSQLI_CLIENT_SSL : 0 )
);
mysqli_autocommit( $this->sessionDBObject, true );
mysqli_set_charset( $this->sessionDBObject, "utf8" );
return $this->createSessionsTable();
}
protected function createSessionsTable() {
if( !mysqli_query( $this->sessionDBObject, "CREATE TABLE IF NOT EXISTS externallinks_sessions (
`id` CHAR(128) NOT NULL,
`set_time` CHAR(10) NOT NULL,
`data` LONGBLOB NOT NULL,
`session_key` CHAR(128) NOT NULL,
PRIMARY KEY (`id`),
INDEX `TIME` (`set_time` ASC) )
"
)
) {
return false;
}
return true;
}
public function close() {
mysqli_close( $this->sessionDBObject );
unset( $this->read_stmt, $this->key_stmt, $this->w_stmt, $this->delete_stmt, $this->gc_stmt );
return true;
}
public function read( $id ) {
if( !isset( $this->read_stmt ) ) {
$this->read_stmt =
mysqli_prepare( $this->sessionDBObject, "SELECT data FROM externallinks_sessions WHERE id = ? LIMIT 1"
);
}
mysqli_stmt_bind_param( $this->read_stmt, 's', $id );
mysqli_stmt_execute( $this->read_stmt );
mysqli_stmt_store_result( $this->read_stmt );
mysqli_stmt_bind_result( $this->read_stmt, $data );
mysqli_stmt_fetch( $this->read_stmt );
$key = $this->getkey( $id );
$data = $this->decrypt( $data, $key );
return $data;
}
private function getkey( $id ) {
if( !isset( $this->key_stmt ) ) {
$this->key_stmt =
mysqli_prepare( $this->sessionDBObject,
"SELECT session_key FROM externallinks_sessions WHERE id = ? LIMIT 1"
);
}
mysqli_stmt_bind_param( $this->key_stmt, 's', $id );
mysqli_stmt_execute( $this->key_stmt );
mysqli_stmt_store_result( $this->key_stmt );
if( $this->key_stmt->num_rows == 1 ) {
mysqli_stmt_bind_result( $this->key_stmt, $key );
mysqli_stmt_fetch( $this->key_stmt );
$this->sessionRawKey = $key;
$key = hash( 'sha512', $this->sessionRawKey . SESSIONSECRET );
return $key;
} else {
if( !isset( $this->sessionRawKey ) ) $this->sessionRawKey = uniqid( mt_rand( 1, mt_getrandmax() ), true );
$random_key = hash( 'sha512', $this->sessionRawKey . SESSIONSECRET );
return $random_key;
}
}
private function decrypt( $data, $key ) {
$salt = 'cH!swe!retReGu7W6bEDRup7usuDUh9THeD2CHeGE*ewr4n39=E@rAsp7c-Ph@pH';
$iv_size = openssl_cipher_iv_length( "AES-256-CBC" );
$hash = hash( 'sha256', $salt . $key . $salt );
$iv = substr( $hash, strlen( $hash ) - $iv_size );
$key = substr( $hash, 0, 32 );
$decrypted = openssl_decrypt( base64_decode( $data ), "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv );
$decrypted = rtrim( $decrypted, "\0" );
return $decrypted;
}
public function write( $id, $data ) {
// Get unique key
$key = $this->getkey( $id );
// Encrypt the data
$data = $this->encrypt( $data, $key );
$time = time();
if( !isset( $this->w_stmt ) ) {
$this->w_stmt = mysqli_prepare( $this->sessionDBObject,
"REPLACE INTO externallinks_sessions (id, set_time, data, session_key) VALUES (?, ?, ?, ?)"
);
}
mysqli_stmt_bind_param( $this->w_stmt, 'siss', $id, $time, $data, $this->sessionRawKey );
mysqli_stmt_execute( $this->w_stmt );
return true;
}
private function encrypt( $data, $key ) {
$salt = 'cH!swe!retReGu7W6bEDRup7usuDUh9THeD2CHeGE*ewr4n39=E@rAsp7c-Ph@pH';
$iv_size = openssl_cipher_iv_length( "AES-256-CBC" );
$hash = hash( 'sha256', $salt . $key . $salt );
$iv = substr( $hash, strlen( $hash ) - $iv_size );
$key = substr( $hash, 0, 32 );
$encrypted = base64_encode( openssl_encrypt( $data, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv ) );
return $encrypted;
}
public function destroy( $id ) {
if( !isset( $this->delete_stmt ) ) {
$this->delete_stmt =
mysqli_prepare( $this->sessionDBObject, "DELETE FROM externallinks_sessions WHERE id = ?" );
}
mysqli_stmt_bind_param( $this->delete_stmt, 's', $id );
mysqli_stmt_execute( $this->delete_stmt );
return true;
}
public function gc( $max ) {
if( !isset( $this->gc_stmt ) ) {
$this->gc_stmt =
mysqli_prepare( $this->sessionDBObject, "DELETE FROM externallinks_sessions WHERE set_time < ?" );
}
$old = time() - $max;
mysqli_stmt_bind_param( $this->gc_stmt, 's', $old );
mysqli_stmt_execute( $this->gc_stmt );
return true;
}
}