include/punk/punk_session.h

filter: Statementstmt 96.4% 348 / 361 Branchbran 71.3% 271 / 380 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 83.5% 619 / 741 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xs/ratelimit.xs ↑ Summary include/punk/punk_dbq.h »
1 /* punk_session.h - signed cookie sessions, in C.
2 *
3 * The session is the handler's hashref, JSON-encoded (punk_frj) and carried in
4 * a cookie as base64url(payload).base64url(HMAC-SHA256(payload, key)) - the
5 * client can read it but cannot forge it. A bundled public-domain SHA-256 (as
6 * SHA-1 was bundled for the WS handshake) keeps the dist zero-dependency.
7 *
8 * Must be included after punk_context.h (frj / pcx_*), punk_cookie.h
9 * (pk_build_cookie) and punk_names.h.
10 */
11  
12 #ifndef PUNK_SESSION_H
13 #define PUNK_SESSION_H
14  
15 /* ---- SHA-256 (public domain) ---------------------------------------------- */
16  
17 #define PS_ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
18  
19 static const U32 ps_sha256_k[64] = {
20 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
21 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
22 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
23 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
24 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
25 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
26 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
27 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
28 };
29  
30 /* The compression function over whole 64-byte blocks, folded into `h`. Split
31 * out so a caller that cannot hold its message in memory (punk_asset.h hashes
32 * a file in chunks) shares this loop rather than keeping a second copy of it
33 * in step. */
34 117702 static void ps_sha256_blocks(U32 h[8], const unsigned char *m, size_t nblocks) {
35 size_t b;
36 int i;
37 235611 ▶ for (b = 0; b < nblocks; b++) {
Branch: 1 branch
BranchTrueFalseTotal
for (b = 0; b < nblocks; b++) { 117909 117702 235611
38 117909 const unsigned char *p = m + b * 64;
39 U32 w[64], a, c0, c, d, e, f, g, hh, t1, t2;
40 2004453 ▶ for (i = 0; i < 16; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 16; i++) 1886544 117909 2004453
41 1886544 w[i] = ((U32)p[4*i]<<24)|((U32)p[4*i+1]<<16)
42 1886544 | ((U32)p[4*i+2]<<8)|(U32)p[4*i+3];
43 5777541 ▶ for (i = 16; i < 64; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 16; i < 64; i++) { 5659632 117909 5777541
44 5659632 U32 s0 = PS_ROR(w[i-15],7) ^ PS_ROR(w[i-15],18) ^ (w[i-15]>>3);
45 5659632 U32 s1 = PS_ROR(w[i-2],17) ^ PS_ROR(w[i-2],19) ^ (w[i-2]>>10);
46 5659632 w[i] = w[i-16] + s0 + w[i-7] + s1;
47 }
48 117909 a=h[0];c0=h[1];c=h[2];d=h[3];e=h[4];f=h[5];g=h[6];hh=h[7];
49 7664085 ▶ for (i = 0; i < 64; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 64; i++) { 7546176 117909 7664085
50 7546176 U32 S1 = PS_ROR(e,6)^PS_ROR(e,11)^PS_ROR(e,25);
51 7546176 U32 ch = (e & f) ^ ((~e) & g);
52 7546176 U32 S0 = PS_ROR(a,2)^PS_ROR(a,13)^PS_ROR(a,22);
53 7546176 U32 maj = (a & c0) ^ (a & c) ^ (c0 & c);
54 7546176 t1 = hh + S1 + ch + ps_sha256_k[i] + w[i];
55 7546176 t2 = S0 + maj;
56 7546176 hh=g; g=f; f=e; e=d+t1; d=c; c=c0; c0=a; a=t1+t2;
57 }
58 117909 h[0]+=a;h[1]+=c0;h[2]+=c;h[3]+=d;h[4]+=e;h[5]+=f;h[6]+=g;h[7]+=hh;
59 }
60 117702 }
61  
62 static const U32 ps_sha256_iv[8] = { 0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
63 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19 };
64  
65 /* The final block(s): the 0x80 terminator, the zero padding and the 64-bit
66 * bit-count, folded in. `rem` is what is left of the message after the whole
67 * blocks, `total` its full byte length. */
68 58831 static void ps_sha256_final(U32 h[8], const unsigned char *rest, size_t rem,
69 size_t total, unsigned char out[32]) {
70 unsigned char tail[128];
71 58831 ▶ size_t tlen = (rem < 56) ? 64 : 128;
Branch: 1 branch
BranchTrueFalseTotal
size_t tlen = (rem < 56) ? 64 : 128; 58828 3 58831
72 58831 U32 hi = (U32)(total >> 29), lo = (U32)(total << 3);
73 int i;
74 58831 memset(tail, 0, sizeof tail);
75 58831 ▶ if (rem) memcpy(tail, rest, rem);
Branch: 1 branch
BranchTrueFalseTotal
if (rem) memcpy(tail, rest, rem); 58831 0 58831
76 58831 tail[rem] = 0x80;
77 58831 tail[tlen-1]=(unsigned char)(lo&0xff); tail[tlen-2]=(unsigned char)((lo>>8)&0xff);
78 58831 tail[tlen-3]=(unsigned char)((lo>>16)&0xff); tail[tlen-4]=(unsigned char)((lo>>24)&0xff);
79 58831 tail[tlen-5]=(unsigned char)(hi&0xff); tail[tlen-6]=(unsigned char)((hi>>8)&0xff);
80 58831 tail[tlen-7]=(unsigned char)((hi>>16)&0xff); tail[tlen-8]=(unsigned char)((hi>>24)&0xff);
81 58831 ps_sha256_blocks(h, tail, tlen / 64);
82 529479 ▶ for (i = 0; i < 8; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 8; i++) { 470648 58831 529479
83 470648 out[4*i] =(unsigned char)((h[i]>>24)&0xff);
84 470648 out[4*i+1]=(unsigned char)((h[i]>>16)&0xff);
85 470648 out[4*i+2]=(unsigned char)((h[i]>>8)&0xff);
86 470648 out[4*i+3]=(unsigned char)(h[i]&0xff);
87 }
88 58831 }
89  
90 58787 static void pk_sha256(const unsigned char *msg, size_t len, unsigned char out[32]) {
91 U32 h[8];
92 58787 size_t whole = len / 64;
93 58787 memcpy(h, ps_sha256_iv, sizeof h);
94 58787 ▶ if (whole) ps_sha256_blocks(h, msg, whole);
Branch: 1 branch
BranchTrueFalseTotal
if (whole) ps_sha256_blocks(h, msg, whole); 58667 120 58787
95 58787 ps_sha256_final(h, msg + whole * 64, len - whole * 64, len, out);
96 58787 }
97  
98 29333 static void pk_hmac_sha256(const unsigned char *key, size_t klen,
99 const unsigned char *msg, size_t mlen,
100 unsigned char out[32]) {
101 unsigned char k[64], ipad[64], opad[64], ihash[32], ob[96];
102 unsigned char *ibuf;
103 int i;
104 29333 ▶ if (klen > 64) { pk_sha256(key, klen, k); memset(k+32, 0, 32); }
Branch: 1 branch
BranchTrueFalseTotal
if (klen > 64) { pk_sha256(key, klen, k); memset(k+32, 0, 32); } 0 29333 29333
105 29333 ▶ else { memcpy(k, key, klen); if (klen < 64) memset(k+klen, 0, 64-klen); }
Branch: 1 branch
BranchTrueFalseTotal
else { memcpy(k, key, klen); if (klen < 64) memset(k+klen, 0, 64-klen); } 29333 0 29333
106 1906645 ▶ for (i = 0; i < 64; i++) { ipad[i] = k[i]^0x36; opad[i] = k[i]^0x5c; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 64; i++) { ipad[i] = k[i]^0x36; opad[i] = k[i]^0x5c; } 1877312 29333 1906645
107 29333 Newx(ibuf, 64 + mlen, unsigned char);
108 29333 memcpy(ibuf, ipad, 64);
109 29333 ▶ if (mlen) memcpy(ibuf+64, msg, mlen);
Branch: 1 branch
BranchTrueFalseTotal
if (mlen) memcpy(ibuf+64, msg, mlen); 29333 0 29333
110 29333 pk_sha256(ibuf, 64+mlen, ihash);
111 29333 Safefree(ibuf);
112 29333 memcpy(ob, opad, 64);
113 29333 memcpy(ob+64, ihash, 32);
114 29333 pk_sha256(ob, 96, out);
115 29333 }
116  
117 /* ---- base64url (no padding, cookie-safe) ---------------------------------- */
118  
119 static const char PS_B64U[] =
120 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
121  
122 4572 static SV *pk_b64url(pTHX_ const unsigned char *in, size_t len) {
123 4572 SV *out = newSVpvs("");
124 4572 size_t i = 0;
125 30346 ▶ for (; i + 3 <= len; i += 3) {
Branch: 1 branch
BranchTrueFalseTotal
for (; i + 3 <= len; i += 3) { 25774 4572 30346
126 25774 U32 n = ((U32)in[i]<<16)|((U32)in[i+1]<<8)|in[i+2];
127 25774 char c[4] = { PS_B64U[(n>>18)&63], PS_B64U[(n>>12)&63],
128 25774 PS_B64U[(n>>6)&63], PS_B64U[n&63] };
129 25774 sv_catpvn(out, c, 4);
130 }
131 4572 ▶ if (i < len) {
Branch: 1 branch
BranchTrueFalseTotal
if (i < len) { 4265 307 4572
132 4265 int rem = (int)(len - i), cn = 2;
133 4265 U32 n = (U32)in[i]<<16;
134 char c[3];
135 4265 ▶ if (rem == 2) n |= (U32)in[i+1]<<8;
Branch: 1 branch
BranchTrueFalseTotal
if (rem == 2) n |= (U32)in[i+1]<<8; 470 3795 4265
136 4265 c[0] = PS_B64U[(n>>18)&63];
137 4265 c[1] = PS_B64U[(n>>12)&63];
138 4265 ▶ if (rem == 2) c[cn++] = PS_B64U[(n>>6)&63];
Branch: 1 branch
BranchTrueFalseTotal
if (rem == 2) c[cn++] = PS_B64U[(n>>6)&63]; 470 3795 4265
139 4265 sv_catpvn(out, c, cn);
140 }
141 4572 return out;
142 }
143  
144 14223 static int ps_b64u_val(unsigned char c) {
145 14223 ▶ if (c>='A'&&c<='Z') return c-'A';
Branch: 2 branches
BranchTrueFalseTotal
if (c>='A'&&c<='Z') return c-'A'; 12064 2159 14223
if (c>='A'&&c<='Z') return c-'A'; 6617 5447 12064
146 7606 ▶ if (c>='a'&&c<='z') return c-'a'+26;
Branch: 2 branches
BranchTrueFalseTotal
if (c>='a'&&c<='z') return c-'a'+26; 5447 2159 7606
if (c>='a'&&c<='z') return c-'a'+26; 5447 0 5447
147 2159 ▶ if (c>='0'&&c<='9') return c-'0'+52;
Branch: 2 branches
BranchTrueFalseTotal
if (c>='0'&&c<='9') return c-'0'+52; 2159 0 2159
if (c>='0'&&c<='9') return c-'0'+52; 2159 0 2159
148 0 ▶ if (c=='-') return 62;
Branch: 1 branch
BranchTrueFalseTotal
if (c=='-') return 62; 0 0 0
149 0 ▶ if (c=='_') return 63;
Branch: 1 branch
BranchTrueFalseTotal
if (c=='_') return 63; 0 0 0
150 0 return -1;
151 }
152  
153 190 static SV *pk_b64url_decode(pTHX_ const char *in, size_t len) {
154 190 SV *out = newSVpvs("");
155 190 U32 acc = 0; int bits = 0; size_t i;
156 14413 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 14223 190 14413
157 14223 int v = ps_b64u_val((unsigned char)in[i]);
158 14223 ▶ if (v < 0) { SvREFCNT_dec(out); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (v < 0) { SvREFCNT_dec(out); return NULL; } 0 14223 14223
159 14223 acc = (acc << 6) | (U32)v; bits += 6;
160 14223 ▶ if (bits >= 8) { unsigned char b; bits -= 8; b = (acc >> bits) & 0xff;
Branch: 1 branch
BranchTrueFalseTotal
if (bits >= 8) { unsigned char b; bits -= 8; b = (acc >> bits) & 0xff; 10620 3603 14223
161 10620 sv_catpvn(out, (char *)&b, 1); }
162 }
163 190 return out;
164 }
165  
166 /* ---- sign / verify -------------------------------------------------------- */
167  
168 /* payload -> "base64url(payload).base64url(HMAC(base64url(payload)))" (+1) */
169 135 static SV *pk_session_sign(pTHX_ SV *payload, const char *key, STRLEN klen) {
170 135 STRLEN pl; const char *p = SvPV_const(payload, pl);
171 unsigned char mac[32];
172 135 SV *b64p = pk_b64url(aTHX_ (const unsigned char *)p, pl);
173 SV *out;
174 135 pk_hmac_sha256((const unsigned char *)key, klen,
175 135 (const unsigned char *)SvPVX(b64p), SvCUR(b64p), mac);
176 135 out = newSVsv(b64p);
177 135 SvREFCNT_dec(b64p);
178 135 sv_catpvs(out, ".");
179 135 { SV *b64m = pk_b64url(aTHX_ mac, 32); sv_catsv(out, b64m); SvREFCNT_dec(b64m); }
180 135 return out;
181 }
182  
183 /* verify a cookie value; on a good signature return the decoded payload (+1),
184 * else NULL. Constant-time signature compare. */
185 202 static SV *pk_session_verify(pTHX_ const char *cookie, STRLEN clen,
186 const char *key, STRLEN klen) {
187 202 STRLEN i, dot = clen;
188 const char *b64p, *sig;
189 STRLEN b64pl, sigl;
190 unsigned char mac[32];
191 SV *expsig;
192 8861 ▶ for (i = clen; i > 0; i--) if (cookie[i-1] == '.') { dot = i-1; break; }
Branch: 2 branches
BranchTrueFalseTotal
for (i = clen; i > 0; i--) if (cookie[i-1] == '.') { dot = i-1; break; } 198 8659 8857
for (i = clen; i > 0; i--) if (cookie[i-1] == '.') { dot = i-1; break; } 8857 4 8861
193 202 ▶ if (dot >= clen) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (dot >= clen) return NULL; 4 198 202
194 198 b64p = cookie; b64pl = dot;
195 198 sig = cookie + dot + 1; sigl = clen - dot - 1;
196 198 pk_hmac_sha256((const unsigned char *)key, klen,
197 (const unsigned char *)b64p, b64pl, mac);
198 198 expsig = pk_b64url(aTHX_ mac, 32);
199 198 ▶ if (SvCUR(expsig) != sigl) { SvREFCNT_dec(expsig); return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (SvCUR(expsig) != sigl) { SvREFCNT_dec(expsig); return NULL; } 3 195 198
200 {
201 195 const char *e = SvPVX(expsig);
202 195 unsigned char diff = 0;
203 STRLEN j;
204 8580 ▶ for (j = 0; j < sigl; j++) diff |= (unsigned char)(e[j] ^ sig[j]);
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < sigl; j++) diff |= (unsigned char)(e[j] ^ sig[j]); 8385 195 8580
205 195 SvREFCNT_dec(expsig);
206 195 ▶ if (diff) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (diff) return NULL; 5 190 195
207 }
208 190 return pk_b64url_decode(aTHX_ b64p, b64pl);
209 }
210  
211 /* ---- the session lifecycle ------------------------------------------------ *
212 * $c->session is a hashref cached in the stash under `punk.session` alongside
213 * the canonical serialization it loaded with (`punk.session.orig`); the after-
214 * dispatch write-back re-signs a Set-Cookie only when that serialization
215 * changed, or deletes the cookie when session_expire set `punk.session.expire`. */
216  
217 /* the session config the `session` keyword froze on the app, or NULL */
218 749 static HV *ps_cfg(pTHX_ SV *c) {
219 749 SV *app = pcx_get(aTHX_ pcx_av(aTHX_ c), PCX_APP);
220 SV **s;
221 749 ▶ if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 749 0 749
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 749 0 749
if (!(app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)) return NULL; 0 749 749
222 749 s = hv_fetchs((HV *)SvRV(app), "session", 0);
223 746 ▶ return (s && *s && SvROK(*s) && SvTYPE(SvRV(*s)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
return (s && *s && SvROK(*s) && SvTYPE(SvRV(*s)) == SVt_PVHV) 746 0 746
return (s && *s && SvROK(*s) && SvTYPE(SvRV(*s)) == SVt_PVHV) 746 0 746
return (s && *s && SvROK(*s) && SvTYPE(SvRV(*s)) == SVt_PVHV) 746 0 746
224 1495 ▶ ? (HV *)SvRV(*s) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? (HV *)SvRV(*s) : NULL; 746 3 749
225 }
226  
227 1396 static const char *ps_cfg_str(pTHX_ HV *cfg, const char *k, const char *def,
228 STRLEN *len) {
229 1396 SV **e = hv_fetch(cfg, k, (I32)strlen(k), 0);
230 2792 ▶ if (e && *e && SvOK(*e)) return SvPV_const(*e, *len);
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) return SvPV_const(*e, *len); 1396 0 1396
if (e && *e && SvOK(*e)) return SvPV_const(*e, *len); 1396 0 1396
if (e && *e && SvOK(*e)) return SvPV_const(*e, *len); 1396 0 1396
231 0 *len = strlen(def);
232 0 return def;
233 }
234  
235 280 static IV ps_cfg_iv(pTHX_ HV *cfg, const char *k, IV def) {
236 280 SV **e = hv_fetch(cfg, k, (I32)strlen(k), 0);
237 280 ▶ return (e && *e && SvOK(*e)) ? SvIV(*e) : def;
Branch: 3 branches
BranchTrueFalseTotal
return (e && *e && SvOK(*e)) ? SvIV(*e) : def; 51 229 280
return (e && *e && SvOK(*e)) ? SvIV(*e) : def; 51 0 51
return (e && *e && SvOK(*e)) ? SvIV(*e) : def; 51 0 51
238 }
239  
240 /* The absolute expiry stamped into the signed payload, under a reserved key
241 * the application never sees (the same trick flash plays with punk.flash).
242 *
243 * Without it `expires` was only the browser's Max-Age: a hint to a client
244 * that is free to ignore it. The signature carries no time, so a cookie
245 * captured once stayed valid for as long as the secret did, and session_expire
246 * only asked the browser to forget a value that still authenticated. Stamping
247 * the expiry inside the signature is what makes the lifetime the server's to
248 * decide.
249 *
250 * A session cookie with no `expires` is still bounded here, because "until the
251 * browser closes" is the client's promise and not a limit on the value. */
252 #define PK_SESSION_EXP "punk.exp"
253 #define PK_SESSION_EXP_LEN 8
254 #define PK_SESSION_MAX_LIFETIME (30 * 86400)
255  
256 1375 static HV *ps_stash(pTHX_ AV *av) {
257 1375 SV *st = pcx_get(aTHX_ av, PCX_STASH);
258 1375 ▶ if (!st) { st = newRV_noinc((SV *)newHV()); (void)av_store(av, PCX_STASH, st); }
Branch: 1 branch
BranchTrueFalseTotal
if (!st) { st = newRV_noinc((SV *)newHV()); (void)av_store(av, PCX_STASH, st); } 1063 312 1375
259 1375 return (HV *)SvRV(st);
260 }
261  
262 /* canonical JSON of an SV (+1) - stable across key order for the dirty check */
263 597 static SV *ps_encode(pTHX_ SV *data) {
264 frj_opts o;
265 597 Zero(&o, 1, frj_opts);
266 597 o.canonical = 1;
267 597 return punk_frj(aTHX)->encode(aTHX_ data, &o);
268 }
269  
270 /* "7d" / "1h" / "30m" / "3600" -> seconds */
271 21 static IV ps_parse_duration(pTHX_ SV *v) {
272 STRLEN l; const char *s;
273 21 IV n = 0; STRLEN i = 0;
274 21 ▶ if (SvIOK(v) || looks_like_number(v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvIOK(v) || looks_like_number(v)) { 21 0 21
275 /* a bare number with no unit is seconds unless a unit follows */
276 }
277 21 s = SvPV_const(v, l);
278 42 ▶ while (i < l && s[i] >= '0' && s[i] <= '9') { n = n * 10 + (s[i] - '0'); i++; }
Branch: 3 branches
BranchTrueFalseTotal
while (i < l && s[i] >= '0' && s[i] <= '9') { n = n * 10 + (s[i] - '0'); i++; } 42 0 42
while (i < l && s[i] >= '0' && s[i] <= '9') { n = n * 10 + (s[i] - '0'); i++; } 42 0 42
while (i < l && s[i] >= '0' && s[i] <= '9') { n = n * 10 + (s[i] - '0'); i++; } 21 21 42
279 21 ▶ if (i < l) {
Branch: 1 branch
BranchTrueFalseTotal
if (i < l) { 21 0 21
280 21 switch (s[i]) {
281 1 case 's': break;
282 0 case 'm': n *= 60; break;
283 4 case 'h': n *= 3600; break;
284 16 case 'd': n *= 86400; break;
285 0 case 'w': n *= 604800; break;
286 0 default: break;
287 }
288 }
289 21 return n;
290 }
291  
292 /* The options `session` understands.
293 *
294 * It used to copy every pair it was given straight into the config, so a typo
295 * was silent: `htponly => 1` looked configured and was not. That was survivable
296 * while every option was a cookie attribute with a safe default. It stopped
297 * being survivable with `store`, where the typo's failure is "everything works
298 * and the store stays empty" - a cookie session, at the 4KB ceiling, wearing
299 * the configuration of a server-side one.
300 *
301 * `max_age` is here as well as `expires` because it is what the frozen config
302 * actually holds: reading one back and passing it in again should not croak. */
303 static const char *const PS_KEYS[] = {
304 "secret", "cookie", "expires", "max_age", "path", "domain", "secure",
305 "httponly", "samesite", "store", "allow_unshared", "sliding", "tier", NULL
306 };
307  
308 /* `cfg` is the half-built config to release first: this croak is catchable
309 * (a test, an eval around to_app), so leaking it on the way out would be a
310 * leak per attempt rather than one on a process that is about to die. */
311 197 static void ps_check_key(pTHX_ const char *k, STRLEN kl, HV *cfg) {
312 int i;
313 794 ▶ for (i = 0; PS_KEYS[i]; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; PS_KEYS[i]; i++) 792 2 794
314 792 ▶ if (strlen(PS_KEYS[i]) == kl && memEQ(k, PS_KEYS[i], kl)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (strlen(PS_KEYS[i]) == kl && memEQ(k, PS_KEYS[i], kl)) return; 226 566 792
if (strlen(PS_KEYS[i]) == kl && memEQ(k, PS_KEYS[i], kl)) return; 195 31 226
315 2 ▶ if (cfg) SvREFCNT_dec((SV *)cfg);
Branch: 1 branch
BranchTrueFalseTotal
if (cfg) SvREFCNT_dec((SV *)cfg); 2 0 2
316 2 croak("Punk: `session` does not understand `%.*s`. It takes secret, "
317 "cookie, expires, path, domain, secure, httponly, samesite, store, "
318 "sliding, tier and allow_unshared", (int)kl, k);
319 }
320  
321 /* ---- the server-side store, when there is one ------------------------------ *
322 *
323 * `session store => ...` moves the payload off the client: the cookie carries a
324 * signed id and the session itself lives in a Punk::Cache. The seam is narrow
325 * on purpose - three method calls, get / set / delete - so any backend that
326 * satisfies that contract can hold a session, including one from outside this
327 * distribution.
328 *
329 * The id helpers are declared and not defined here. They need punk_entropy.h,
330 * which needs punk_csrf.h, which needs this file, so they live in
331 * punk_sessionstore.h and are reached from here by declaration. The compiler
332 * still checks the signatures; the ordering is the only thing being worked
333 * around. */
334 static SV *ps_new_id(pTHX);
335 static SV *ps_id_seal(pTHX_ SV *id, const char *key, STRLEN kl, IV ttl);
336 static SV *ps_id_unseal(pTHX_ const char *cv, STRLEN cvl,
337 const char *key, STRLEN kl);
338 /* the one read that has to know about the memory tier - see punk_sessionstore.h
339 * for why a session goes round it unless asked not to */
340 static SV *ps_store_get(pTHX_ SV *store, SV *key, int use_tier);
341  
342 /* The id this request arrived with, kept beside the session it named so the
343 * write-back knows whether the client already has it. */
344 #define PK_SESSION_SID "punk.session.id"
345 #define PK_SESSION_SID_LEN 15
346  
347 /* Set by session_rotate: the id to retire once the new one is written. */
348 #define PK_SESSION_ROT "punk.session.rotate"
349 #define PK_SESSION_ROT_LEN 19
350  
351 /* When the entry was last written, stamped inside the stored payload under a
352 * reserved key the application never sees - the same trick the cookie plays
353 * with punk.exp, and flash with punk.flash.
354 *
355 * It exists for the sliding expiry, which has to answer "how much of this
356 * session's life is left" and cannot ask the store: `get` returns bytes, and
357 * a contract that also reported an entry's expiry would be a sixth thing for
358 * every backend to implement. One integer in the payload answers it for all
359 * of them. */
360 #define PK_SESSION_AT "punk.at"
361 #define PK_SESSION_AT_LEN 7
362 #define PK_SESSION_AT_STASH "punk.session.at"
363 #define PK_SESSION_AT_STASH_LEN 15
364  
365 /* What a stored session may weigh.
366 *
367 * The cookie's ~4KB ceiling was the wire format's, and it goes: a basket in a
368 * session stops being a croak. Unbounded is not what replaces it, because a
369 * session an application can grow without limit is a way to fill somebody's
370 * store from a login form. A megabyte is far past any legitimate session and
371 * far below anything that threatens a store. */
372 #define PK_SESSION_STORE_MAX (1024 * 1024)
373  
374 /* the store the resolution put on the config at to_app, or NULL for a cookie
375 * session - which is every application that did not ask for one */
376 588 static SV *ps_cfg_store(pTHX_ HV *cfg) {
377 588 SV **s = hv_fetchs(cfg, "punk.store", 0);
378 588 ▶ return (s && *s && SvROK(*s)) ? *s : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (s && *s && SvROK(*s)) ? *s : NULL; 177 411 588
return (s && *s && SvROK(*s)) ? *s : NULL; 177 0 177
return (s && *s && SvROK(*s)) ? *s : NULL; 177 0 177
379 }
380  
381 /* The id this request arrived with (+1), unsealed from the cookie, or NULL.
382 *
383 * Separate from ps_load because a logout may never have read the session:
384 * `post '/logout' => sub { $_[0]->session_expire }` touches nothing, and the
385 * entry still has to be deleted. Revocation that depends on the handler
386 * having looked at the session first would be revocation that usually does
387 * not happen. */
388 /* The named request cookie's value (+1), or NULL: what Punk::Request::cookie
389 * answers (first value wins, decoded), read without building the request
390 * object and the two method frames. The request's own parsed table is used
391 * when it has one, and filled when the request exists but has not parsed
392 * yet, so a later $c->req->cookies finds the work done. */
393 365 static SV *ps_cookie_value(pTHX_ AV *av, const char *name, STRLEN nl) {
394 365 SV *req = pcx_get(aTHX_ av, PCX_REQ);
395 45 ▶ AV *reqav = (req && SvROK(req) && SvTYPE(SvRV(req)) == SVt_PVAV)
Branch: 2 branches
BranchTrueFalseTotal
AV *reqav = (req && SvROK(req) && SvTYPE(SvRV(req)) == SVt_PVAV) 45 0 45
AV *reqav = (req && SvROK(req) && SvTYPE(SvRV(req)) == SVt_PVAV) 45 0 45
396 410 ▶ ? (AV *)SvRV(req) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? (AV *)SvRV(req) : NULL; 45 320 365
397 365 HV *table = NULL;
398 SV **v;
399 365 ▶ if (reqav) {
Branch: 1 branch
BranchTrueFalseTotal
if (reqav) { 45 320 365
400 45 SV **ck = av_fetch(reqav, PQ_COOKIES, 0);
401 45 ▶ if (ck && *ck && SvROK(*ck) && SvTYPE(SvRV(*ck)) == SVt_PVHV)
Branch: 4 branches
BranchTrueFalseTotal
if (ck && *ck && SvROK(*ck) && SvTYPE(SvRV(*ck)) == SVt_PVHV) 0 45 45
if (ck && *ck && SvROK(*ck) && SvTYPE(SvRV(*ck)) == SVt_PVHV) 0 0 0
if (ck && *ck && SvROK(*ck) && SvTYPE(SvRV(*ck)) == SVt_PVHV) 0 0 0
if (ck && *ck && SvROK(*ck) && SvTYPE(SvRV(*ck)) == SVt_PVHV) 0 0 0
402 0 table = (HV *)SvRV(*ck);
403 }
404 365 ▶ if (!table) {
Branch: 1 branch
BranchTrueFalseTotal
if (!table) { 365 0 365
405 365 SV *envsv = pcx_get(aTHX_ av, PCX_ENV);
406 365 ▶ HV *env = (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
HV *env = (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 365 0 365
HV *env = (envsv && SvROK(envsv) && SvTYPE(SvRV(envsv)) == SVt_PVHV) 365 0 365
407 730 ▶ ? (HV *)SvRV(envsv) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? (HV *)SvRV(envsv) : NULL; 365 0 365
408 365 ▶ SV **h = env ? hv_fetchs(env, "HTTP_COOKIE", 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV **h = env ? hv_fetchs(env, "HTTP_COOKIE", 0) : NULL; 365 0 365
409 365 STRLEN hl = 0;
410 590 ▶ const char *hs = (h && *h && SvOK(*h)) ? SvPV_const(*h, hl) : "";
Branch: 3 branches
BranchTrueFalseTotal
const char *hs = (h && *h && SvOK(*h)) ? SvPV_const(*h, hl) : ""; 225 140 365
const char *hs = (h && *h && SvOK(*h)) ? SvPV_const(*h, hl) : ""; 225 0 225
const char *hs = (h && *h && SvOK(*h)) ? SvPV_const(*h, hl) : ""; 225 0 225
411 365 ▶ if (!hl) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!hl) return NULL; 140 225 365
412 225 table = pq_parse_cookies(aTHX_ hs, hl);
413 225 ▶ if (reqav) (void)pq_cached(aTHX_ reqav, PQ_COOKIES, table);
Branch: 1 branch
BranchTrueFalseTotal
if (reqav) (void)pq_cached(aTHX_ reqav, PQ_COOKIES, table); 23 202 225
414 202 else sv_2mortal((SV *)table);
415 }
416 225 v = hv_fetch(table, name, (I32)nl, 0);
417 225 ▶ return (v && *v) ? newSVsv(*v) : NULL;
Branch: 2 branches
BranchTrueFalseTotal
return (v && *v) ? newSVsv(*v) : NULL; 225 0 225
return (v && *v) ? newSVsv(*v) : NULL; 225 0 225
418 }
419  
420 94 static SV *ps_req_id(pTHX_ SV *c, HV *cfg) {
421 94 AV *av = pcx_av(aTHX_ c);
422 STRLEN nl, kl, cvl;
423 94 const char *cookie_name = ps_cfg_str(aTHX_ cfg, "cookie", "punk.sid", &nl);
424 94 const char *key = ps_cfg_str(aTHX_ cfg, "secret", "", &kl);
425 94 SV *cval = ps_cookie_value(aTHX_ av, cookie_name, nl);
426 94 ▶ if (!cval) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!cval) return NULL; 41 53 94
427 53 sv_2mortal(cval);
428 53 ▶ if (!(SvOK(cval) && SvCUR(cval))) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvOK(cval) && SvCUR(cval))) return NULL; 53 0 53
if (!(SvOK(cval) && SvCUR(cval))) return NULL; 0 53 53
429 /* The SvPV goes in its OWN statement, and the length is read after it.
430 *
431 * `ps_id_unseal(aTHX_ SvPV_const(cval, cvl), cvl, ...)` is the same bug as
432 * a multi-eval Sv macro around POPs: the macro assigns cvl and the sibling
433 * argument reads it, and C does not say which happens first. clang went
434 * left to right and worked; gcc goes right to left, read cvl before it was
435 * ever assigned, and handed a garbage length to the verifier - which
436 * walked off the buffer. It crashed on every request carrying a cookie,
437 * on every non-threaded smoker, and on nothing here. */
438 {
439 53 const char *cv = SvPV_const(cval, cvl);
440 53 return ps_id_unseal(aTHX_ cv, cvl, key, kl);
441 }
442 }
443  
444 /* Give the session a new name at the write-back: the id to retire goes
445 * under PK_SESSION_ROT and the current one is forgotten. session_rotate and
446 * login both land here.
447 *
448 * When the stash holds no id the cookie is asked. A logout followed by a
449 * login never loaded the session, and a second rotation in one request has
450 * already forgotten the id: either way the entry the request named still has
451 * to go. */
452 37 static void ps_mark_rotate(pTHX_ SV *c, HV *cfg, HV *stash) {
453 SV **idp;
454 37 SV *old = NULL;
455 37 idp = hv_fetch(stash, PK_SESSION_SID, PK_SESSION_SID_LEN, 0);
456 37 ▶ if (idp && *idp && SvOK(*idp)) old = newSVsv(*idp);
Branch: 3 branches
BranchTrueFalseTotal
if (idp && *idp && SvOK(*idp)) old = newSVsv(*idp); 6 31 37
if (idp && *idp && SvOK(*idp)) old = newSVsv(*idp); 6 0 6
if (idp && *idp && SvOK(*idp)) old = newSVsv(*idp); 6 0 6
457 31 ▶ else if (cfg && ps_cfg_store(aTHX_ cfg)) old = ps_req_id(aTHX_ c, cfg);
Branch: 2 branches
BranchTrueFalseTotal
else if (cfg && ps_cfg_store(aTHX_ cfg)) old = ps_req_id(aTHX_ c, cfg); 31 0 31
else if (cfg && ps_cfg_store(aTHX_ cfg)) old = ps_req_id(aTHX_ c, cfg); 7 24 31
458 37 ▶ (void)hv_store(stash, PK_SESSION_ROT, PK_SESSION_ROT_LEN,
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_store(stash, PK_SESSION_ROT, PK_SESSION_ROT_LEN, 28 9 37
459 old ? old : newSV(0), 0);
460 37 (void)hv_delete(stash, PK_SESSION_SID, PK_SESSION_SID_LEN, G_DISCARD);
461 37 }
462  
463 /* Secure when the options do not say: on for a request that arrived over
464 * https, so a session cookie set there is never sent in the clear. */
465 305 static int ps_secure_default(pTHX_ SV *c) {
466 305 SV *env = pcx_get(aTHX_ pcx_av(aTHX_ c), PCX_ENV);
467 SV **e;
468 STRLEN l;
469 const char *v;
470 305 ▶ if (!(env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV)) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!(env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV)) return 0; 305 0 305
if (!(env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV)) return 0; 305 0 305
if (!(env && SvROK(env) && SvTYPE(SvRV(env)) == SVt_PVHV)) return 0; 0 305 305
471 305 e = hv_fetchs((HV *)SvRV(env), "psgi.url_scheme", 0);
472 305 ▶ if (!(e && *e && SvOK(*e))) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!(e && *e && SvOK(*e))) return 0; 180 125 305
if (!(e && *e && SvOK(*e))) return 0; 180 0 180
if (!(e && *e && SvOK(*e))) return 0; 0 180 180
473 180 v = SvPV_const(*e, l);
474 180 ▶ return l == 5 && memEQ(v, "https", 5);
Branch: 2 branches
BranchTrueFalseTotal
return l == 5 && memEQ(v, "https", 5); 5 175 180
return l == 5 && memEQ(v, "https", 5); 5 0 5
475 }
476  
477 /* $c->session: load (once) from the signed cookie and cache the hashref (+1) */
478 378 static SV *ps_load(pTHX_ SV *c) {
479 378 AV *av = pcx_av(aTHX_ c);
480 378 HV *stash = ps_stash(aTHX_ av);
481 378 SV **cached = hv_fetchs(stash, "punk.session", 0);
482 378 HV *cfg, *sess = NULL;
483 STRLEN nl, kl;
484 const char *cookie_name, *key;
485 SV *cval, *rv, *store;
486 378 ▶ if (cached && *cached && SvROK(*cached)) return newSVsv(*cached);
Branch: 3 branches
BranchTrueFalseTotal
if (cached && *cached && SvROK(*cached)) return newSVsv(*cached); 106 272 378
if (cached && *cached && SvROK(*cached)) return newSVsv(*cached); 106 0 106
if (cached && *cached && SvROK(*cached)) return newSVsv(*cached); 106 0 106
487 272 cfg = ps_cfg(aTHX_ c);
488 272 ▶ if (!cfg) croak("Punk: no session configured (add a `session` keyword)");
Branch: 1 branch
BranchTrueFalseTotal
if (!cfg) croak("Punk: no session configured (add a `session` keyword)"); 1 271 272
489 271 cookie_name = ps_cfg_str(aTHX_ cfg, "cookie", "punk.sid", &nl);
490 271 key = ps_cfg_str(aTHX_ cfg, "secret", "", &kl);
491 271 cval = ps_cookie_value(aTHX_ av, cookie_name, nl);
492 271 ▶ if (cval) sv_2mortal(cval);
Branch: 1 branch
BranchTrueFalseTotal
if (cval) sv_2mortal(cval); 172 99 271
493 271 store = ps_cfg_store(aTHX_ cfg);
494 271 ▶ if (store) {
Branch: 1 branch
BranchTrueFalseTotal
if (store) { 82 189 271
495 /* THE STORE ROUND TRIP HAPPENS HERE, and only here - which is why
496 * $c->session is loaded on demand rather than per request. A route
497 * that never asks for the session never pays for it: a static asset,
498 * a health check, an API route on a bearer token. The consequence to
499 * remember is the other way round - a request that never touches the
500 * session does not extend it either. */
501 /* A forged, tampered or expired cookie yields no id, and no id means
502 * no lookup: a guess never reaches the backend. */
503 82 SV *id = ps_req_id(aTHX_ c, cfg);
504 82 ▶ if (id) {
Branch: 1 branch
BranchTrueFalseTotal
if (id) { 43 39 82
505 SV *raw;
506 43 sv_2mortal(id);
507 43 raw = ps_store_get(aTHX_ store, id,
508 43 ps_cfg_iv(aTHX_ cfg, "tier", 0) ? 1 : 0);
509 43 ▶ if (raw) sv_2mortal(raw);
Branch: 1 branch
BranchTrueFalseTotal
if (raw) sv_2mortal(raw); 35 8 43
510 43 ▶ if (raw && SvOK(raw)) {
Branch: 2 branches
BranchTrueFalseTotal
if (raw && SvOK(raw)) { 35 8 43
if (raw && SvOK(raw)) { 35 0 35
511 STRLEN rl;
512 35 const char *rb = SvPV_const(raw, rl);
513 35 SV *decoded = punk_frj(aTHX)->decode(aTHX_ rb, rl, NULL);
514 35 ▶ if (decoded) sv_2mortal(decoded);
Branch: 1 branch
BranchTrueFalseTotal
if (decoded) sv_2mortal(decoded); 35 0 35
515 35 ▶ if (decoded && SvROK(decoded)
Branch: 2 branches
BranchTrueFalseTotal
if (decoded && SvROK(decoded) 35 0 35
if (decoded && SvROK(decoded) 35 0 35
516 35 ▶ && SvTYPE(SvRV(decoded)) == SVt_PVHV) {
Branch: 1 branch
BranchTrueFalseTotal
&& SvTYPE(SvRV(decoded)) == SVt_PVHV) { 35 0 35
517 SV **atp;
518 SV *rvs;
519 35 sess = newHVhv((HV *)SvRV(decoded));
520 /* the write stamp is ours, not the application's: it is
521 * lifted into the stash and stripped before anything sees
522 * the hash, so the dirty check compares like with like */
523 35 atp = hv_fetch(sess, PK_SESSION_AT, PK_SESSION_AT_LEN, 0);
524 35 ▶ if (atp && *atp && SvOK(*atp))
Branch: 3 branches
BranchTrueFalseTotal
if (atp && *atp && SvOK(*atp)) 35 0 35
if (atp && *atp && SvOK(*atp)) 35 0 35
if (atp && *atp && SvOK(*atp)) 35 0 35
525 35 (void)hv_store(stash, PK_SESSION_AT_STASH,
526 PK_SESSION_AT_STASH_LEN,
527 newSVsv(*atp), 0);
528 35 (void)hv_delete(sess, PK_SESSION_AT, PK_SESSION_AT_LEN,
529 G_DISCARD);
530 35 rvs = sv_2mortal(newRV_inc((SV *)sess));
531 35 (void)hv_stores(stash, "punk.session.orig",
532 ps_encode(aTHX_ rvs));
533 35 (void)hv_store(stash, PK_SESSION_SID, PK_SESSION_SID_LEN,
534 newSVsv(id), 0);
535 }
536 }
537 /* An id whose entry has gone - expired, evicted, or deleted by a
538 * logout - is NOT carried forward. The session starts empty and
539 * the write-back mints a fresh id, so a revoked id can never come
540 * back to life as the name of a new session. */
541 }
542 }
543 189 ▶ else if (cval && SvOK(cval) && SvCUR(cval)) {
Branch: 3 branches
BranchTrueFalseTotal
else if (cval && SvOK(cval) && SvCUR(cval)) { 127 62 189
else if (cval && SvOK(cval) && SvCUR(cval)) { 127 0 127
else if (cval && SvOK(cval) && SvCUR(cval)) { 127 0 127
544 127 STRLEN cvl; const char *cv = SvPV_const(cval, cvl);
545 127 SV *payload = pk_session_verify(aTHX_ cv, cvl, key, kl);
546 127 ▶ if (payload) {
Branch: 1 branch
BranchTrueFalseTotal
if (payload) { 126 1 127
547 SV *decoded;
548 126 sv_2mortal(payload);
549 126 decoded = punk_frj(aTHX)->decode(aTHX_ SvPVX(payload), SvCUR(payload), NULL);
550 126 ▶ if (decoded) sv_2mortal(decoded);
Branch: 1 branch
BranchTrueFalseTotal
if (decoded) sv_2mortal(decoded); 126 0 126
551 126 ▶ if (decoded && SvROK(decoded) && SvTYPE(SvRV(decoded)) == SVt_PVHV) {
Branch: 3 branches
BranchTrueFalseTotal
if (decoded && SvROK(decoded) && SvTYPE(SvRV(decoded)) == SVt_PVHV) { 126 0 126
if (decoded && SvROK(decoded) && SvTYPE(SvRV(decoded)) == SVt_PVHV) { 126 0 126
if (decoded && SvROK(decoded) && SvTYPE(SvRV(decoded)) == SVt_PVHV) { 126 0 126
552 126 HV *dh = (HV *)SvRV(decoded);
553 126 SV **ep = hv_fetch(dh, PK_SESSION_EXP, PK_SESSION_EXP_LEN, 0);
554 /* A payload past its stamped expiry is not a session. It is
555 * left to fall through to the empty one below, so an expired
556 * cookie logs the user out rather than half-loading. */
557 126 ▶ if (!ep || !*ep || !SvOK(*ep) || SvIV(*ep) > (IV)time(NULL)) {
Branch: 4 branches
BranchTrueFalseTotal
if (!ep || !*ep || !SvOK(*ep) || SvIV(*ep) > (IV)time(NULL)) { 124 2 126
if (!ep || !*ep || !SvOK(*ep) || SvIV(*ep) > (IV)time(NULL)) { 124 0 124
if (!ep || !*ep || !SvOK(*ep) || SvIV(*ep) > (IV)time(NULL)) { 124 0 124
if (!ep || !*ep || !SvOK(*ep) || SvIV(*ep) > (IV)time(NULL)) { 122 2 124
558 SV *rvs;
559 124 sess = newHVhv(dh); /* a fresh copy */
560 /* the expiry is ours, not the application's: strip it
561 * before anything sees the hash, and take the dirty-check
562 * baseline from the stripped copy so it compares like
563 * with like against what the write-back encodes */
564 124 (void)hv_delete(sess, PK_SESSION_EXP, PK_SESSION_EXP_LEN,
565 G_DISCARD);
566 124 rvs = sv_2mortal(newRV_inc((SV *)sess));
567 124 (void)hv_stores(stash, "punk.session.orig",
568 ps_encode(aTHX_ rvs));
569 }
570 }
571 }
572 }
573 271 ▶ if (!sess) {
Branch: 1 branch
BranchTrueFalseTotal
if (!sess) { 112 159 271
574 112 sess = newHV();
575 112 (void)hv_stores(stash, "punk.session.orig", newSVpvs(""));
576 }
577 271 rv = newRV_noinc((SV *)sess);
578 271 (void)hv_stores(stash, "punk.session", rv); /* the stash owns rv */
579 271 return newRV_inc((SV *)sess); /* a second ref, +1 */
580 }
581  
582 /* The store half of the write-back: put the session where it lives, and hand
583 * back a Set-Cookie (+1) only when the client has something new to be told -
584 * which is on creation, and otherwise never.
585 *
586 * That asymmetry is the point. On a cookie session every write is a
587 * Set-Cookie, because the cookie IS the session. Here an ordinary write
588 * touches the store and leaves the response headers alone: the id in the
589 * client's cookie still names the same session, whatever the session now
590 * contains. */
591 82 static SV *ps_store_writeback(pTHX_ HV *cfg, HV *stash, SV *store,
592 SV *sess, SV *cname, int secure) {
593 82 SV **origp = hv_fetchs(stash, "punk.session.orig", 0);
594 82 SV **idp = hv_fetch(stash, PK_SESSION_SID, PK_SESSION_SID_LEN, 0);
595 82 SV **rotp = hv_fetch(stash, PK_SESSION_ROT, PK_SESSION_ROT_LEN, 0);
596 82 SV *cur = sv_2mortal(ps_encode(aTHX_ sess));
597 82 IV ttl = ps_cfg_iv(aTHX_ cfg, "max_age", 0);
598 82 IV now = (IV)time(NULL);
599 STRLEN kl;
600 const char *key;
601 SV *id, *argv[3], *ok;
602 82 ▶ int fresh, rotating = (rotp && *rotp) ? 1 : 0, sliding = 0;
Branch: 2 branches
BranchTrueFalseTotal
int fresh, rotating = (rotp && *rotp) ? 1 : 0, sliding = 0; 10 72 82
int fresh, rotating = (rotp && *rotp) ? 1 : 0, sliding = 0; 10 0 10
603  
604 82 ▶ if (ttl <= 0) ttl = PK_SESSION_MAX_LIFETIME;
Branch: 1 branch
BranchTrueFalseTotal
if (ttl <= 0) ttl = PK_SESSION_MAX_LIFETIME; 54 28 82
605  
606 /* A session nobody named and nobody wrote to is not a session. Loading
607 * one is enough to reach here - a guard or a csrf check on a cookieless
608 * request does it - and writing it would hand every anonymous denial a
609 * store entry with the full lifetime, which is a way to fill the store,
610 * or to evict the real sessions from one with a budget. */
611 82 ▶ if (!rotating && !(idp && *idp && SvOK(*idp))
Branch: 4 branches
BranchTrueFalseTotal
if (!rotating && !(idp && *idp && SvOK(*idp)) 72 10 82
if (!rotating && !(idp && *idp && SvOK(*idp)) 29 43 72
if (!rotating && !(idp && *idp && SvOK(*idp)) 29 0 29
if (!rotating && !(idp && *idp && SvOK(*idp)) 0 29 29
612 43 ▶ && HvUSEDKEYS((HV *)SvRV(sess)) == 0)
Branch: 2 branches
BranchTrueFalseTotal
&& HvUSEDKEYS((HV *)SvRV(sess)) == 0) 0 43 43
&& HvUSEDKEYS((HV *)SvRV(sess)) == 0) 20 23 43
613 20 return NULL;
614  
615 /* Unchanged is the common case, and change detection stops being an
616 * optimisation here: it is what keeps a read-mostly application off the
617 * store's write path entirely.
618 *
619 * Two things override it. A rotation has to write even when the session
620 * is identical, because the point is that it now lives under a different
621 * name. And a sliding expiry has to write to move the expiry - but only
622 * once the session is far enough through its life to need it, or sliding
623 * would be a store write on every request, which is the cost the read
624 * path was designed to avoid. */
625 62 ▶ if (origp && *origp && sv_eq(cur, *origp) && !rotating) {
Branch: 4 branches
BranchTrueFalseTotal
if (origp && *origp && sv_eq(cur, *origp) && !rotating) { 61 1 62
if (origp && *origp && sv_eq(cur, *origp) && !rotating) { 61 0 61
if (origp && *origp && sv_eq(cur, *origp) && !rotating) { 27 34 61
if (origp && *origp && sv_eq(cur, *origp) && !rotating) { 25 2 27
626 SV **atp;
627 25 ▶ if (!ps_cfg_iv(aTHX_ cfg, "sliding", 0)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!ps_cfg_iv(aTHX_ cfg, "sliding", 0)) return NULL; 23 2 25
628 2 atp = hv_fetch(stash, PK_SESSION_AT_STASH, PK_SESSION_AT_STASH_LEN, 0);
629 2 ▶ if (!(atp && *atp && SvOK(*atp))) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!(atp && *atp && SvOK(*atp))) return NULL; 2 0 2
if (!(atp && *atp && SvOK(*atp))) return NULL; 2 0 2
if (!(atp && *atp && SvOK(*atp))) return NULL; 0 2 2
630 2 ▶ if (now - SvIV(*atp) <= ttl / 2) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (now - SvIV(*atp) <= ttl / 2) return NULL; 1 1 2
631 1 sliding = 1;
632 }
633  
634 38 key = ps_cfg_str(aTHX_ cfg, "secret", "", &kl);
635 38 ▶ if (!kl) {
Branch: 1 branch
BranchTrueFalseTotal
if (!kl) { 0 38 38
636 /* checked before the store is touched, not after: a session written
637 * under an id that can never be sealed into a cookie is an orphan */
638 0 warn("Punk: session has no secret; not saved - the id would ride in "
639 "a cookie signed with an empty key, which anyone can forge");
640 0 return NULL;
641 }
642  
643 38 ▶ if (SvCUR(cur) > PK_SESSION_STORE_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvCUR(cur) > PK_SESSION_STORE_MAX) { 1 37 38
644 /* the write-back is a trapped after-hook, so croaking would vanish */
645 1 warn("Punk: session is %d bytes, over the %d-byte limit; not saved - "
646 "a session is a name for what a user is doing, not a place to "
647 "keep what they are doing it to",
648 (int)SvCUR(cur), (int)PK_SESSION_STORE_MAX);
649 1 return NULL;
650 }
651  
652 /* A rotation always gets a new name; otherwise the one the request
653 * arrived with, if it had one.
654 *
655 * A COPY of that one, not the stash's SV. Storing the id back into the
656 * stash below frees whatever was under the key, so holding the stash's
657 * own SV here left `id` dangling and the seal below reading freed memory.
658 * It surfaced as a missing Set-Cookie rather than a crash, because this
659 * runs on a trapped after-hook: the croak vanished with the response
660 * going out perfectly formed and one header short. */
661 37 ▶ fresh = rotating || !(idp && *idp && SvOK(*idp));
Branch: 4 branches
BranchTrueFalseTotal
fresh = rotating || !(idp && *idp && SvOK(*idp)); 27 10 37
fresh = rotating || !(idp && *idp && SvOK(*idp)); 5 22 27
fresh = rotating || !(idp && *idp && SvOK(*idp)); 5 0 5
fresh = rotating || !(idp && *idp && SvOK(*idp)); 0 5 5
662 37 ▶ id = sv_2mortal(fresh ? ps_new_id(aTHX) : newSVsv(*idp));
Branch: 1 branch
BranchTrueFalseTotal
id = sv_2mortal(fresh ? ps_new_id(aTHX) : newSVsv(*idp)); 32 5 37
663  
664 /* What goes into the store is the session plus the write stamp - never
665 * the hash the application holds, which keeps its own contents and keeps
666 * the dirty check comparing stripped serializations. */
667 {
668 37 HV *payload = newHVhv((HV *)SvRV(sess));
669 SV *prv;
670 37 (void)hv_store(payload, PK_SESSION_AT, PK_SESSION_AT_LEN,
671 newSViv(now), 0);
672 37 prv = sv_2mortal(newRV_noinc((SV *)payload));
673 37 argv[1] = sv_2mortal(ps_encode(aTHX_ prv));
674 }
675 37 argv[0] = id;
676 37 argv[2] = sv_2mortal(newSViv(ttl));
677 37 ok = pcx_call_meth(aTHX_ store, "set", argv, 3, 1);
678 37 ▶ if (ok) sv_2mortal(ok);
Branch: 1 branch
BranchTrueFalseTotal
if (ok) sv_2mortal(ok); 37 0 37
679 37 ▶ if (!(ok && SvTRUE(ok))) {
Branch: 2 branches
BranchTrueFalseTotal
if (!(ok && SvTRUE(ok))) { 37 0 37
if (!(ok && SvTRUE(ok))) { 1 36 37
680 /* A store may refuse: the file store refuses a value too large for its
681 * budget rather than evicting everything else to fit, and a backend
682 * from outside this distribution may refuse for reasons of its own.
683 * Say so. A refusal that returns quietly is a login that appeared to
684 * work and a user who is not logged in. */
685 1 warn("Punk: the session store refused the write; the session was NOT "
686 "saved - check the store's budget and its `refused` count");
687 1 return NULL;
688 }
689  
690 /* The old entry goes AFTER the new one is safely written, and the order
691 * matters in one direction only. A failed delete leaves an id naming the
692 * session as it was BEFORE this request - which in the attack this
693 * defends against is the attacker's own empty session, and which expires
694 * on its own TTL. A failed write after a delete would be a user logged
695 * out at the moment they logged in. */
696 36 ▶ if (rotating && SvOK(*rotp)) {
Branch: 2 branches
BranchTrueFalseTotal
if (rotating && SvOK(*rotp)) { 10 26 36
if (rotating && SvOK(*rotp)) { 6 4 10
697 6 SV *old = *rotp;
698 6 SV *d = pcx_call_meth(aTHX_ store, "delete", &old, 1, 1);
699 6 ▶ if (d) SvREFCNT_dec(d);
Branch: 1 branch
BranchTrueFalseTotal
if (d) SvREFCNT_dec(d); 6 0 6
700 }
701 36 (void)hv_delete(stash, PK_SESSION_ROT, PK_SESSION_ROT_LEN, G_DISCARD);
702 36 (void)hv_store(stash, PK_SESSION_SID, PK_SESSION_SID_LEN, newSVsv(id), 0);
703  
704 /* Nothing to tell the client unless the id changed - or the expiry did,
705 * because a cookie that runs out while its entry lives is a logout the
706 * sliding expiry exists to prevent. */
707 36 ▶ if (!fresh && !sliding) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (!fresh && !sliding) return NULL; 5 31 36
if (!fresh && !sliding) return NULL; 4 1 5
708 32 return pk_build_cookie_ex(aTHX_ cname,
709 sv_2mortal(ps_id_seal(aTHX_ id, key, kl, ttl)),
710 cfg, secure);
711 }
712  
713 /* the after-dispatch write-back: add a Set-Cookie to the triplet when the
714 * session changed, or a deletion cookie when it was expired */
715 397 static void ps_writeback(pTHX_ SV *c, SV *resp) {
716 397 AV *av = pcx_av(aTHX_ c);
717 397 HV *cfg = ps_cfg(aTHX_ c);
718 397 SV *st = pcx_get(aTHX_ av, PCX_STASH);
719 HV *stash;
720 SV **sessp, **origp, **expp, **hp;
721 AV *r, *headers;
722 STRLEN nl;
723 const char *cookie_name;
724 397 SV *cname, *store, *setcookie = NULL;
725 int secure;
726 558 ▶ if (!cfg || !st || !SvROK(st)) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!cfg || !st || !SvROK(st)) return; 397 0 397
if (!cfg || !st || !SvROK(st)) return; 289 108 397
if (!cfg || !st || !SvROK(st)) return; 0 289 289
727 289 stash = (HV *)SvRV(st);
728 289 sessp = hv_fetchs(stash, "punk.session", 0);
729 289 ▶ if (!(sessp && *sessp && SvROK(*sessp))) return; /* never accessed */
Branch: 3 branches
BranchTrueFalseTotal
if (!(sessp && *sessp && SvROK(*sessp))) return; /* never accessed */ 282 7 289
if (!(sessp && *sessp && SvROK(*sessp))) return; /* never accessed */ 282 0 282
if (!(sessp && *sessp && SvROK(*sessp))) return; /* never accessed */ 0 282 282
730 282 ▶ if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) return; 282 0 282
if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) return; 0 282 282
731 282 r = (AV *)SvRV(resp);
732 282 hp = av_fetch(r, 1, 0);
733 282 ▶ if (!(hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV)) return;
Branch: 4 branches
BranchTrueFalseTotal
if (!(hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV)) return; 282 0 282
if (!(hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV)) return; 282 0 282
if (!(hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV)) return; 282 0 282
if (!(hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV)) return; 0 282 282
734 282 headers = (AV *)SvRV(*hp);
735 282 cookie_name = ps_cfg_str(aTHX_ cfg, "cookie", "punk.sid", &nl);
736 282 cname = sv_2mortal(newSVpvn(cookie_name, nl));
737 282 expp = hv_fetchs(stash, "punk.session.expire", 0);
738 282 store = ps_cfg_store(aTHX_ cfg);
739 282 secure = ps_secure_default(aTHX_ c);
740 282 ▶ if (expp && *expp && SvTRUE(*expp)) {
Branch: 3 branches
BranchTrueFalseTotal
if (expp && *expp && SvTRUE(*expp)) { 10 272 282
if (expp && *expp && SvTRUE(*expp)) { 10 0 10
if (expp && *expp && SvTRUE(*expp)) { 10 0 10
741 /* Logging out of a stored session is a DELETE, and that is the whole
742 * difference. A signed cookie is good until it expires no matter what
743 * the server thinks, so session_expire could only ever ask the browser
744 * in front of it to forget - never reach a copy somebody had already
745 * taken. With an entry to remove, the stolen cookie is dead on its
746 * next request.
747 *
748 * The id comes from the cookie rather than the stash, because a
749 * logout route usually never touched $c->session at all. */
750 10 ▶ if (store) {
Branch: 1 branch
BranchTrueFalseTotal
if (store) { 5 5 10
751 5 SV *id = ps_req_id(aTHX_ c, cfg);
752 5 ▶ if (id) {
Branch: 1 branch
BranchTrueFalseTotal
if (id) { 5 0 5
753 SV *d;
754 5 sv_2mortal(id);
755 5 d = pcx_call_meth(aTHX_ store, "delete", &id, 1, 1);
756 5 ▶ if (d) SvREFCNT_dec(d);
Branch: 1 branch
BranchTrueFalseTotal
if (d) SvREFCNT_dec(d); 5 0 5
757 }
758 }
759 10 setcookie = pk_build_cookie_ex(aTHX_ cname, &PL_sv_undef, cfg, secure);
760 }
761 272 ▶ else if (store) {
Branch: 1 branch
BranchTrueFalseTotal
else if (store) { 82 190 272
762 82 setcookie = ps_store_writeback(aTHX_ cfg, stash, store, *sessp, cname,
763 secure);
764 82 ▶ if (!setcookie) return; /* stored, or refused, or unchanged */
Branch: 1 branch
BranchTrueFalseTotal
if (!setcookie) return; /* stored, or refused, or unchanged */ 50 32 82
765 }
766 else {
767 190 SV *cur = sv_2mortal(ps_encode(aTHX_ *sessp));
768 STRLEN kl; const char *key;
769 SV *signed_val;
770 190 origp = hv_fetchs(stash, "punk.session.orig", 0);
771 215 ▶ if (origp && *origp && sv_eq(cur, *origp)) return; /* unchanged */
Branch: 3 branches
BranchTrueFalseTotal
if (origp && *origp && sv_eq(cur, *origp)) return; /* unchanged */ 189 1 190
if (origp && *origp && sv_eq(cur, *origp)) return; /* unchanged */ 189 0 189
if (origp && *origp && sv_eq(cur, *origp)) return; /* unchanged */ 79 110 189
772 /* nothing came in and nothing was put in: no cookie to send */
773 111 ▶ if (origp && *origp && !SvCUR(*origp)
Branch: 3 branches
BranchTrueFalseTotal
if (origp && *origp && !SvCUR(*origp) 110 1 111
if (origp && *origp && !SvCUR(*origp) 110 0 110
if (origp && *origp && !SvCUR(*origp) 65 45 110
774 65 ▶ && HvUSEDKEYS((HV *)SvRV(*sessp)) == 0)
Branch: 2 branches
BranchTrueFalseTotal
&& HvUSEDKEYS((HV *)SvRV(*sessp)) == 0) 0 65 65
&& HvUSEDKEYS((HV *)SvRV(*sessp)) == 0) 24 41 65
775 24 return;
776 87 ▶ if (SvCUR(cur) > 4000) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvCUR(cur) > 4000) { 1 86 87
777 /* the write-back is a trapped after-hook, so croaking would vanish;
778 * warn and drop the cookie rather than silently truncate it */
779 1 warn("Punk: session is too large for a signed cookie (%d bytes); "
780 "not saved - a server-side store is needed", (int)SvCUR(cur));
781 1 return;
782 }
783 /* Sign an expiry-stamped copy, not the hash itself: the application
784 * keeps the session it was handed, and the dirty check above stays on
785 * the stripped serialization, so a request that changed nothing still
786 * writes no cookie. The stamp refreshes every time the session is
787 * written, which is what makes `expires` a lifetime rather than a
788 * countdown from first login. */
789 {
790 86 HV *payload = newHVhv((HV *)SvRV(*sessp));
791 86 IV ttl = ps_cfg_iv(aTHX_ cfg, "max_age", 0);
792 SV *prv;
793 86 ▶ if (ttl <= 0) ttl = PK_SESSION_MAX_LIFETIME;
Branch: 1 branch
BranchTrueFalseTotal
if (ttl <= 0) ttl = PK_SESSION_MAX_LIFETIME; 81 5 86
794 86 (void)hv_store(payload, PK_SESSION_EXP, PK_SESSION_EXP_LEN,
795 newSViv((IV)time(NULL) + ttl), 0);
796 86 prv = sv_2mortal(newRV_noinc((SV *)payload));
797 86 cur = sv_2mortal(ps_encode(aTHX_ prv));
798 }
799 86 key = ps_cfg_str(aTHX_ cfg, "secret", "", &kl);
800 86 ▶ if (!kl) {
Branch: 1 branch
BranchTrueFalseTotal
if (!kl) { 0 86 86
801 /* the `session` keyword refuses an empty secret at boot, so this
802 * is only reachable by writing the config by hand. Signing with a
803 * zero-length key is a forgeable cookie, so drop it here too -
804 * same shape as the oversize case, since croaking in a trapped
805 * after-hook would vanish */
806 0 warn("Punk: session has no secret; not saved - a cookie signed "
807 "with an empty key can be forged by anyone");
808 0 return;
809 }
810 86 signed_val = sv_2mortal(pk_session_sign(aTHX_ cur, key, kl));
811 86 setcookie = pk_build_cookie_ex(aTHX_ cname, signed_val, cfg, secure);
812 }
813 128 av_push(headers, newSVpvs("Set-Cookie"));
814 128 av_push(headers, setcookie); /* +1, list takes it */
815 }
816  
817 #endif /* PUNK_SESSION_H */
« xs/ratelimit.xs ↑ Summary include/punk/punk_dbq.h »