xref: /PHP-5.6/ext/session/mod_files.c (revision 66826730)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 5                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2016 The PHP Group                                |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Author: Sascha Schumann <sascha@schumann.cx>                         |
16    +----------------------------------------------------------------------+
17  */
18 
19 /* $Id$ */
20 
21 #include "php.h"
22 
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 
26 #if HAVE_SYS_FILE_H
27 #include <sys/file.h>
28 #endif
29 
30 #if HAVE_DIRENT_H
31 #include <dirent.h>
32 #endif
33 
34 #ifdef PHP_WIN32
35 #include "win32/readdir.h"
36 #endif
37 #include <time.h>
38 
39 #include <fcntl.h>
40 #include <errno.h>
41 
42 #if HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45 
46 #include "php_session.h"
47 #include "mod_files.h"
48 #include "ext/standard/flock_compat.h"
49 #include "php_open_temporary_file.h"
50 
51 #define FILE_PREFIX "sess_"
52 
53 #ifdef PHP_WIN32
54 # ifndef O_NOFOLLOW
55 #  define O_NOFOLLOW 0
56 # endif
57 #endif
58 
59 typedef struct {
60 	int fd;
61 	char *lastkey;
62 	char *basedir;
63 	size_t basedir_len;
64 	size_t dirdepth;
65 	size_t st_size;
66 	int filemode;
67 } ps_files;
68 
69 ps_module ps_mod_files = {
70 	PS_MOD_SID(files)
71 };
72 
73 
ps_files_path_create(char * buf,size_t buflen,ps_files * data,const char * key)74 static char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)
75 {
76 	size_t key_len;
77 	const char *p;
78 	int i;
79 	int n;
80 
81 	key_len = strlen(key);
82 	if (!data || key_len <= data->dirdepth ||
83 		buflen < (strlen(data->basedir) + 2 * data->dirdepth + key_len + 5 + sizeof(FILE_PREFIX))) {
84 		return NULL;
85 	}
86 
87 	p = key;
88 	memcpy(buf, data->basedir, data->basedir_len);
89 	n = data->basedir_len;
90 	buf[n++] = PHP_DIR_SEPARATOR;
91 	for (i = 0; i < (int)data->dirdepth; i++) {
92 		buf[n++] = *p++;
93 		buf[n++] = PHP_DIR_SEPARATOR;
94 	}
95 	memcpy(buf + n, FILE_PREFIX, sizeof(FILE_PREFIX) - 1);
96 	n += sizeof(FILE_PREFIX) - 1;
97 	memcpy(buf + n, key, key_len);
98 	n += key_len;
99 	buf[n] = '\0';
100 
101 	return buf;
102 }
103 
104 #ifndef O_BINARY
105 # define O_BINARY 0
106 #endif
107 
ps_files_close(ps_files * data)108 static void ps_files_close(ps_files *data)
109 {
110 	if (data->fd != -1) {
111 #ifdef PHP_WIN32
112 		/* On Win32 locked files that are closed without being explicitly unlocked
113 		   will be unlocked only when "system resources become available". */
114 		flock(data->fd, LOCK_UN);
115 #endif
116 		close(data->fd);
117 		data->fd = -1;
118 	}
119 }
120 
ps_files_open(ps_files * data,const char * key TSRMLS_DC)121 static void ps_files_open(ps_files *data, const char *key TSRMLS_DC)
122 {
123 	char buf[MAXPATHLEN];
124 	struct stat sbuf;
125 	int ret;
126 
127 	if (data->fd < 0 || !data->lastkey || strcmp(key, data->lastkey)) {
128 		if (data->lastkey) {
129 			efree(data->lastkey);
130 			data->lastkey = NULL;
131 		}
132 
133 		ps_files_close(data);
134 
135 		if (php_session_valid_key(key) == FAILURE) {
136 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'");
137 			return;
138 		}
139 
140 		if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
141 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to create session data file path. Too short session ID, invalid save_path or path lentgth exceeds MAXPATHLEN(%d)", MAXPATHLEN);
142 			return;
143 		}
144 
145 		data->lastkey = estrdup(key);
146 
147 		/* O_NOFOLLOW to prevent us from following evil symlinks */
148 #ifdef O_NOFOLLOW
149 		data->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY | O_NOFOLLOW, data->filemode);
150 #else
151 		/* Check to make sure that the opened file is not outside of allowable dirs.
152 		   This is not 100% safe but it's hard to do something better without O_NOFOLLOW */
153 		if(PG(open_basedir) && lstat(buf, &sbuf) == 0 && S_ISLNK(sbuf.st_mode) && php_check_open_basedir(buf TSRMLS_CC)) {
154 			return;
155 		}
156 		data->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY, data->filemode);
157 #endif
158 
159 		if (data->fd != -1) {
160 #ifndef PHP_WIN32
161 			/* check that this session file was created by us or root – we
162 			   don't want to end up accepting the sessions of another webapp */
163 			if (fstat(data->fd, &sbuf) || (sbuf.st_uid != 0 && sbuf.st_uid != getuid() && sbuf.st_uid != geteuid())) {
164 				close(data->fd);
165 				data->fd = -1;
166 				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session data file is not created by your uid");
167 				return;
168 			}
169 #endif
170 			do {
171 				ret = flock(data->fd, LOCK_EX);
172 			} while (ret == -1 && errno == EINTR);
173 
174 #ifdef F_SETFD
175 # ifndef FD_CLOEXEC
176 #  define FD_CLOEXEC 1
177 # endif
178 			if (fcntl(data->fd, F_SETFD, FD_CLOEXEC)) {
179 				php_error_docref(NULL TSRMLS_CC, E_WARNING, "fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)", data->fd, strerror(errno), errno);
180 			}
181 #endif
182 		} else {
183 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "open(%s, O_RDWR) failed: %s (%d)", buf, strerror(errno), errno);
184 		}
185 	}
186 }
187 
ps_files_cleanup_dir(const char * dirname,int maxlifetime TSRMLS_DC)188 static int ps_files_cleanup_dir(const char *dirname, int maxlifetime TSRMLS_DC)
189 {
190 	DIR *dir;
191 	char dentry[sizeof(struct dirent) + MAXPATHLEN];
192 	struct dirent *entry = (struct dirent *) &dentry;
193 	struct stat sbuf;
194 	char buf[MAXPATHLEN];
195 	time_t now;
196 	int nrdels = 0;
197 	size_t dirname_len;
198 
199 	dir = opendir(dirname);
200 	if (!dir) {
201 		php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ps_files_cleanup_dir: opendir(%s) failed: %s (%d)", dirname, strerror(errno), errno);
202 		return (0);
203 	}
204 
205 	time(&now);
206 
207 	dirname_len = strlen(dirname);
208 
209 	/* Prepare buffer (dirname never changes) */
210 	memcpy(buf, dirname, dirname_len);
211 	buf[dirname_len] = PHP_DIR_SEPARATOR;
212 
213 	while (php_readdir_r(dir, (struct dirent *) dentry, &entry) == 0 && entry) {
214 		/* does the file start with our prefix? */
215 		if (!strncmp(entry->d_name, FILE_PREFIX, sizeof(FILE_PREFIX) - 1)) {
216 			size_t entry_len = strlen(entry->d_name);
217 
218 			/* does it fit into our buffer? */
219 			if (entry_len + dirname_len + 2 < MAXPATHLEN) {
220 				/* create the full path.. */
221 				memcpy(buf + dirname_len + 1, entry->d_name, entry_len);
222 
223 				/* NUL terminate it and */
224 				buf[dirname_len + entry_len + 1] = '\0';
225 
226 				/* check whether its last access was more than maxlifetime ago */
227 				if (VCWD_STAT(buf, &sbuf) == 0 &&
228 						(now - sbuf.st_mtime) > maxlifetime) {
229 					VCWD_UNLINK(buf);
230 					nrdels++;
231 				}
232 			}
233 		}
234 	}
235 
236 	closedir(dir);
237 
238 	return (nrdels);
239 }
240 
ps_files_key_exists(ps_files * data,const char * key TSRMLS_DC)241 static int ps_files_key_exists(ps_files *data, const char *key TSRMLS_DC)
242 {
243 	char buf[MAXPATHLEN];
244 	struct stat sbuf;
245 
246 	if (!key || !ps_files_path_create(buf, sizeof(buf), data, key)) {
247 		return FAILURE;
248 	}
249 	if (VCWD_STAT(buf, &sbuf)) {
250 		return FAILURE;
251 	}
252 	return SUCCESS;
253 }
254 
255 
256 #define PS_FILES_DATA ps_files *data = PS_GET_MOD_DATA()
257 
PS_OPEN_FUNC(files)258 PS_OPEN_FUNC(files)
259 {
260 	ps_files *data;
261 	const char *p, *last;
262 	const char *argv[3];
263 	int argc = 0;
264 	size_t dirdepth = 0;
265 	int filemode = 0600;
266 
267 	if (*save_path == '\0') {
268 		/* if save path is an empty string, determine the temporary dir */
269 		save_path = php_get_temporary_directory(TSRMLS_C);
270 
271 		if (php_check_open_basedir(save_path TSRMLS_CC)) {
272 			return FAILURE;
273 		}
274 	}
275 
276 	/* split up input parameter */
277 	last = save_path;
278 	p = strchr(save_path, ';');
279 	while (p) {
280 		argv[argc++] = last;
281 		last = ++p;
282 		p = strchr(p, ';');
283 		if (argc > 1) break;
284 	}
285 	argv[argc++] = last;
286 
287 	if (argc > 1) {
288 		errno = 0;
289 		dirdepth = (size_t) strtol(argv[0], NULL, 10);
290 		if (errno == ERANGE) {
291 			php_error(E_WARNING, "The first parameter in session.save_path is invalid");
292 			return FAILURE;
293 		}
294 	}
295 
296 	if (argc > 2) {
297 		errno = 0;
298 		filemode = strtol(argv[1], NULL, 8);
299 		if (errno == ERANGE || filemode < 0 || filemode > 07777) {
300 			php_error(E_WARNING, "The second parameter in session.save_path is invalid");
301 			return FAILURE;
302 		}
303 	}
304 	save_path = argv[argc - 1];
305 
306 	data = ecalloc(1, sizeof(*data));
307 
308 	data->fd = -1;
309 	data->dirdepth = dirdepth;
310 	data->filemode = filemode;
311 	data->basedir_len = strlen(save_path);
312 	data->basedir = estrndup(save_path, data->basedir_len);
313 
314 	if (PS_GET_MOD_DATA()) {
315 		ps_close_files(mod_data TSRMLS_CC);
316 	}
317 	PS_SET_MOD_DATA(data);
318 
319 	return SUCCESS;
320 }
321 
PS_CLOSE_FUNC(files)322 PS_CLOSE_FUNC(files)
323 {
324 	PS_FILES_DATA;
325 
326 	ps_files_close(data);
327 
328 	if (data->lastkey) {
329 		efree(data->lastkey);
330 		data->lastkey = NULL;
331 	}
332 
333 	efree(data->basedir);
334 	efree(data);
335 	*mod_data = NULL;
336 
337 	return SUCCESS;
338 }
339 
PS_READ_FUNC(files)340 PS_READ_FUNC(files)
341 {
342 	long n;
343 	struct stat sbuf;
344 	PS_FILES_DATA;
345 
346 	/* If strict mode, check session id existence */
347 	if (PS(use_strict_mode) &&
348 		ps_files_key_exists(data, key TSRMLS_CC) == FAILURE) {
349 		/* key points to PS(id), but cannot change here. */
350 		if (key) {
351 			efree(PS(id));
352 			PS(id) = NULL;
353 		}
354 		PS(id) = PS(mod)->s_create_sid((void **)&data, NULL TSRMLS_CC);
355 		if (!PS(id)) {
356 			return FAILURE;
357 		}
358 		if (PS(use_cookies)) {
359 			PS(send_cookie) = 1;
360 		}
361 		php_session_reset_id(TSRMLS_C);
362 		PS(session_status) = php_session_active;
363 	}
364 
365 	if (!PS(id)) {
366 		return FAILURE;
367 	}
368 
369 	ps_files_open(data, PS(id) TSRMLS_CC);
370 	if (data->fd < 0) {
371 		return FAILURE;
372 	}
373 
374 	if (fstat(data->fd, &sbuf)) {
375 		return FAILURE;
376 	}
377 
378 	data->st_size = *vallen = sbuf.st_size;
379 
380 	if (sbuf.st_size == 0) {
381 		*val = STR_EMPTY_ALLOC();
382 		return SUCCESS;
383 	}
384 
385 	*val = emalloc(sbuf.st_size);
386 
387 #if defined(HAVE_PREAD)
388 	n = pread(data->fd, *val, sbuf.st_size, 0);
389 #else
390 	lseek(data->fd, 0, SEEK_SET);
391 	n = read(data->fd, *val, sbuf.st_size);
392 #endif
393 
394 	if (n != sbuf.st_size) {
395 		if (n == -1) {
396 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "read failed: %s (%d)", strerror(errno), errno);
397 		} else {
398 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "read returned less bytes than requested");
399 		}
400 		efree(*val);
401 		return FAILURE;
402 	}
403 
404 	return SUCCESS;
405 }
406 
PS_WRITE_FUNC(files)407 PS_WRITE_FUNC(files)
408 {
409 	long n;
410 	PS_FILES_DATA;
411 
412 	ps_files_open(data, key TSRMLS_CC);
413 	if (data->fd < 0) {
414 		return FAILURE;
415 	}
416 
417 	/* Truncate file if the amount of new data is smaller than the existing data set. */
418 
419 	if (vallen < (int)data->st_size) {
420 		php_ignore_value(ftruncate(data->fd, 0));
421 	}
422 
423 #if defined(HAVE_PWRITE)
424 	n = pwrite(data->fd, val, vallen, 0);
425 #else
426 	lseek(data->fd, 0, SEEK_SET);
427 	n = write(data->fd, val, vallen);
428 #endif
429 
430 	if (n != vallen) {
431 		if (n == -1) {
432 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "write failed: %s (%d)", strerror(errno), errno);
433 		} else {
434 			php_error_docref(NULL TSRMLS_CC, E_WARNING, "write wrote less bytes than requested");
435 		}
436 		return FAILURE;
437 	}
438 
439 	return SUCCESS;
440 }
441 
PS_DESTROY_FUNC(files)442 PS_DESTROY_FUNC(files)
443 {
444 	char buf[MAXPATHLEN];
445 	PS_FILES_DATA;
446 
447 	if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
448 		return FAILURE;
449 	}
450 
451 	if (data->fd != -1) {
452 		ps_files_close(data);
453 
454 		if (VCWD_UNLINK(buf) == -1) {
455 			/* This is a little safety check for instances when we are dealing with a regenerated session
456 			 * that was not yet written to disk. */
457 			if (!VCWD_ACCESS(buf, F_OK)) {
458 				return FAILURE;
459 			}
460 		}
461 	}
462 
463 	return SUCCESS;
464 }
465 
PS_GC_FUNC(files)466 PS_GC_FUNC(files)
467 {
468 	PS_FILES_DATA;
469 
470 	/* we don't perform any cleanup, if dirdepth is larger than 0.
471 	   we return SUCCESS, since all cleanup should be handled by
472 	   an external entity (i.e. find -ctime x | xargs rm) */
473 
474 	if (data->dirdepth == 0) {
475 		*nrdels = ps_files_cleanup_dir(data->basedir, maxlifetime TSRMLS_CC);
476 	}
477 
478 	return SUCCESS;
479 }
480 
PS_CREATE_SID_FUNC(files)481 PS_CREATE_SID_FUNC(files)
482 {
483 	char *sid;
484 	int maxfail = 3;
485 	PS_FILES_DATA;
486 
487 	do {
488 		sid = php_session_create_id((void **)&data, newlen TSRMLS_CC);
489 		/* Check collision */
490 		if (data && ps_files_key_exists(data, sid TSRMLS_CC) == SUCCESS) {
491 			if (sid) {
492 				efree(sid);
493 				sid = NULL;
494 			}
495 			if (!(maxfail--)) {
496 				return NULL;
497 			}
498 		}
499 	} while(!sid);
500 
501 	return sid;
502 }
503 
504 
505 /*
506  * Local variables:
507  * tab-width: 4
508  * c-basic-offset: 4
509  * End:
510  * vim600: sw=4 ts=4 fdm=marker
511  * vim<600: sw=4 ts=4
512  */
513