Apache HTTPD
mod_usertrack.c
Go to the documentation of this file.
1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* User Tracking Module (Was mod_cookies.c)
18 *
19 * *** IMPORTANT NOTE: This module is not designed to generate
20 * *** cryptographically secure cookies. This means you should not
21 * *** use cookies generated by this module for authentication purposes
22 *
23 * This Apache module is designed to track users paths through a site.
24 * It uses the client-side state ("Cookie") protocol developed by Netscape.
25 * It is known to work on most browsers.
26 *
27 * Each time a page is requested we look to see if the browser is sending
28 * us a Cookie: header that we previously generated.
29 *
30 * If we don't find one then the user hasn't been to this site since
31 * starting their browser or their browser doesn't support cookies. So
32 * we generate a unique Cookie for the transaction and send it back to
33 * the browser (via a "Set-Cookie" header)
34 * Future requests from the same browser should keep the same Cookie line.
35 *
36 * By matching up all the requests with the same cookie you can
37 * work out exactly what path a user took through your site. To log
38 * the cookie use the " %{Cookie}n " directive in a custom access log;
39 *
40 * Example 1 : If you currently use the standard Log file format (CLF)
41 * and use the command "TransferLog somefilename", add the line
42 * LogFormat "%h %l %u %t \"%r\" %s %b %{Cookie}n"
43 * to your config file.
44 *
45 * Example 2 : If you used to use the old "CookieLog" directive, you
46 * can emulate it by adding the following command to your config file
47 * CustomLog filename "%{Cookie}n \"%r\" %t"
48 *
49 * Mark Cox, [email protected], 6 July 95
50 *
51 * This file replaces mod_cookies.c
52 */
53
54#include "apr.h"
55#include "apr_lib.h"
56#include "apr_strings.h"
57
58#define APR_WANT_STRFUNC
59#include "apr_want.h"
60
61#include "httpd.h"
62#include "http_config.h"
63#include "http_core.h"
64#include "http_request.h"
65#include "http_log.h"
66
67
68module AP_MODULE_DECLARE_DATA usertrack_module;
69
70typedef struct {
71 int always;
74
81
82typedef struct {
85 const char *cookie_name;
86 const char *cookie_domain;
87 char *regexp_string; /* used to compile regexp; save for debugging */
88 ap_regex_t *regexp; /* used to find usertrack cookie in cookie header */
91 const char *samesite;
93
94/* Make Cookie: Now we have to generate something that is going to be
95 * pretty unique. We can base it on the pid, time, hostip */
96
97#define COOKIE_NAME "Apache"
98
100{
102 &usertrack_module);
103 char cookiebuf[2 * (sizeof(apr_uint64_t) + sizeof(int)) + 2];
104 unsigned int random;
106 char *new_cookie;
108
112 dcfg = ap_get_module_config(r->per_dir_config, &usertrack_module);
113 if (cls->expires) {
114
115 /* Cookie with date; as strftime '%a, %d-%h-%y %H:%M:%S GMT' */
116 new_cookie = apr_psprintf(r->pool, "%s=%s; path=/",
117 dcfg->cookie_name, cookiebuf);
118
119 if ((dcfg->style == CT_UNSET) || (dcfg->style == CT_NETSCAPE)) {
122 + apr_time_from_sec(cls->expires));
124 "%s; expires=%s, "
125 "%.2d-%s-%.2d %.2d:%.2d:%.2d GMT",
126 new_cookie, apr_day_snames[tms.tm_wday],
127 tms.tm_mday,
128 apr_month_snames[tms.tm_mon],
129 tms.tm_year % 100,
130 tms.tm_hour, tms.tm_min, tms.tm_sec);
131 }
132 else {
133 new_cookie = apr_psprintf(r->pool, "%s; max-age=%d",
134 new_cookie, cls->expires);
135 }
136 }
137 else {
138 new_cookie = apr_psprintf(r->pool, "%s=%s; path=/",
139 dcfg->cookie_name, cookiebuf);
140 }
141 if (dcfg->cookie_domain != NULL) {
142 new_cookie = apr_pstrcat(r->pool, new_cookie, "; domain=",
143 dcfg->cookie_domain,
144 (dcfg->style == CT_COOKIE2
145 ? "; version=1"
146 : ""),
147 NULL);
148 }
149 if (dcfg->samesite != NULL) {
151 dcfg->samesite,
152 NULL);
153 }
154 if (dcfg->is_secure) {
155 new_cookie = apr_pstrcat(r->pool, new_cookie, "; Secure",
156 NULL);
157 }
158 if (dcfg->is_httponly) {
159 new_cookie = apr_pstrcat(r->pool, new_cookie, "; HttpOnly",
160 NULL);
161 }
162
163
164
166 (dcfg->style == CT_COOKIE2 ? "Set-Cookie2" : "Set-Cookie"),
167 new_cookie);
168 apr_table_setn(r->notes, "cookie", apr_pstrdup(r->pool, cookiebuf)); /* log first time */
169}
170
171/* dcfg->regexp is "^cookie_name=([^;]+)|;[ \t]+cookie_name=([^;]+)",
172 * which has three subexpressions, $0..$2 */
173#define NUM_SUBS 3
174
176 apr_pool_t *p,
177 const char *cookie_name)
178{
179 int danger_chars = 0;
180 const char *sp = cookie_name;
181
182 /* The goal is to end up with this regexp,
183 * ^cookie_name=([^;,]+)|[;,][ \t]+cookie_name=([^;,]+)
184 * with cookie_name obviously substituted either
185 * with the real cookie name set by the user in httpd.conf, or with the
186 * default COOKIE_NAME. */
187
188 /* Anyway, we need to escape the cookie_name before pasting it
189 * into the regex
190 */
191 while (*sp) {
192 if (!apr_isalnum(*sp)) {
193 ++danger_chars;
194 }
195 ++sp;
196 }
197
198 if (danger_chars) {
199 char *cp;
200 cp = apr_palloc(p, sp - cookie_name + danger_chars + 1); /* 1 == \0 */
201 sp = cookie_name;
202 cookie_name = cp;
203 while (*sp) {
204 if (!apr_isalnum(*sp)) {
205 *cp++ = '\\';
206 }
207 *cp++ = *sp++;
208 }
209 *cp = '\0';
210 }
211
212 dcfg->regexp_string = apr_pstrcat(p, "^",
213 cookie_name,
214 "=([^;,]+)|[;,][ \t]*",
215 cookie_name,
216 "=([^;,]+)", NULL);
217
218 dcfg->regexp = ap_pregcomp(p, dcfg->regexp_string, AP_REG_EXTENDED);
219 ap_assert(dcfg->regexp != NULL);
220}
221
223{
225 &usertrack_module);
226 const char *cookie_header;
228
229 /* Do not run in subrequests */
230 if (!dcfg->enabled || r->main) {
231 return DECLINED;
232 }
233
234 if ((cookie_header = apr_table_get(r->headers_in, "Cookie"))) {
235 if (!ap_regexec(dcfg->regexp, cookie_header, NUM_SUBS, regm, 0)) {
236 char *cookieval = NULL;
237 int err = 0;
238 /* Our regexp,
239 * ^cookie_name=([^;]+)|;[ \t]+cookie_name=([^;]+)
240 * only allows for $1 or $2 to be available. ($0 is always
241 * filled with the entire matched expression, not just
242 * the part in parentheses.) So just check for either one
243 * and assign to cookieval if present. */
244 if (regm[1].rm_so != -1) {
246 NUM_SUBS, regm);
247 if (cookieval == NULL)
248 err = 1;
249 }
250 if (regm[2].rm_so != -1) {
252 NUM_SUBS, regm);
253 if (cookieval == NULL)
254 err = 1;
255 }
256 if (err) {
258 "Failed to extract cookie value (out of mem?)");
260 }
261 /* Set the cookie in a note, for logging */
262 apr_table_setn(r->notes, "cookie", cookieval);
263
264 return DECLINED; /* There's already a cookie, no new one */
265 }
266 }
267 make_cookie(r);
268 return OK; /* We set our cookie */
269}
270
272{
275
276 cls->expires = 0;
277
278 return (void *) cls;
279}
280
281static void *make_cookie_dir(apr_pool_t *p, char *d)
282{
284
287 dcfg->style = CT_UNSET;
288 /* calloc'ed to disabled: enabled, cookie_domain, samesite, is_secure,
289 * is_httponly */
290
291 /* In case the user does not use the CookieName directive,
292 * we need to compile the regexp for the default cookie name. */
294
295 return dcfg;
296}
297
298static const char *set_cookie_exp(cmd_parms *parms, void *dummy,
299 const char *arg)
300{
302 time_t factor, modifier = 0;
303 time_t num = 0;
304 char *word;
305
306 cls = ap_get_module_config(parms->server->module_config,
307 &usertrack_module);
308 /* The simple case first - all numbers (we assume) */
309 if (apr_isdigit(arg[0]) && apr_isdigit(arg[strlen(arg) - 1])) {
310 cls->expires = atol(arg);
311 return NULL;
312 }
313
314 /*
315 * The harder case - stolen from mod_expires
316 *
317 * CookieExpires "[plus] {<num> <type>}*"
318 */
319
320 word = ap_getword_conf(parms->temp_pool, &arg);
321 if (!strncasecmp(word, "plus", 1)) {
322 word = ap_getword_conf(parms->temp_pool, &arg);
323 };
324
325 /* {<num> <type>}* */
326 while (word[0]) {
327 /* <num> */
328 if (apr_isdigit(word[0]))
329 num = atoi(word);
330 else
331 return "bad expires code, numeric value expected.";
332
333 /* <type> */
334 word = ap_getword_conf(parms->temp_pool, &arg);
335 if (!word[0])
336 return "bad expires code, missing <type>";
337
338 if (!strncasecmp(word, "years", 1))
339 factor = 60 * 60 * 24 * 365;
340 else if (!strncasecmp(word, "months", 2))
341 factor = 60 * 60 * 24 * 30;
342 else if (!strncasecmp(word, "weeks", 1))
343 factor = 60 * 60 * 24 * 7;
344 else if (!strncasecmp(word, "days", 1))
345 factor = 60 * 60 * 24;
346 else if (!strncasecmp(word, "hours", 1))
347 factor = 60 * 60;
348 else if (!strncasecmp(word, "minutes", 2))
349 factor = 60;
350 else if (!strncasecmp(word, "seconds", 1))
351 factor = 1;
352 else
353 return "bad expires code, unrecognized type";
354
355 modifier = modifier + factor * num;
356
357 /* next <num> */
358 word = ap_getword_conf(parms->temp_pool, &arg);
359 }
360
361 cls->expires = modifier;
362
363 return NULL;
364}
365
366static const char *set_cookie_name(cmd_parms *cmd, void *mconfig,
367 const char *name)
368{
370
372
374
375 if (dcfg->regexp == NULL) {
376 return "Regular expression could not be compiled.";
377 }
378 if (dcfg->regexp->re_nsub + 1 != NUM_SUBS) {
379 return apr_pstrcat(cmd->pool, "Invalid cookie name \"",
380 name, "\"", NULL);
381 }
382
383 return NULL;
384}
385
386/*
387 * Set the value for the 'Domain=' attribute.
388 */
389static const char *set_cookie_domain(cmd_parms *cmd, void *mconfig,
390 const char *name)
391{
393
395
396 /*
397 * Apply the restrictions on cookie domain attributes.
398 */
399 if (!name[0]) {
400 return "CookieDomain values may not be null";
401 }
402 if (name[0] != '.') {
403 return "CookieDomain values must begin with a dot";
404 }
405 if (ap_strchr_c(&name[1], '.') == NULL) {
406 return "CookieDomain values must contain at least one embedded dot";
407 }
408
410 return NULL;
411}
412
413/*
414 * Make a note of the cookie style we should use.
415 */
416static const char *set_cookie_style(cmd_parms *cmd, void *mconfig,
417 const char *name)
418{
420
422
423 if (strcasecmp(name, "Netscape") == 0) {
425 }
426 else if ((strcasecmp(name, "Cookie") == 0)
427 || (strcasecmp(name, "RFC2109") == 0)) {
428 dcfg->style = CT_COOKIE;
429 }
430 else if ((strcasecmp(name, "Cookie2") == 0)
431 || (strcasecmp(name, "RFC2965") == 0)) {
432 dcfg->style = CT_COOKIE2;
433 }
434 else {
435 return apr_psprintf(cmd->pool, "Invalid %s keyword: '%s'",
436 cmd->cmd->name, name);
437 }
438
439 return NULL;
440}
441
442/*
443 * SameSite enabled disabled
444 */
445
446static const char *set_samesite_value(cmd_parms *cmd, void *mconfig,
447 const char *name)
448{
450
452
453 if (strcasecmp(name, "strict") == 0) {
454 dcfg->samesite = "SameSite=Strict";
455 } else if (strcasecmp(name, "lax") == 0) {
456 dcfg->samesite = "SameSite=Lax";
457 } else if (strcasecmp(name, "none") == 0) {
458 dcfg->samesite = "SameSite=None";
459 } else {
460 return "CookieSameSite accepts 'Strict', 'Lax', or 'None'";
461 }
462
463
464 return NULL;
465}
466
467static const command_rec cookie_log_cmds[] = {
468 AP_INIT_TAKE1("CookieExpires", set_cookie_exp, NULL, OR_FILEINFO,
469 "an expiry date code"),
471 "domain to which this cookie applies"),
473 "'Netscape', 'Cookie' (RFC2109), or 'Cookie2' (RFC2965)"),
474 AP_INIT_FLAG("CookieTracking", ap_set_flag_slot,
476 "whether or not to enable cookies"),
478 "name of the tracking cookie"),
480 "SameSite setting"),
481 AP_INIT_FLAG("CookieSecure", ap_set_flag_slot,
482 (void *)APR_OFFSETOF(cookie_dir_rec, is_secure), OR_FILEINFO,
483 "is cookie secure"),
484 AP_INIT_FLAG("CookieHttpOnly", ap_set_flag_slot,
485 (void *)APR_OFFSETOF(cookie_dir_rec, is_httponly),OR_FILEINFO,
486 "is cookie http only"),
487
488 {NULL}
489};
490
495
498 make_cookie_dir, /* dir config creater */
499 NULL, /* dir merger --- default is to override */
500 make_cookie_log_state, /* server config */
501 NULL, /* merge server configs */
502 cookie_log_cmds, /* command apr_table_t */
503 register_hooks /* register hooks */
504};
#define AP_REG_EXTENDED
Definition ap_regex.h:78
APR general purpose library routines.
apr_size_t const unsigned char unsigned int unsigned int d
Definition apr_siphash.h:72
APR Strings library.
APR Standard Headers Support.
#define AP_INIT_TAKE1(directive, func, mconfig, where, help)
#define ap_get_module_config(v, m)
#define AP_DECLARE_MODULE(foo)
#define AP_INIT_FLAG(directive, func, mconfig, where, help)
const char * ap_set_flag_slot(cmd_parms *cmd, void *struct_ptr, int arg)
Definition config.c:1512
request_rec * r
#define DECLINED
Definition httpd.h:457
#define OK
Definition httpd.h:456
#define APLOGNO(n)
Definition http_log.h:117
#define ap_log_rerror
Definition http_log.h:454
#define APLOG_MARK
Definition http_log.h:283
#define APLOG_CRIT
Definition http_log.h:66
void ap_hook_fixups(ap_HOOK_fixups_t *pf, const char *const *aszPre, const char *const *aszSucc, int nOrder)
Definition request.c:87
void * dummy
Definition http_vhost.h:62
void const char * arg
Definition http_vhost.h:63
int enabled
#define APR_HOOK_REALLY_FIRST
Definition apr_hooks.h:299
#define OR_FILEINFO
#define HTTP_INTERNAL_SERVER_ERROR
Definition httpd.h:535
#define STANDARD20_MODULE_STUFF
void ap_random_insecure_bytes(void *buf, apr_size_t size)
Definition core.c:5455
#define ap_strchr_c(s, c)
Definition httpd.h:2353
char * ap_pregsub(apr_pool_t *p, const char *input, const char *source, apr_size_t nmatch, ap_regmatch_t pmatch[])
Definition util.c:457
#define ap_assert(exp)
Definition httpd.h:2271
ap_regex_t * ap_pregcomp(apr_pool_t *p, const char *pattern, int cflags)
Definition util.c:262
char * ap_getword_conf(apr_pool_t *p, const char **line)
Definition util.c:833
apr_size_t size
#define apr_isalnum(c)
Definition apr_lib.h:203
#define apr_isdigit(c)
Definition apr_lib.h:209
int strcasecmp(const char *a, const char *b)
int strncasecmp(const char *a, const char *b, size_t n)
apr_interval_time_t apr_int32_t * num
Definition apr_poll.h:273
#define apr_pcalloc(p, size)
Definition apr_pools.h:465
void * random
Definition apr_random.h:99
const char * s
Definition apr_strings.h:95
apr_int32_t apr_int32_t apr_int32_t err
apr_cmdtype_e cmd
APR_DECLARE_DATA const char apr_month_snames[12][4]
Definition timestr.c:33
APR_DECLARE_DATA const char apr_day_snames[7][4]
Definition timestr.c:37
apr_int64_t apr_time_t
Definition apr_time.h:45
#define apr_time_from_sec(sec)
Definition apr_time.h:78
Apache Configuration.
CORE HTTP Daemon.
Apache Logging library.
Apache Request library.
HTTP Daemon routines.
apr_pool_t * p
Definition md_event.c:32
return NULL
Definition mod_so.c:359
static void make_cookie(request_rec *r)
static void * make_cookie_dir(apr_pool_t *p, char *d)
#define NUM_SUBS
static int spot_cookie(request_rec *r)
cookie_type_e
@ CT_NETSCAPE
@ CT_UNSET
@ CT_COOKIE2
@ CT_COOKIE
static const command_rec cookie_log_cmds[]
static void set_and_comp_regexp(cookie_dir_rec *dcfg, apr_pool_t *p, const char *cookie_name)
static const char * set_cookie_exp(cmd_parms *parms, void *dummy, const char *arg)
static void register_hooks(apr_pool_t *p)
static const char * set_cookie_domain(cmd_parms *cmd, void *mconfig, const char *name)
#define COOKIE_NAME
static const char * set_cookie_name(cmd_parms *cmd, void *mconfig, const char *name)
static const char * set_cookie_style(cmd_parms *cmd, void *mconfig, const char *name)
static void * make_cookie_log_state(apr_pool_t *p, server_rec *s)
static const char * set_samesite_value(cmd_parms *cmd, void *mconfig, const char *name)
char * name
const char * cookie_name
const char * samesite
const char * cookie_domain
cookie_type_e style
ap_regex_t * regexp
A structure that represents the current request.
Definition httpd.h:845
apr_table_t * notes
Definition httpd.h:985
apr_pool_t * pool
Definition httpd.h:847
apr_time_t request_time
Definition httpd.h:886
apr_table_t * err_headers_out
Definition httpd.h:981
apr_table_t * headers_in
Definition httpd.h:976
request_rec * main
Definition httpd.h:860
server_rec * server
Definition httpd.h:851
struct ap_conf_vector_t * per_dir_config
Definition httpd.h:1047
A structure to store information for each virtual server.
Definition httpd.h:1322
struct ap_conf_vector_t * module_config
Definition httpd.h:1341
static apr_time_t now
Definition testtime.c:33