include/ptotp/ptotp_plugin.h

filter: Statementstmt 0.0% 0 / 798 Branchbran 0.0% 0 / 564 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 0.0% 0 / 1362 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/Punk/Plugin/TOTP.pm ↑ Summary xs/plugin.xs »
1 /* ptotp_plugin.h - Punk::Plugin::TOTP, the C half.
2 *
3 * Everything the plugin does at registration and per request lives here:
4 * the helpers it installs on the context, the challenge routes, the
5 * step-up guard, and the enrolment QR rendered through QR::Code's C ABI
6 * (qr_abi.h) rather than a Perl call per enrolment. xs/plugin.xs is the
7 * thin XS surface over it - register, state_for and _recovery_digest.
8 *
9 * Included from TOTP.xs AFTER the engine's static helpers (pt_alg_of,
10 * pt_secret_of, pt_pairs ...), which it reuses directly: one dist, one
11 * translation unit, one bootstrap.
12 *
13 * The configuration is an ordinary hash per application class, read at
14 * each use rather than frozen into C integers - state_for hands it back,
15 * and a test may localise a value in it and expect the next request to
16 * see the change.
17 */
18  
19 #ifndef PTOTP_PLUGIN_H
20 #define PTOTP_PLUGIN_H
21  
22 /* the kind recovery rows carry in the token table - fixed, not config:
23 * a configurable kind is a second place the same decision lives */
24 #define PP_RKIND "totp_recovery"
25  
26 /* the secret burned when an account has none: fixed bytes, so
27 * verification costs the same whether 2FA is enabled or not */
28 static const unsigned char PP_DUMMY[] = "punk.totp.dummy.....";
29  
30 /* per-class configuration: class name => { ... } */
31 static HV *PP_STATE = NULL;
32  
33 /* ---- the QR::Code C ABI ---------------------------------------------------
34 * Resolved once, at the first registration - so a box without QR::Code
35 * fails at boot rather than at the first enrolment. svg_styled is a
36 * version-2 member, hence the floor. */
37  
38 #define PP_QR_NEED 2
39  
40 static const qr_abi_t *PP_QR = NULL;
41  
42 0 static void pp_qr_boot(pTHX)
43 {
44 0 UV p = 0;
45 0 dSP;
46  
47 0 ▶ if (PP_QR)
Branch: 1 branch
BranchTrueFalseTotal
if (PP_QR) 0 0 0
48 0 return;
49 0 ENTER; SAVETMPS;
50 0 eval_pv("require QR::Code;", TRUE);
51 0 ▶ PUSHMARK(SP); PUTBACK;
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); PUTBACK; 0 0 0
52 0 ▶ if (call_pv("QR::Code::_abi_ptr", G_SCALAR | G_EVAL) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (call_pv("QR::Code::_abi_ptr", G_SCALAR | G_EVAL) > 0) { 0 0 0
53 0 SPAGAIN;
54 0 p = POPu;
55 0 PUTBACK;
56 }
57 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
58  
59 0 ▶ PP_QR = p ? INT2PTR(const qr_abi_t *, p) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
PP_QR = p ? INT2PTR(const qr_abi_t *, p) : NULL; 0 0 0
60 0 ▶ if (!PP_QR || PP_QR->version < PP_QR_NEED) {
Branch: 2 branches
BranchTrueFalseTotal
if (!PP_QR || PP_QR->version < PP_QR_NEED) { 0 0 0
if (!PP_QR || PP_QR->version < PP_QR_NEED) { 0 0 0
61 0 PP_QR = NULL;
62 0 croak("Punk::Plugin::TOTP: QR::Code with qr_abi version %d or "
63 "newer is required", PP_QR_NEED);
64 }
65 }
66  
67 /* ---- closures: a CV carrying captured SVs ---------------------------------
68 * Slot 0 of the capture is a reference to the configuration hash. */
69  
70 typedef struct { AV *cap; } pp_clos_t;
71  
72 0 static int pp_clos_free(pTHX_ SV *sv, MAGIC *mg)
73 {
74 0 pp_clos_t *c = (pp_clos_t *)mg->mg_ptr;
75 PERL_UNUSED_ARG(sv);
76 0 ▶ if (c) {
Branch: 1 branch
BranchTrueFalseTotal
if (c) { 0 0 0
77 0 ▶ if (c->cap) SvREFCNT_dec((SV *)c->cap);
Branch: 1 branch
BranchTrueFalseTotal
if (c->cap) SvREFCNT_dec((SV *)c->cap); 0 0 0
78 0 Safefree(c);
79 }
80 0 return 0;
81 }
82  
83 static MGVTBL pp_clos_vtbl = { NULL, NULL, NULL, NULL, pp_clos_free,
84 NULL, NULL, NULL };
85  
86 0 static SV *pp_closure(pTHX_ XSUBADDR_t body, HV *cfg)
87 {
88 0 CV *cv = (CV *)newXS(NULL, body, (char *)__FILE__);
89 0 AV *cap = newAV();
90 pp_clos_t *c;
91  
92 0 av_push(cap, newRV_inc((SV *)cfg));
93 0 Newxz(c, 1, pp_clos_t);
94 0 c->cap = cap;
95 0 sv_magicext((SV *)cv, NULL, PERL_MAGIC_ext, &pp_clos_vtbl, (char *)c, 0);
96 0 return newRV_noinc((SV *)cv);
97 }
98  
99 0 static HV *pp_cfg_of(pTHX_ CV *cv)
100 {
101 0 MAGIC *mg = mg_findext((SV *)cv, PERL_MAGIC_ext, &pp_clos_vtbl);
102 0 ▶ AV *cap = mg ? ((pp_clos_t *)mg->mg_ptr)->cap : NULL;
Branch: 1 branch
BranchTrueFalseTotal
AV *cap = mg ? ((pp_clos_t *)mg->mg_ptr)->cap : NULL; 0 0 0
103 0 ▶ SV **e = cap ? av_fetch(cap, 0, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV **e = cap ? av_fetch(cap, 0, 0) : NULL; 0 0 0
104 0 ▶ if (!(e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV))
Branch: 4 branches
BranchTrueFalseTotal
if (!(e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV)) 0 0 0
if (!(e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV)) 0 0 0
if (!(e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV)) 0 0 0
if (!(e && *e && SvROK(*e) && SvTYPE(SvRV(*e)) == SVt_PVHV)) 0 0 0
105 0 croak("Punk::Plugin::TOTP: a closure lost its configuration");
106 0 return (HV *)SvRV(*e);
107 }
108  
109 /* ---- calling back into Perl ----------------------------------------------
110 * Every call is scalar context and hands back a NEW SV (+1) - a copy of
111 * the result, undef when there was none - so a caller owns what it
112 * holds and mortalises it. */
113  
114 /* `threw`, when given, catches a die instead of letting it out: the only
115 * caller that wants this is the attempt counter, which must not turn a
116 * failed sign-in into a 500 on a database missing its columns. */
117 0 static SV *pp_call_common(pTHX_ SV *inv, const char *meth, SV *code,
118 SV **argv, int argc, int *threw)
119 {
120 0 dSP;
121 0 ▶ I32 flags = G_SCALAR | (threw ? G_EVAL : 0);
Branch: 1 branch
BranchTrueFalseTotal
I32 flags = G_SCALAR | (threw ? G_EVAL : 0); 0 0 0
122 int count, i;
123 SV *ret;
124  
125 0 ENTER; SAVETMPS;
126 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
127 0 ▶ EXTEND(SP, argc + 1);
Branch: 2 branches
BranchTrueFalseTotal
EXTEND(SP, argc + 1); 0 0 0
EXTEND(SP, argc + 1); 0 0 0
128 0 ▶ if (inv) PUSHs(inv);
Branch: 1 branch
BranchTrueFalseTotal
if (inv) PUSHs(inv); 0 0 0
129 0 ▶ for (i = 0; i < argc; i++) PUSHs(argv[i]);
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < argc; i++) PUSHs(argv[i]); 0 0 0
130 0 PUTBACK;
131 0 ▶ if (code) count = call_sv(code, flags);
Branch: 1 branch
BranchTrueFalseTotal
if (code) count = call_sv(code, flags); 0 0 0
132 0 ▶ else if (inv) count = call_method(meth, flags);
Branch: 1 branch
BranchTrueFalseTotal
else if (inv) count = call_method(meth, flags); 0 0 0
133 0 else count = call_pv(meth, flags);
134 0 SPAGAIN;
135 0 ▶ if (count > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (count > 0) { 0 0 0
136 0 SV *top = POPs;
137 0 ret = newSVsv(top);
138 } else {
139 0 ret = newSV(0);
140 }
141 0 ▶ if (threw) *threw = SvTRUE(ERRSV) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
if (threw) *threw = SvTRUE(ERRSV) ? 1 : 0; 0 0 0
if (threw) *threw = SvTRUE(ERRSV) ? 1 : 0; 0 0 0
142 0 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 0 0 0
143 0 return ret;
144 }
145  
146 /* $inv->$meth(@argv) */
147 0 static SV *pp_call(pTHX_ SV *inv, const char *meth, SV **argv, int argc)
148 {
149 0 return pp_call_common(aTHX_ inv, meth, NULL, argv, argc, NULL);
150 }
151  
152 /* $code->(@argv) */
153 0 static SV *pp_call_code(pTHX_ SV *code, SV **argv, int argc)
154 {
155 0 return pp_call_common(aTHX_ NULL, NULL, code, argv, argc, NULL);
156 }
157  
158 /* Punk::Auth::_await($c, $v) for a value that may be a future; a plain
159 * value, or a Punk without the seam, passes straight through. */
160 0 static SV *pp_await_ev(pTHX_ SV *c, SV *v, int *threw)
161 {
162 SV *argv[2];
163 0 ▶ if (!v) return newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
if (!v) return newSV(0); 0 0 0
164 0 ▶ if (!SvROK(v) || !get_cv("Punk::Auth::_await", 0))
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(v) || !get_cv("Punk::Auth::_await", 0)) 0 0 0
if (!SvROK(v) || !get_cv("Punk::Auth::_await", 0)) 0 0 0
165 0 return newSVsv(v);
166 0 argv[0] = c;
167 0 argv[1] = v;
168 0 return pp_call_common(aTHX_ NULL, "Punk::Auth::_await", NULL, argv, 2, threw);
169 }
170  
171 0 static SV *pp_await(pTHX_ SV *c, SV *v)
172 {
173 0 return pp_await_ev(aTHX_ c, v, NULL);
174 }
175  
176 0 static int pp_is_hash(SV *sv)
177 {
178 0 ▶ return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV;
Branch: 3 branches
BranchTrueFalseTotal
return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV; 0 0 0
return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV; 0 0 0
return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV; 0 0 0
179 }
180  
181 0 static int pp_is_array(SV *sv)
182 {
183 0 ▶ return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVAV;
Branch: 3 branches
BranchTrueFalseTotal
return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVAV; 0 0 0
return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVAV; 0 0 0
return sv && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVAV; 0 0 0
184 }
185  
186 0 static SV *pp_hget(pTHX_ HV *h, const char *k)
187 {
188 0 SV **e = hv_fetch(h, k, (I32)strlen(k), 0);
189 0 ▶ return (e && *e && SvOK(*e)) ? *e : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (e && *e && SvOK(*e)) ? *e : NULL; 0 0 0
return (e && *e && SvOK(*e)) ? *e : NULL; 0 0 0
return (e && *e && SvOK(*e)) ? *e : NULL; 0 0 0
190 }
191  
192 /* ---- configuration --------------------------------------------------------- */
193  
194 0 static IV pp_cfg_iv(pTHX_ HV *cfg, const char *k, IV dflt)
195 {
196 0 SV *v = pp_hget(aTHX_ cfg, k);
197 0 ▶ return v ? SvIV(v) : dflt;
Branch: 1 branch
BranchTrueFalseTotal
return v ? SvIV(v) : dflt; 0 0 0
198 }
199  
200 /* a cfg value as an SV that is never NULL - the config is validated at
201 * registration, so a missing key is a corrupted state hash */
202 0 static SV *pp_cfg_sv(pTHX_ HV *cfg, const char *k)
203 {
204 0 SV *v = pp_hget(aTHX_ cfg, k);
205 0 ▶ if (!v) croak("Punk::Plugin::TOTP: configuration lost '%s'", k);
Branch: 1 branch
BranchTrueFalseTotal
if (!v) croak("Punk::Plugin::TOTP: configuration lost '%s'", k); 0 0 0
206 0 return v;
207 }
208  
209 /* the column name behind a logical field (secret, counter, enabled,
210 * email) */
211 0 static SV *pp_field(pTHX_ HV *cfg, const char *which)
212 {
213 0 SV *f = pp_hget(aTHX_ cfg, "fields");
214 0 ▶ SV *v = pp_is_hash(f) ? pp_hget(aTHX_ (HV *)SvRV(f), which) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *v = pp_is_hash(f) ? pp_hget(aTHX_ (HV *)SvRV(f), which) : NULL; 0 0 0
215 0 ▶ if (!v) croak("Punk::Plugin::TOTP: configuration lost field '%s'", which);
Branch: 1 branch
BranchTrueFalseTotal
if (!v) croak("Punk::Plugin::TOTP: configuration lost field '%s'", which); 0 0 0
216 0 return v;
217 }
218  
219 0 static SV *pp_user_get(pTHX_ HV *cfg, HV *user, const char *which)
220 {
221 STRLEN nl;
222 0 const char *np = SvPV_const(pp_field(aTHX_ cfg, which), nl);
223 0 SV **e = hv_fetch(user, np, (I32)nl, 0);
224 0 ▶ return (e && *e && SvOK(*e)) ? *e : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (e && *e && SvOK(*e)) ? *e : NULL; 0 0 0
return (e && *e && SvOK(*e)) ? *e : NULL; 0 0 0
return (e && *e && SvOK(*e)) ? *e : NULL; 0 0 0
225 }
226  
227 /* $c->model($cfg{$which}), mortal */
228 0 static SV *pp_model(pTHX_ HV *cfg, SV *c, const char *which)
229 {
230 0 SV *name = pp_cfg_sv(aTHX_ cfg, which);
231 0 return sv_2mortal(pp_call(aTHX_ c, "model", &name, 1));
232 }
233  
234 /* ---- the session ---------------------------------------------------------- */
235  
236 0 static HV *pp_session(pTHX_ SV *c)
237 {
238 0 SV *s = sv_2mortal(pp_call(aTHX_ c, "session", NULL, 0));
239 0 ▶ if (!pp_is_hash(s))
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_hash(s)) 0 0 0
240 0 croak("Punk::Plugin::TOTP needs the session keyword");
241 0 return (HV *)SvRV(s);
242 }
243  
244 /* the pending marker while it is live; an expired one is removed, so a
245 * stale half-state cannot be resumed */
246 0 static HV *pp_pending(pTHX_ SV *c)
247 {
248 0 HV *s = pp_session(aTHX_ c);
249 0 SV **e = hv_fetchs(s, "totp_pending", 0);
250 SV *exp;
251 0 ▶ if (!(e && *e && pp_is_hash(*e)))
Branch: 3 branches
BranchTrueFalseTotal
if (!(e && *e && pp_is_hash(*e))) 0 0 0
if (!(e && *e && pp_is_hash(*e))) 0 0 0
if (!(e && *e && pp_is_hash(*e))) 0 0 0
252 0 return NULL;
253 0 exp = pp_hget(aTHX_ (HV *)SvRV(*e), "exp");
254 0 ▶ if (exp && (NV)time(NULL) < SvNV(exp))
Branch: 2 branches
BranchTrueFalseTotal
if (exp && (NV)time(NULL) < SvNV(exp)) 0 0 0
if (exp && (NV)time(NULL) < SvNV(exp)) 0 0 0
255 0 return (HV *)SvRV(*e);
256 0 (void)hv_delete(s, "totp_pending", 12, G_DISCARD);
257 0 return NULL;
258 }
259  
260 0 static void pp_set_pending(pTHX_ HV *cfg, HV *s, SV *id, SV *to)
261 {
262 0 HV *p = newHV();
263 0 (void)hv_stores(p, "id", newSVsv(id));
264 0 (void)hv_stores(p, "exp", newSViv((IV)time(NULL)
265 + pp_cfg_iv(aTHX_ cfg, "pending_ttl", 300)));
266 0 ▶ (void)hv_stores(p, "to", (to && SvOK(to)) ? newSVsv(to) : newSVpvs("/"));
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_stores(p, "to", (to && SvOK(to)) ? newSVsv(to) : newSVpvs("/")); 0 0 0
(void)hv_stores(p, "to", (to && SvOK(to)) ? newSVsv(to) : newSVpvs("/")); 0 0 0
267 0 (void)hv_stores(s, "totp_pending", newRV_noinc((SV *)p));
268 0 }
269  
270 /* ---- the attempt counter ---------------------------------------------------
271 *
272 * On the user row, and NOT in the session, which is the whole point: a Punk
273 * session without a store is a signed cookie and nothing more, so a client
274 * that keeps a copy from before its failures and presents it again gets its
275 * counter back and the limit never fires. Counting in state the client holds
276 * is counting in state the client chooses.
277 *
278 * Per account rather than per pending marker for the same reason one level
279 * up: re-running the password step mints a fresh marker, so a per-marker
280 * count never bounded guessing of the second factor either - it only made an
281 * attacker repeat a step they had already passed.
282 *
283 * The window makes it self-healing. A permanent lock would hand anyone who
284 * knows a password a way to keep the account's owner out for good, which is
285 * a worse bargain than the guessing it prevents. */
286  
287 0 static IV pp_user_iv(pTHX_ HV *cfg, HV *uh, const char *which)
288 {
289 0 SV *v = pp_user_get(aTHX_ cfg, uh, which);
290 0 ▶ return v ? SvIV(v) : 0;
Branch: 1 branch
BranchTrueFalseTotal
return v ? SvIV(v) : 0; 0 0 0
291 }
292  
293 /* the failures that still count: a window that has lapsed counts as none */
294 0 static IV pp_fail_count(pTHX_ HV *cfg, HV *uh)
295 {
296 0 IV n = pp_user_iv(aTHX_ cfg, uh, "failed");
297 0 IV at = pp_user_iv(aTHX_ cfg, uh, "failed_at");
298 0 IV w = pp_cfg_iv(aTHX_ cfg, "attempt_window", 900);
299 0 ▶ if (n <= 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) return 0; 0 0 0
300 0 ▶ if (at && (IV)time(NULL) - at >= w) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (at && (IV)time(NULL) - at >= w) return 0; 0 0 0
if (at && (IV)time(NULL) - at >= w) return 0; 0 0 0
301 0 return n;
302 }
303  
304 /* said once per process: a limit that is silently not running is the bug
305 * this release exists to fix, so it does not get to be quiet */
306 0 static void pp_counter_broken(pTHX)
307 {
308 static int said = 0;
309 0 ▶ if (said) return;
Branch: 1 branch
BranchTrueFalseTotal
if (said) return; 0 0 0
310 0 said = 1;
311 0 warn("Punk::Plugin::TOTP: the second-factor attempt count could not be "
312 "written to the user row - the user table needs the totp_failed and "
313 "totp_failed_at columns (or whatever `fields` names them). Every "
314 "failed attempt un-answers the first factor until it does.");
315 }
316  
317 /* write columns to the user row, mirroring them into the hash the caller
318 * holds; 0 when the write did not land */
319 0 static int pp_user_write(pTHX_ HV *cfg, SV *c, HV *uh,
320 const char *const *which, IV *vals, int n)
321 {
322 0 SV *model = pp_model(aTHX_ cfg, c, "model");
323 0 HV *data = newHV();
324 0 SV *dref, *ret, *id = pp_hget(aTHX_ uh, "id");
325 0 int i, threw = 0;
326  
327 0 ▶ (void)hv_stores(data, "id", id ? newSVsv(id) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(data, "id", id ? newSVsv(id) : newSV(0)); 0 0 0
328 0 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 0 0 0
329 STRLEN fl;
330 0 const char *fp = SvPV_const(pp_field(aTHX_ cfg, which[i]), fl);
331 0 (void)hv_store(data, fp, (I32)fl, newSViv(vals[i]), 0);
332 }
333 0 dref = sv_2mortal(newRV_noinc((SV *)data));
334 0 ret = pp_call_common(aTHX_ model, "update", NULL, &dref, 1, &threw);
335 0 ▶ if (!threw && SvROK(ret))
Branch: 2 branches
BranchTrueFalseTotal
if (!threw && SvROK(ret)) 0 0 0
if (!threw && SvROK(ret)) 0 0 0
336 0 SvREFCNT_dec(pp_await_ev(aTHX_ c, ret, &threw));
337 0 SvREFCNT_dec(ret);
338 0 ▶ if (threw) {
Branch: 1 branch
BranchTrueFalseTotal
if (threw) { 0 0 0
339 0 pp_counter_broken(aTHX);
340 0 return 0;
341 }
342 0 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 0 0 0
343 STRLEN fl;
344 0 const char *fp = SvPV_const(pp_field(aTHX_ cfg, which[i]), fl);
345 0 (void)hv_store(uh, fp, (I32)fl, newSViv(vals[i]), 0);
346 }
347 0 return 1;
348 }
349  
350 static const char *const PP_FAILF[2] = { "failed", "failed_at" };
351  
352 0 static int pp_fail_bump(pTHX_ HV *cfg, SV *c, HV *uh, IV n)
353 {
354 IV vals[2];
355 0 vals[0] = n + 1;
356 0 vals[1] = (IV)time(NULL);
357 0 return pp_user_write(aTHX_ cfg, c, uh, PP_FAILF, vals, 2);
358 }
359  
360 0 static void pp_fail_clear(pTHX_ HV *cfg, SV *c, HV *uh)
361 {
362 IV vals[2];
363 /* nothing to clear: the pass costs no write on the ordinary path */
364 0 ▶ if (!pp_user_iv(aTHX_ cfg, uh, "failed")
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_user_iv(aTHX_ cfg, uh, "failed") 0 0 0
365 0 ▶ && !pp_user_iv(aTHX_ cfg, uh, "failed_at"))
Branch: 1 branch
BranchTrueFalseTotal
&& !pp_user_iv(aTHX_ cfg, uh, "failed_at")) 0 0 0
366 0 return;
367 0 vals[0] = 0;
368 0 vals[1] = 0;
369 0 (void)pp_user_write(aTHX_ cfg, c, uh, PP_FAILF, vals, 2);
370 }
371  
372 0 static SV *pp_redirect(pTHX_ SV *c, SV *where)
373 {
374 0 return pp_call(aTHX_ c, "redirect", &where, 1);
375 }
376  
377 /* ---- the recovery digest --------------------------------------------------
378 * Case folded and grouping stripped before digesting: people type what
379 * the drawer's paper shows, in whatever case their keyboard chose.
380 * Lowercase sha256 hex - pwd_token_digest's wire form - so the rows are
381 * interchangeable with the auth battery's own tokens. */
382  
383 0 static SV *pp_recovery_digest(pTHX_ SV *code)
384 {
385 static const char hexd[] = "0123456789abcdef";
386 0 STRLEN n, i, j = 0;
387 0 const char *p = SvPV_const(code, n);
388 0 const frh_algo_t *a = PT_FRH->algo_by_id(PT_ALGS[1].frh_id);
389 unsigned char sum[64];
390 char hex[129];
391 char *buf;
392  
393 0 Newx(buf, n + 1, char);
394 0 SAVEFREEPV(buf);
395 0 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 0 0 0
396 0 unsigned char ch = (unsigned char)p[i];
397 0 ▶ if (isSPACE(ch) || ch == '-') continue;
Branch: 2 branches
BranchTrueFalseTotal
if (isSPACE(ch) || ch == '-') continue; 0 0 0
if (isSPACE(ch) || ch == '-') continue; 0 0 0
398 0 ▶ buf[j++] = (char)toUPPER(ch);
Branch: 1 branch
BranchTrueFalseTotal
buf[j++] = (char)toUPPER(ch); 0 0 0
399 }
400 0 ▶ if (!a || a->digest_size > sizeof sum
Branch: 2 branches
BranchTrueFalseTotal
if (!a || a->digest_size > sizeof sum 0 0 0
if (!a || a->digest_size > sizeof sum 0 0 0
401 0 ▶ || PT_FRH->digest(a->id, (const unsigned char *)buf, j, sum) != 0)
Branch: 1 branch
BranchTrueFalseTotal
|| PT_FRH->digest(a->id, (const unsigned char *)buf, j, sum) != 0) 0 0 0
402 0 croak("Punk::Plugin::TOTP: sha256 failed");
403 0 ▶ for (i = 0; i < a->digest_size; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < a->digest_size; i++) { 0 0 0
404 0 hex[2 * i] = hexd[sum[i] >> 4];
405 0 hex[2 * i + 1] = hexd[sum[i] & 15];
406 }
407 0 return newSVpvn(hex, a->digest_size * 2);
408 }
409  
410 /* ---- the enrolment QR, through qr_abi -------------------------------------
411 * The same option surface QR::Code->svg takes - ecc, version, quiet, logo,
412 * style - mapped onto the ABI's structs, with H as the default level: an
413 * enrolment QR is scanned once, from a screen, by every phone the user
414 * will ever own, so it gets maximum margin. */
415  
416 0 static int pp_ecc_of(pTHX_ SV *sv, int dflt)
417 {
418 STRLEN n;
419 const char *p;
420 0 ▶ if (!sv) return dflt;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return dflt; 0 0 0
421 0 p = SvPV_const(sv, n);
422 0 ▶ if (n == 1)
Branch: 1 branch
BranchTrueFalseTotal
if (n == 1) 0 0 0
423 0 switch (*p) {
424 0 case 'L': case 'l': return QR_ABI_ECC_L;
425 0 case 'M': case 'm': return QR_ABI_ECC_M;
426 0 case 'Q': case 'q': return QR_ABI_ECC_Q;
427 0 case 'H': case 'h': return QR_ABI_ECC_H;
428 }
429 0 croak("ecc must be L, M, Q or H, not '%.*s'", (int)n, p);
430 return -1;
431 }
432  
433 0 static int pp_range_of(pTHX_ SV *sv, const char *what, IV lo, IV hi, int dflt)
434 {
435 IV v;
436 0 ▶ if (!sv) return dflt;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return dflt; 0 0 0
437 0 v = SvIV(sv);
438 0 ▶ if (v < lo || v > hi)
Branch: 2 branches
BranchTrueFalseTotal
if (v < lo || v > hi) 0 0 0
if (v < lo || v > hi) 0 0 0
439 0 croak("%s must be %" IVdf " to %" IVdf ", not %" IVdf, what, lo, hi, v);
440 0 return (int)v;
441 }
442  
443 0 static void pp_color_copy(pTHX_ SV *sv, char *dst, size_t dstlen)
444 {
445 STRLEN n;
446 0 const char *p = SvPV_const(sv, n);
447 0 ▶ if (n >= dstlen) n = dstlen - 1;
Branch: 1 branch
BranchTrueFalseTotal
if (n >= dstlen) n = dstlen - 1; 0 0 0
448 0 memcpy(dst, p, n);
449 0 dst[n] = '\0';
450 0 }
451  
452 0 static SV *pp_slurp(pTHX_ const char *path)
453 {
454 0 PerlIO *f = PerlIO_open(path, "rb");
455 SV *out;
456 char buf[65536];
457 SSize_t n;
458 0 ▶ if (!f) croak("logo file '%s': %s", path, Strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
if (!f) croak("logo file '%s': %s", path, Strerror(errno)); 0 0 0
459 0 out = sv_2mortal(newSVpvs(""));
460 0 ▶ while ((n = PerlIO_read(f, buf, sizeof buf)) > 0)
Branch: 1 branch
BranchTrueFalseTotal
while ((n = PerlIO_read(f, buf, sizeof buf)) > 0) 0 0 0
461 0 sv_catpvn(out, buf, (STRLEN)n);
462 0 PerlIO_close(f);
463 0 return out;
464 }
465  
466 /* Fills *lg. The bytes it borrows belong to SVs that live to the end of
467 * the XSUB, which outlives the render. */
468 0 static void pp_logo_of(pTHX_ SV *sv, qr_abi_logo_t *lg)
469 {
470 static const char *const ok[] =
471 { "text", "svg", "image", "file", "scale", "em" };
472 HV *h;
473 SV *text, *markup, *image, *file, *bytes;
474 STRLEN n;
475  
476 0 memset(lg, 0, sizeof *lg);
477 0 lg->size = sizeof *lg;
478  
479 0 ▶ if (!SvROK(sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvROK(sv)) { 0 0 0
480 0 lg->text = SvPV_const(sv, n);
481 0 lg->text_len = n;
482 0 ▶ if (!n) croak("logo text is empty");
Branch: 1 branch
BranchTrueFalseTotal
if (!n) croak("logo text is empty"); 0 0 0
483 0 lg->kind = QR_ABI_LOGO_TEXT;
484 0 return;
485 }
486 0 ▶ if (!pp_is_hash(sv))
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_hash(sv)) 0 0 0
487 0 croak("logo must be a string or a hashref");
488 0 h = (HV *)SvRV(sv);
489 0 pt_check_keys(aTHX_ "logo", h, ok, 6);
490  
491 0 text = pp_hget(aTHX_ h, "text");
492 0 markup = pp_hget(aTHX_ h, "svg");
493 0 image = pp_hget(aTHX_ h, "image");
494 0 file = pp_hget(aTHX_ h, "file");
495 0 ▶ if (!!text + !!markup + !!image + !!file != 1)
Branch: 1 branch
BranchTrueFalseTotal
if (!!text + !!markup + !!image + !!file != 1) 0 0 0
496 0 croak("logo needs exactly one of text, svg, image or file");
497 {
498 SV *v;
499 0 ▶ if ((v = pp_hget(aTHX_ h, "scale"))) lg->scale = SvNV(v);
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "scale"))) lg->scale = SvNV(v); 0 0 0
500 0 ▶ if ((v = pp_hget(aTHX_ h, "em"))) lg->em = SvNV(v);
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "em"))) lg->em = SvNV(v); 0 0 0
501 }
502 0 ▶ if (text) {
Branch: 1 branch
BranchTrueFalseTotal
if (text) { 0 0 0
503 0 lg->text = SvPV_const(text, n);
504 0 lg->text_len = n;
505 0 ▶ if (!n) croak("logo text is empty");
Branch: 1 branch
BranchTrueFalseTotal
if (!n) croak("logo text is empty"); 0 0 0
506 0 lg->kind = QR_ABI_LOGO_TEXT;
507 0 return;
508 }
509 0 ▶ if (markup) {
Branch: 1 branch
BranchTrueFalseTotal
if (markup) { 0 0 0
510 0 lg->markup = SvPV_const(markup, n);
511 0 lg->markup_len = n;
512 0 lg->kind = QR_ABI_LOGO_SVG;
513 0 return;
514 }
515  
516 /* image bytes, or a file holding any of the three formats; the
517 * format comes from the bytes, never from the name */
518 0 ▶ bytes = image ? image : pp_slurp(aTHX_ SvPV_nolen_const(file));
Branch: 1 branch
BranchTrueFalseTotal
bytes = image ? image : pp_slurp(aTHX_ SvPV_nolen_const(file)); 0 0 0
519 {
520 0 const unsigned char *p = (const unsigned char *)SvPVbyte(bytes, n);
521 0 STRLEN i = 0;
522 0 ▶ if (n >= 8 && memcmp(p, "\x89PNG\r\n\x1a\n", 8) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (n >= 8 && memcmp(p, "\x89PNG\r\n\x1a\n", 8) == 0) { 0 0 0
if (n >= 8 && memcmp(p, "\x89PNG\r\n\x1a\n", 8) == 0) { 0 0 0
523 0 lg->kind = QR_ABI_LOGO_IMAGE; lg->img = p; lg->img_len = n;
524 0 lg->img_fmt = QR_ABI_IMG_PNG;
525 0 return;
526 }
527 0 ▶ if (n >= 3 && p[0] == 0xFF && p[1] == 0xD8 && p[2] == 0xFF) {
Branch: 4 branches
BranchTrueFalseTotal
if (n >= 3 && p[0] == 0xFF && p[1] == 0xD8 && p[2] == 0xFF) { 0 0 0
if (n >= 3 && p[0] == 0xFF && p[1] == 0xD8 && p[2] == 0xFF) { 0 0 0
if (n >= 3 && p[0] == 0xFF && p[1] == 0xD8 && p[2] == 0xFF) { 0 0 0
if (n >= 3 && p[0] == 0xFF && p[1] == 0xD8 && p[2] == 0xFF) { 0 0 0
528 0 lg->kind = QR_ABI_LOGO_IMAGE; lg->img = p; lg->img_len = n;
529 0 lg->img_fmt = QR_ABI_IMG_JPEG;
530 0 return;
531 }
532 0 ▶ while (i < n && isSPACE(p[i])) i++;
Branch: 2 branches
BranchTrueFalseTotal
while (i < n && isSPACE(p[i])) i++; 0 0 0
while (i < n && isSPACE(p[i])) i++; 0 0 0
533 0 ▶ if (i < n && p[i] == '<') {
Branch: 2 branches
BranchTrueFalseTotal
if (i < n && p[i] == '<') { 0 0 0
if (i < n && p[i] == '<') { 0 0 0
534 0 lg->kind = QR_ABI_LOGO_SVG;
535 0 lg->markup = (const char *)p;
536 0 lg->markup_len = n;
537 0 return;
538 }
539 0 croak("logo image must be PNG, JPEG or SVG");
540 }
541 }
542  
543 0 static void pp_style_of(pTHX_ SV *sv, qr_abi_style_t *st)
544 {
545 static const char *const ok[] =
546 { "shape", "radius", "finder", "dark", "light", "finder_dark",
547 "gradient" };
548 HV *h;
549 SV *v;
550  
551 0 memset(st, 0, sizeof *st);
552 0 st->size = sizeof *st;
553 0 ▶ if (!pp_is_hash(sv)) croak("style must be a hashref");
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_hash(sv)) croak("style must be a hashref"); 0 0 0
554 0 h = (HV *)SvRV(sv);
555 0 pt_check_keys(aTHX_ "style", h, ok, 7);
556  
557 0 ▶ if ((v = pp_hget(aTHX_ h, "shape"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "shape"))) { 0 0 0
558 0 const char *p = SvPV_nolen_const(v);
559 0 ▶ if (strEQ(p, "square")) st->shape = QR_ABI_SHAPE_SQUARE;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(p, "square")) st->shape = QR_ABI_SHAPE_SQUARE; 0 0 0
560 0 ▶ else if (strEQ(p, "rounded")) st->shape = QR_ABI_SHAPE_ROUNDED;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(p, "rounded")) st->shape = QR_ABI_SHAPE_ROUNDED; 0 0 0
561 0 ▶ else if (strEQ(p, "dot")) st->shape = QR_ABI_SHAPE_DOT;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(p, "dot")) st->shape = QR_ABI_SHAPE_DOT; 0 0 0
562 0 else croak("style shape must be square, rounded or dot, not '%s'", p);
563 }
564 0 ▶ if ((v = pp_hget(aTHX_ h, "finder"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "finder"))) { 0 0 0
565 0 const char *p = SvPV_nolen_const(v);
566 0 ▶ if (strEQ(p, "square")) st->finder = QR_ABI_FINDER_SQUARE;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(p, "square")) st->finder = QR_ABI_FINDER_SQUARE; 0 0 0
567 0 ▶ else if (strEQ(p, "rounded")) st->finder = QR_ABI_FINDER_ROUNDED;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(p, "rounded")) st->finder = QR_ABI_FINDER_ROUNDED; 0 0 0
568 0 ▶ else if (strEQ(p, "circle")) st->finder = QR_ABI_FINDER_CIRCLE;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(p, "circle")) st->finder = QR_ABI_FINDER_CIRCLE; 0 0 0
569 0 else croak("style finder must be square, rounded or circle, "
570 "not '%s'", p);
571 }
572 0 ▶ if ((v = pp_hget(aTHX_ h, "radius"))) st->radius = SvNV(v);
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "radius"))) st->radius = SvNV(v); 0 0 0
573 0 ▶ if ((v = pp_hget(aTHX_ h, "dark"))) pp_color_copy(aTHX_ v, st->dark, sizeof st->dark);
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "dark"))) pp_color_copy(aTHX_ v, st->dark, sizeof st->dark); 0 0 0
574 0 ▶ if ((v = pp_hget(aTHX_ h, "light"))) pp_color_copy(aTHX_ v, st->light, sizeof st->light);
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "light"))) pp_color_copy(aTHX_ v, st->light, sizeof st->light); 0 0 0
575 0 ▶ if ((v = pp_hget(aTHX_ h, "finder_dark"))) pp_color_copy(aTHX_ v, st->finder_dark, sizeof st->finder_dark);
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "finder_dark"))) pp_color_copy(aTHX_ v, st->finder_dark, sizeof st->finder_dark); 0 0 0
576  
577 0 ▶ if ((v = pp_hget(aTHX_ h, "gradient"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ h, "gradient"))) { 0 0 0
578 static const char *const gok[] = { "type", "angle", "stops" };
579 HV *g;
580 SV *t, *stops;
581 0 ▶ if (!pp_is_hash(v)) croak("style gradient must be a hashref");
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_hash(v)) croak("style gradient must be a hashref"); 0 0 0
582 0 g = (HV *)SvRV(v);
583 0 pt_check_keys(aTHX_ "gradient", g, gok, 3);
584 0 ▶ if ((t = pp_hget(aTHX_ g, "type"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((t = pp_hget(aTHX_ g, "type"))) { 0 0 0
585 0 const char *p = SvPV_nolen_const(t);
586 0 ▶ if (strEQ(p, "none")) st->grad_type = QR_ABI_GRAD_NONE;
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(p, "none")) st->grad_type = QR_ABI_GRAD_NONE; 0 0 0
587 0 ▶ else if (strEQ(p, "linear")) st->grad_type = QR_ABI_GRAD_LINEAR;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(p, "linear")) st->grad_type = QR_ABI_GRAD_LINEAR; 0 0 0
588 0 ▶ else if (strEQ(p, "radial")) st->grad_type = QR_ABI_GRAD_RADIAL;
Branch: 1 branch
BranchTrueFalseTotal
else if (strEQ(p, "radial")) st->grad_type = QR_ABI_GRAD_RADIAL; 0 0 0
589 0 else croak("gradient type must be none, linear or radial, "
590 "not '%s'", p);
591 }
592 0 ▶ if ((t = pp_hget(aTHX_ g, "angle"))) st->grad_angle = SvNV(t);
Branch: 1 branch
BranchTrueFalseTotal
if ((t = pp_hget(aTHX_ g, "angle"))) st->grad_angle = SvNV(t); 0 0 0
593 0 ▶ if ((stops = pp_hget(aTHX_ g, "stops"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((stops = pp_hget(aTHX_ g, "stops"))) { 0 0 0
594 AV *av;
595 SSize_t i, n;
596 0 ▶ if (!pp_is_array(stops)) croak("gradient stops must be an arrayref");
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_array(stops)) croak("gradient stops must be an arrayref"); 0 0 0
597 0 av = (AV *)SvRV(stops);
598 0 n = av_len(av) + 1;
599 0 ▶ if (n > QR_ABI_MAX_STOPS)
Branch: 1 branch
BranchTrueFalseTotal
if (n > QR_ABI_MAX_STOPS) 0 0 0
600 0 croak("gradient takes at most %d stops", QR_ABI_MAX_STOPS);
601 0 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 0 0 0
602 0 SV **e = av_fetch(av, i, 0);
603 0 ▶ if (e && *e && SvOK(*e))
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) 0 0 0
if (e && *e && SvOK(*e)) 0 0 0
if (e && *e && SvOK(*e)) 0 0 0
604 0 pp_color_copy(aTHX_ *e, st->stops[i], sizeof st->stops[i]);
605 }
606 0 st->nstops = (int)n;
607 }
608 }
609 0 }
610  
611 /* the otpauth:// URI as an SVG document (+1) */
612 0 static SV *pp_render_qr(pTHX_ SV *uri, HV *opt)
613 {
614 static const char *const ok[] = { "ecc", "version", "quiet", "logo", "style" };
615 qr_abi_style_t st;
616 qr_abi_logo_t lg;
617 SV *osv;
618 0 int ecc, version, quiet, has_logo = 0, has_style = 0;
619 STRLEN n;
620 const unsigned char *data;
621 char err[256];
622 char *out;
623 SV *svg;
624  
625 0 pp_qr_boot(aTHX);
626 0 pt_check_keys(aTHX_ "totp_qr", opt, ok, 5);
627  
628 0 ▶ if ((osv = pp_hget(aTHX_ opt, "logo"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((osv = pp_hget(aTHX_ opt, "logo"))) { 0 0 0
629 /* a logo is erasures, and erasures need budget: Q or H only */
630 0 ecc = pp_ecc_of(aTHX_ pp_hget(aTHX_ opt, "ecc"), QR_ABI_ECC_H);
631 0 ▶ if (ecc < QR_ABI_ECC_Q)
Branch: 1 branch
BranchTrueFalseTotal
if (ecc < QR_ABI_ECC_Q) 0 0 0
632 0 croak("a centre logo needs ECC level Q or H");
633 0 pp_logo_of(aTHX_ osv, &lg);
634 0 has_logo = 1;
635 } else {
636 0 ecc = pp_ecc_of(aTHX_ pp_hget(aTHX_ opt, "ecc"), QR_ABI_ECC_H);
637 }
638 0 ▶ if ((osv = pp_hget(aTHX_ opt, "style"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((osv = pp_hget(aTHX_ opt, "style"))) { 0 0 0
639 0 pp_style_of(aTHX_ osv, &st);
640 0 has_style = 1;
641 }
642 0 version = pp_range_of(aTHX_ pp_hget(aTHX_ opt, "version"), "version", 1, 15, 0);
643 0 quiet = pp_range_of(aTHX_ pp_hget(aTHX_ opt, "quiet"), "quiet", 0, 16, 4);
644  
645 0 data = (const unsigned char *)SvPVbyte(uri, n);
646 0 err[0] = '\0';
647 0 ▶ out = PP_QR->svg_styled(data, (int)n, ecc, version, quiet,
Branch: 2 branches
BranchTrueFalseTotal
out = PP_QR->svg_styled(data, (int)n, ecc, version, quiet, 0 0 0
out = PP_QR->svg_styled(data, (int)n, ecc, version, quiet, 0 0 0
648 has_style ? &st : NULL,
649 has_logo ? &lg : NULL,
650 NULL, err, sizeof err);
651 0 ▶ if (!out)
Branch: 1 branch
BranchTrueFalseTotal
if (!out) 0 0 0
652 0 ▶ croak("totp_qr: %s", err[0] ? err : "QR::Code could not render the symbol");
Branch: 1 branch
BranchTrueFalseTotal
croak("totp_qr: %s", err[0] ? err : "QR::Code could not render the symbol"); 0 0 0
653 0 svg = newSVpv(out, 0);
654 0 PP_QR->free_fn(out);
655 0 return svg;
656 }
657  
658 /* ---- the helpers ------------------------------------------------------------
659 * Each is an XS closure over the configuration, installed on the context
660 * through $app->helper. ST(0) is the context. */
661  
662 /* $c->totp_secret */
663 XS_INTERNAL(pp_h_secret);
664 0 XS_INTERNAL(pp_h_secret)
665 {
666 0 dXSARGS;
667 0 HV *cfg = pp_cfg_of(aTHX_ cv);
668 0 const pt_alg_t *alg = pt_alg_of(aTHX_ pp_hget(aTHX_ cfg, "algorithm"));
669 unsigned char raw[64];
670 char b32[((sizeof raw + 4) / 5) * 8 + 1];
671 PERL_UNUSED_VAR(items);
672  
673 0 ▶ if (ptotp_random_bytes(raw, alg->secret_bytes) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (ptotp_random_bytes(raw, alg->secret_bytes) != 0) 0 0 0
674 0 croak("Punk::TOTP: the entropy source failed; refusing to degrade");
675 0 ptotp_b32_encode(b32, raw, alg->secret_bytes);
676 0 ST(0) = sv_2mortal(newSVpv(b32, 0));
677 0 XSRETURN(1);
678 }
679  
680 /* the otpauth:// URI (+1): issuer and parameters from config, account
681 * from %opt or the signed-in user's email */
682 0 static SV *pp_uri(pTHX_ HV *cfg, SV *c, SV *secret, HV *opt)
683 {
684 0 AV *args = (AV *)sv_2mortal((SV *)newAV());
685 0 SV *account = NULL;
686 SV *v;
687 0 SV *klass = sv_2mortal(newSVpvs("Punk::TOTP"));
688 HE *he;
689  
690 0 ▶ if ((v = pp_hget(aTHX_ opt, "account"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ opt, "account"))) { 0 0 0
691 0 account = sv_2mortal(newSVsv(v));
692 0 (void)hv_delete(opt, "account", 7, G_DISCARD);
693 }
694 0 ▶ if (!account) {
Branch: 1 branch
BranchTrueFalseTotal
if (!account) { 0 0 0
695 0 SV *user = sv_2mortal(pp_call(aTHX_ c, "current_user", NULL, 0));
696 0 SV *em = pp_is_hash(user)
697 0 ▶ ? pp_user_get(aTHX_ cfg, (HV *)SvRV(user), "email") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? pp_user_get(aTHX_ cfg, (HV *)SvRV(user), "email") : NULL; 0 0 0
698 0 ▶ if (em) account = sv_2mortal(newSVsv(em));
Branch: 1 branch
BranchTrueFalseTotal
if (em) account = sv_2mortal(newSVsv(em)); 0 0 0
699 }
700 0 ▶ if (!account)
Branch: 1 branch
BranchTrueFalseTotal
if (!account) 0 0 0
701 0 croak("totp_uri needs an account (or a signed-in user with an email)");
702  
703 0 av_push(args, newSVsv(secret));
704 0 av_push(args, newSVpvs("issuer")); av_push(args, newSVsv(pp_cfg_sv(aTHX_ cfg, "issuer")));
705 0 av_push(args, newSVpvs("account")); av_push(args, newSVsv(account));
706 0 av_push(args, newSVpvs("algorithm")); av_push(args, newSVsv(pp_cfg_sv(aTHX_ cfg, "algorithm")));
707 0 av_push(args, newSVpvs("digits")); av_push(args, newSVsv(pp_cfg_sv(aTHX_ cfg, "digits")));
708 0 av_push(args, newSVpvs("period")); av_push(args, newSVsv(pp_cfg_sv(aTHX_ cfg, "period")));
709 0 hv_iterinit(opt);
710 0 ▶ while ((he = hv_iternext(opt))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(opt))) { 0 0 0
711 0 av_push(args, newSVsv(hv_iterkeysv(he)));
712 0 av_push(args, newSVsv(hv_iterval(opt, he)));
713 }
714 0 return pp_call(aTHX_ klass, "uri", AvARRAY(args), (int)(av_len(args) + 1));
715 }
716  
717 /* $c->totp_uri($secret, %opt) */
718 XS_INTERNAL(pp_h_uri);
719 0 XS_INTERNAL(pp_h_uri)
720 {
721 0 dXSARGS;
722 0 HV *cfg = pp_cfg_of(aTHX_ cv);
723 HV *opt;
724 0 ▶ if (items < 2) croak("totp_uri takes a secret");
Branch: 1 branch
BranchTrueFalseTotal
if (items < 2) croak("totp_uri takes a secret"); 0 0 0
725 0 opt = pt_pairs(aTHX_ "totp_uri", &ST(0), 2, items);
726 0 ST(0) = sv_2mortal(pp_uri(aTHX_ cfg, ST(0), ST(1), opt));
727 0 XSRETURN(1);
728 }
729  
730 /* $c->totp_qr($secret, %opt) */
731 XS_INTERNAL(pp_h_qr);
732 0 XS_INTERNAL(pp_h_qr)
733 {
734 0 dXSARGS;
735 0 HV *cfg = pp_cfg_of(aTHX_ cv);
736 HV *opt, *uri_opt;
737 SV *v, *uri;
738 0 ▶ if (items < 2) croak("totp_qr takes a secret");
Branch: 1 branch
BranchTrueFalseTotal
if (items < 2) croak("totp_qr takes a secret"); 0 0 0
739 0 opt = pt_pairs(aTHX_ "totp_qr", &ST(0), 2, items);
740 0 uri_opt = (HV *)sv_2mortal((SV *)newHV());
741 0 ▶ if ((v = pp_hget(aTHX_ opt, "account"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ opt, "account"))) { 0 0 0
742 0 (void)hv_stores(uri_opt, "account", newSVsv(v));
743 0 (void)hv_delete(opt, "account", 7, G_DISCARD);
744 }
745 0 uri = sv_2mortal(pp_uri(aTHX_ cfg, ST(0), ST(1), uri_opt));
746 0 ST(0) = sv_2mortal(pp_render_qr(aTHX_ uri, opt));
747 0 XSRETURN(1);
748 }
749  
750 /* $c->totp_verify($user, $code) */
751 XS_INTERNAL(pp_h_verify);
752 0 XS_INTERNAL(pp_h_verify)
753 {
754 0 dXSARGS;
755 0 HV *cfg = pp_cfg_of(aTHX_ cv);
756 SV *c, *user, *code, *secret, *last;
757 HV *uh;
758 const pt_alg_t *alg;
759 int digits;
760 unsigned period, skew;
761 0 STRLEN cn = 0;
762 0 const char *cp = "";
763 0 ptotp_u64 now, lastc, matched = 0;
764 unsigned char *sec;
765 size_t slen;
766  
767 0 ▶ if (items < 2 || !pp_is_hash(ST(1)))
Branch: 2 branches
BranchTrueFalseTotal
if (items < 2 || !pp_is_hash(ST(1))) 0 0 0
if (items < 2 || !pp_is_hash(ST(1))) 0 0 0
768 0 croak("totp_verify takes a user hashref and a code");
769 0 c = ST(0);
770 0 user = ST(1);
771 0 ▶ code = items > 2 ? ST(2) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
code = items > 2 ? ST(2) : NULL; 0 0 0
772 0 uh = (HV *)SvRV(user);
773  
774 0 alg = pt_alg_of(aTHX_ pp_hget(aTHX_ cfg, "algorithm"));
775 0 digits = (int)pp_cfg_iv(aTHX_ cfg, "digits", 6);
776 0 period = (unsigned)pp_cfg_iv(aTHX_ cfg, "period", 30);
777 0 skew = (unsigned)pp_cfg_iv(aTHX_ cfg, "skew", 1);
778 0 now = (ptotp_u64)time(NULL);
779 0 ▶ if (code && SvOK(code)) cp = SvPV_const(code, cn);
Branch: 2 branches
BranchTrueFalseTotal
if (code && SvOK(code)) cp = SvPV_const(code, cn); 0 0 0
if (code && SvOK(code)) cp = SvPV_const(code, cn); 0 0 0
780  
781 0 secret = pp_user_get(aTHX_ cfg, uh, "secret");
782 0 ▶ if (!secret || !SvCUR(secret)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!secret || !SvCUR(secret)) { 0 0 0
if (!secret || !SvCUR(secret)) { 0 0 0
783 /* equal work, then refuse: response time must not report
784 * whether this account has 2FA enabled */
785 0 (void)ptotp_verify(PT_FRH, alg->frh_id, PP_DUMMY, sizeof PP_DUMMY - 1,
786 now, period, digits, cp, (size_t)cn, skew,
787 (ptotp_u64)-1, &matched);
788 0 XSRETURN_IV(0);
789 }
790  
791 0 sec = pt_secret_of(aTHX_ secret, &slen);
792 0 last = pp_user_get(aTHX_ cfg, uh, "counter");
793 0 ▶ lastc = last ? (ptotp_u64)SvNV(last) : (ptotp_u64)-1;
Branch: 1 branch
BranchTrueFalseTotal
lastc = last ? (ptotp_u64)SvNV(last) : (ptotp_u64)-1; 0 0 0
794 0 ▶ if (!ptotp_verify(PT_FRH, alg->frh_id, sec, slen, now, period, digits,
Branch: 1 branch
BranchTrueFalseTotal
if (!ptotp_verify(PT_FRH, alg->frh_id, sec, slen, now, period, digits, 0 0 0
795 cp, (size_t)cn, skew, lastc, &matched))
796 0 XSRETURN_IV(0);
797  
798 { /* the counter write IS the replay protection; without it a
799 * shoulder-surfed code stays valid for the rest of its window */
800 0 SV *model = pp_model(aTHX_ cfg, c, "model");
801 0 HV *data = newHV();
802 SV *dref, *ret, *id;
803 STRLEN fl;
804 0 const char *fp = SvPV_const(pp_field(aTHX_ cfg, "counter"), fl);
805 0 id = pp_hget(aTHX_ uh, "id");
806 0 ▶ (void)hv_stores(data, "id", id ? newSVsv(id) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(data, "id", id ? newSVsv(id) : newSV(0)); 0 0 0
807 0 (void)hv_store(data, fp, (I32)fl, newSVnv((NV)matched), 0);
808 0 dref = sv_2mortal(newRV_noinc((SV *)data));
809 0 ret = pp_call(aTHX_ model, "update", &dref, 1);
810 0 ▶ if (SvROK(ret)) SvREFCNT_dec(pp_await(aTHX_ c, ret));
Branch: 1 branch
BranchTrueFalseTotal
if (SvROK(ret)) SvREFCNT_dec(pp_await(aTHX_ c, ret)); 0 0 0
811 0 SvREFCNT_dec(ret);
812 0 (void)hv_store(uh, fp, (I32)fl, newSVnv((NV)matched), 0);
813 }
814 0 XSRETURN_IV(1);
815 }
816  
817 /* $c->totp_recovery_codes($user, count => $n) */
818 XS_INTERNAL(pp_h_recovery_codes);
819 0 XS_INTERNAL(pp_h_recovery_codes)
820 {
821 0 dXSARGS;
822 0 HV *cfg = pp_cfg_of(aTHX_ cv);
823 SV *c, *id, *m, *v, *res, *rows;
824 HV *opt;
825 0 IV n = 10, i;
826 AV *codes;
827  
828 0 ▶ if (items < 2 || !pp_is_hash(ST(1))
Branch: 2 branches
BranchTrueFalseTotal
if (items < 2 || !pp_is_hash(ST(1)) 0 0 0
if (items < 2 || !pp_is_hash(ST(1)) 0 0 0
829 0 ▶ || !(id = pp_hget(aTHX_ (HV *)SvRV(ST(1)), "id")))
Branch: 1 branch
BranchTrueFalseTotal
|| !(id = pp_hget(aTHX_ (HV *)SvRV(ST(1)), "id"))) 0 0 0
830 0 croak("totp_recovery_codes takes a user hashref");
831 0 c = ST(0);
832 0 opt = pt_pairs(aTHX_ "totp_recovery_codes", &ST(0), 2, items);
833 0 ▶ if ((v = pp_hget(aTHX_ opt, "count"))) n = SvIV(v);
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ opt, "count"))) n = SvIV(v); 0 0 0
834 0 ▶ if (n < 1 || n > 20) croak("count must be 1 to 20");
Branch: 2 branches
BranchTrueFalseTotal
if (n < 1 || n > 20) croak("count must be 1 to 20"); 0 0 0
if (n < 1 || n > 20) croak("count must be 1 to 20"); 0 0 0
835  
836 0 m = pp_model(aTHX_ cfg, c, "recovery_model");
837  
838 { /* a new set revokes the old set: partial invalidation is how a
839 * drawer ends up holding codes that half-work */
840 0 HV *f = newHV();
841 SV *fref;
842 0 (void)hv_stores(f, "user_id", newSVsv(id));
843 0 (void)hv_stores(f, "kind", newSVpvs(PP_RKIND));
844 0 fref = sv_2mortal(newRV_noinc((SV *)f));
845 0 res = sv_2mortal(pp_await(aTHX_ c,
846 sv_2mortal(pp_call(aTHX_ m, "search", &fref, 1))));
847 0 ▶ rows = pp_is_hash(res) ? pp_hget(aTHX_ (HV *)SvRV(res), "rows") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
rows = pp_is_hash(res) ? pp_hget(aTHX_ (HV *)SvRV(res), "rows") : NULL; 0 0 0
848 0 ▶ if (pp_is_array(rows)) {
Branch: 1 branch
BranchTrueFalseTotal
if (pp_is_array(rows)) { 0 0 0
849 0 AV *av = (AV *)SvRV(rows);
850 0 SSize_t ri, rn = av_len(av) + 1;
851 0 ▶ for (ri = 0; ri < rn; ri++) {
Branch: 1 branch
BranchTrueFalseTotal
for (ri = 0; ri < rn; ri++) { 0 0 0
852 0 SV **e = av_fetch(av, ri, 0);
853 0 ▶ SV *rid = (e && *e && pp_is_hash(*e))
Branch: 2 branches
BranchTrueFalseTotal
SV *rid = (e && *e && pp_is_hash(*e)) 0 0 0
SV *rid = (e && *e && pp_is_hash(*e)) 0 0 0
854 0 ▶ ? pp_hget(aTHX_ (HV *)SvRV(*e), "id") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? pp_hget(aTHX_ (HV *)SvRV(*e), "id") : NULL; 0 0 0
855 SV *argv[2];
856 0 ▶ if (!rid) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!rid) continue; 0 0 0
857 0 argv[0] = sv_2mortal(newSVpvs("id"));
858 0 argv[1] = rid;
859 0 SvREFCNT_dec(pp_await(aTHX_ c,
860 sv_2mortal(pp_call(aTHX_ m, "delete", argv, 2))));
861 }
862 }
863 }
864  
865 0 codes = newAV();
866 0 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 0 0 0
867 /* 16 base32 symbols (80 bits) in an alphabet with no 0/1/8/9 to
868 * mistype, grouped for humans */
869 unsigned char raw[16];
870 char b32[((sizeof raw + 4) / 5) * 8 + 1];
871 SV *code, *digest, *rref;
872 HV *row;
873 0 ▶ if (ptotp_random_bytes(raw, sizeof raw) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (ptotp_random_bytes(raw, sizeof raw) != 0) 0 0 0
874 0 croak("Punk::TOTP: the entropy source failed; refusing to degrade");
875 0 ptotp_b32_encode(b32, raw, sizeof raw);
876 0 code = newSVpvn(b32, 8);
877 0 sv_catpvs(code, "-");
878 0 sv_catpvn(code, b32 + 8, 8);
879 0 av_push(codes, code);
880  
881 0 digest = pp_recovery_digest(aTHX_ code);
882 0 row = newHV();
883 0 (void)hv_stores(row, "user_id", newSVsv(id));
884 0 (void)hv_stores(row, "kind", newSVpvs(PP_RKIND));
885 0 (void)hv_stores(row, "digest", digest);
886 0 (void)hv_stores(row, "expires", newSViv(0)); /* a drawer has no clock */
887 0 rref = sv_2mortal(newRV_noinc((SV *)row));
888 0 SvREFCNT_dec(pp_await(aTHX_ c,
889 sv_2mortal(pp_call(aTHX_ m, "create", &rref, 1))));
890 }
891 0 ST(0) = sv_2mortal(newRV_noinc((SV *)codes));
892 0 XSRETURN(1);
893 }
894  
895 /* $c->totp_use_recovery($user, $code) */
896 XS_INTERNAL(pp_h_use_recovery);
897 0 XS_INTERNAL(pp_h_use_recovery)
898 {
899 0 dXSARGS;
900 0 HV *cfg = pp_cfg_of(aTHX_ cv);
901 SV *c, *code, *id, *m, *res, *rows, *row, *rid, *gone, *v;
902 HV *f, *rh;
903 SV *fref, *argv[2];
904  
905 0 ▶ if (items < 2 || !pp_is_hash(ST(1))
Branch: 2 branches
BranchTrueFalseTotal
if (items < 2 || !pp_is_hash(ST(1)) 0 0 0
if (items < 2 || !pp_is_hash(ST(1)) 0 0 0
906 0 ▶ || !(id = pp_hget(aTHX_ (HV *)SvRV(ST(1)), "id")))
Branch: 1 branch
BranchTrueFalseTotal
|| !(id = pp_hget(aTHX_ (HV *)SvRV(ST(1)), "id"))) 0 0 0
907 0 croak("totp_use_recovery takes a user hashref and a code");
908 0 c = ST(0);
909 0 ▶ code = items > 2 ? ST(2) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
code = items > 2 ? ST(2) : NULL; 0 0 0
910 0 ▶ if (!(code && SvOK(code) && SvCUR(code))) XSRETURN_IV(0);
Branch: 3 branches
BranchTrueFalseTotal
if (!(code && SvOK(code) && SvCUR(code))) XSRETURN_IV(0); 0 0 0
if (!(code && SvOK(code) && SvCUR(code))) XSRETURN_IV(0); 0 0 0
if (!(code && SvOK(code) && SvCUR(code))) XSRETURN_IV(0); 0 0 0
911  
912 0 m = pp_model(aTHX_ cfg, c, "recovery_model");
913 0 f = newHV();
914 0 (void)hv_stores(f, "digest", pp_recovery_digest(aTHX_ code));
915 /* scoped to the challenged account: a search on the digest alone walks
916 * every user's rows, which leaves the ownership test below as the only
917 * thing binding a code to the account it was issued to */
918 0 (void)hv_stores(f, "user_id", newSVsv(id));
919 0 fref = sv_2mortal(newRV_noinc((SV *)f));
920 0 res = sv_2mortal(pp_await(aTHX_ c,
921 sv_2mortal(pp_call(aTHX_ m, "search", &fref, 1))));
922 0 ▶ rows = pp_is_hash(res) ? pp_hget(aTHX_ (HV *)SvRV(res), "rows") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
rows = pp_is_hash(res) ? pp_hget(aTHX_ (HV *)SvRV(res), "rows") : NULL; 0 0 0
923 0 ▶ if (!pp_is_array(rows) || av_len((AV *)SvRV(rows)) < 0) XSRETURN_IV(0);
Branch: 2 branches
BranchTrueFalseTotal
if (!pp_is_array(rows) || av_len((AV *)SvRV(rows)) < 0) XSRETURN_IV(0); 0 0 0
if (!pp_is_array(rows) || av_len((AV *)SvRV(rows)) < 0) XSRETURN_IV(0); 0 0 0
924 0 row = *av_fetch((AV *)SvRV(rows), 0, 0);
925 0 ▶ if (!pp_is_hash(row)) XSRETURN_IV(0);
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_hash(row)) XSRETURN_IV(0); 0 0 0
926 0 rh = (HV *)SvRV(row);
927 0 rid = pp_hget(aTHX_ rh, "id");
928 0 ▶ if (!rid) XSRETURN_IV(0);
Branch: 1 branch
BranchTrueFalseTotal
if (!rid) XSRETURN_IV(0); 0 0 0
929  
930 /* THE ORDER IS THE FEATURE: delete first, validate after. A code is
931 * spent whether or not it turns out valid, so a wrong-kind probe
932 * burns the row it hit rather than leaving it live for its real
933 * endpoint - take_token's discipline. */
934 0 argv[0] = sv_2mortal(newSVpvs("id"));
935 0 argv[1] = rid;
936 0 gone = sv_2mortal(pp_await(aTHX_ c,
937 sv_2mortal(pp_call(aTHX_ m, "delete", argv, 2))));
938 0 ▶ if (!SvTRUE(gone)) XSRETURN_IV(0); /* raced; the other take won */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvTRUE(gone)) XSRETURN_IV(0); /* raced; the other take won */ 0 0 0
939 0 v = pp_hget(aTHX_ rh, "kind");
940 0 ▶ if (!v || !strEQ(SvPV_nolen_const(v), PP_RKIND)) XSRETURN_IV(0);
Branch: 2 branches
BranchTrueFalseTotal
if (!v || !strEQ(SvPV_nolen_const(v), PP_RKIND)) XSRETURN_IV(0); 0 0 0
if (!v || !strEQ(SvPV_nolen_const(v), PP_RKIND)) XSRETURN_IV(0); 0 0 0
941 /* as bytes, not as integers: a user model may be keyed on a username, an
942 * email address or a UUID, and every one of those coerces to 0, which
943 * makes any two of them compare equal - one account's recovery code then
944 * passes another account's challenge. The filter above should mean this
945 * never fires; it stays because a model that ignores a filter key must
946 * not be the difference between accounts. */
947 0 v = pp_hget(aTHX_ rh, "user_id");
948 0 ▶ if (!v || !sv_eq(v, id)) XSRETURN_IV(0);
Branch: 2 branches
BranchTrueFalseTotal
if (!v || !sv_eq(v, id)) XSRETURN_IV(0); 0 0 0
if (!v || !sv_eq(v, id)) XSRETURN_IV(0); 0 0 0
949 0 v = pp_hget(aTHX_ rh, "expires");
950 0 ▶ if (v && SvIV(v) && SvIV(v) < (IV)time(NULL)) XSRETURN_IV(0);
Branch: 3 branches
BranchTrueFalseTotal
if (v && SvIV(v) && SvIV(v) < (IV)time(NULL)) XSRETURN_IV(0); 0 0 0
if (v && SvIV(v) && SvIV(v) < (IV)time(NULL)) XSRETURN_IV(0); 0 0 0
if (v && SvIV(v) && SvIV(v) < (IV)time(NULL)) XSRETURN_IV(0); 0 0 0
951 0 XSRETURN_IV(1);
952 }
953  
954 /* ---- the auth seam -----------------------------------------------------------
955 * A half-authenticated session writes `totp_pending` and NOT the auth
956 * session key. That is the whole mechanism: the auth battery reads
957 * exactly one key, so a pending session has no identity as far as every
958 * existing auth_guard is concerned. */
959  
960 /* $c->totp_challenge($user, to => $path) */
961 XS_INTERNAL(pp_h_challenge);
962 0 XS_INTERNAL(pp_h_challenge)
963 {
964 0 dXSARGS;
965 0 HV *cfg = pp_cfg_of(aTHX_ cv);
966 SV *c, *id;
967 HV *opt, *s;
968  
969 0 ▶ if (items < 2 || !pp_is_hash(ST(1))
Branch: 2 branches
BranchTrueFalseTotal
if (items < 2 || !pp_is_hash(ST(1)) 0 0 0
if (items < 2 || !pp_is_hash(ST(1)) 0 0 0
970 0 ▶ || !(id = pp_hget(aTHX_ (HV *)SvRV(ST(1)), "id")))
Branch: 1 branch
BranchTrueFalseTotal
|| !(id = pp_hget(aTHX_ (HV *)SvRV(ST(1)), "id"))) 0 0 0
971 0 croak("totp_challenge takes a user hashref");
972 0 c = ST(0);
973 0 opt = pt_pairs(aTHX_ "totp_challenge", &ST(0), 2, items);
974 0 s = pp_session(aTHX_ c);
975 0 pp_set_pending(aTHX_ cfg, s, id, pp_hget(aTHX_ opt, "to"));
976 0 ST(0) = sv_2mortal(pp_redirect(aTHX_ c, pp_cfg_sv(aTHX_ cfg, "challenge_path")));
977 0 XSRETURN(1);
978 }
979  
980 /* $c->totp_complete: the marker becomes a login */
981 XS_INTERNAL(pp_h_complete);
982 0 XS_INTERNAL(pp_h_complete)
983 {
984 0 dXSARGS;
985 SV *c, *pref, *id, *to, *can, *name;
986 HV *s, *p;
987 SV **e;
988  
989 0 ▶ if (items < 1) croak("totp_complete takes the context");
Branch: 1 branch
BranchTrueFalseTotal
if (items < 1) croak("totp_complete takes the context"); 0 0 0
990 0 c = ST(0);
991 0 s = pp_session(aTHX_ c);
992 0 e = hv_fetchs(s, "totp_pending", 0);
993 0 ▶ if (!(e && *e && pp_is_hash(*e))) XSRETURN_UNDEF;
Branch: 3 branches
BranchTrueFalseTotal
if (!(e && *e && pp_is_hash(*e))) XSRETURN_UNDEF; 0 0 0
if (!(e && *e && pp_is_hash(*e))) XSRETURN_UNDEF; 0 0 0
if (!(e && *e && pp_is_hash(*e))) XSRETURN_UNDEF; 0 0 0
994 0 pref = sv_2mortal(newSVsv(*e)); /* keeps the hash alive */
995 0 (void)hv_delete(s, "totp_pending", 12, G_DISCARD);
996 0 p = (HV *)SvRV(pref);
997 0 id = pp_hget(aTHX_ p, "id");
998 0 to = pp_hget(aTHX_ p, "to");
999  
1000 0 ▶ if (id) SvREFCNT_dec(pp_call(aTHX_ c, "login", &id, 1));
Branch: 1 branch
BranchTrueFalseTotal
if (id) SvREFCNT_dec(pp_call(aTHX_ c, "login", &id, 1)); 0 0 0
1001 0 s = pp_session(aTHX_ c); /* login may have replaced it */
1002 0 (void)hv_stores(s, "totp_at", newSViv((IV)time(NULL)));
1003  
1004 /* the moment the second factor passes is where rotation belongs:
1005 * with a session store this closes the fixation window; without one
1006 * it is Punk's documented no-op, and before 0.26 it does not exist */
1007 0 name = sv_2mortal(newSVpvs("session_rotate"));
1008 0 can = sv_2mortal(pp_call(aTHX_ c, "can", &name, 1));
1009 0 ▶ if (SvTRUE(can)) SvREFCNT_dec(pp_call(aTHX_ c, "session_rotate", NULL, 0));
Branch: 1 branch
BranchTrueFalseTotal
if (SvTRUE(can)) SvREFCNT_dec(pp_call(aTHX_ c, "session_rotate", NULL, 0)); 0 0 0
1010  
1011 0 ▶ ST(0) = to ? sv_2mortal(newSVsv(to)) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
ST(0) = to ? sv_2mortal(newSVsv(to)) : &PL_sv_undef; 0 0 0
1012 0 XSRETURN(1);
1013 }
1014  
1015 /* ---- the challenge route -------------------------------------------------- */
1016  
1017 /* the challenge page: whatever `render` names, or the self-contained
1018 * default so the plugin works out of the box */
1019 0 static SV *pp_render(pTHX_ HV *cfg, SV *c, int error)
1020 {
1021 0 SV *r = pp_hget(aTHX_ cfg, "render");
1022 0 SV *errsv = sv_2mortal(newSViv(error ? 1 : 0));
1023 0 ▶ if (r) {
Branch: 1 branch
BranchTrueFalseTotal
if (r) { 0 0 0
1024 0 ▶ if (SvROK(r) && SvTYPE(SvRV(r)) == SVt_PVCV) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(r) && SvTYPE(SvRV(r)) == SVt_PVCV) { 0 0 0
if (SvROK(r) && SvTYPE(SvRV(r)) == SVt_PVCV) { 0 0 0
1025 SV *argv[2];
1026 0 argv[0] = c;
1027 0 argv[1] = errsv;
1028 0 return pp_call_code(aTHX_ r, argv, 2);
1029 }
1030 0 return pp_call(aTHX_ c, SvPV_nolen_const(r), &errsv, 1);
1031 }
1032 {
1033 0 SV *html = sv_2mortal(newSVpvs(
1034 "<!doctype html><title>Two-factor code</title>\n"
1035 "<h1>Enter your code</h1>"));
1036 0 ▶ if (error)
Branch: 1 branch
BranchTrueFalseTotal
if (error) 0 0 0
1037 0 sv_catpvs(html, "<p class=\"error\">That code did not work. "
1038 "Try again, or use a recovery code.</p>");
1039 0 sv_catpvs(html, "\n<form method=\"post\" action=\"");
1040 0 sv_catsv(html, pp_cfg_sv(aTHX_ cfg, "challenge_path"));
1041 0 sv_catpvs(html, "\">\n"
1042 "<input name=\"code\" autofocus autocomplete=\"one-time-code\"\n"
1043 " inputmode=\"numeric\" pattern=\"[0-9A-Za-z-]*\">\n");
1044 /* The application enabled `csrf` (decided once, at to_app), so its
1045 * check will refuse this form's POST without a token. The token is
1046 * single-use and minted per ask, so a failed code's re-render
1047 * carries a fresh one for free. */
1048 0 ▶ if (pp_cfg_iv(aTHX_ cfg, "csrf_on", 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (pp_cfg_iv(aTHX_ cfg, "csrf_on", 0)) { 0 0 0
1049 0 SV *f = sv_2mortal(pp_call(aTHX_ c, "csrf_field", NULL, 0));
1050 0 sv_catsv(html, f);
1051 0 sv_catpvs(html, "\n");
1052 }
1053 0 sv_catpvs(html,
1054 "<button>Verify</button>\n"
1055 "</form>\n");
1056 /* per-session, and now token-bearing: a stored copy is a page some
1057 * other visitor cannot use and should never be handed */
1058 {
1059 SV *argv[2];
1060 0 argv[0] = sv_2mortal(newSVpvs("Cache-Control"));
1061 0 argv[1] = sv_2mortal(newSVpvs("no-store"));
1062 0 SvREFCNT_dec(pp_call(aTHX_ c, "header", argv, 2));
1063 }
1064 0 return pp_call(aTHX_ c, "html", &html, 1);
1065 }
1066 }
1067  
1068 /* GET challenge_path */
1069 XS_INTERNAL(pp_r_get);
1070 0 XS_INTERNAL(pp_r_get)
1071 {
1072 0 dXSARGS;
1073 0 HV *cfg = pp_cfg_of(aTHX_ cv);
1074 SV *c;
1075 0 ▶ if (items < 1) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (items < 1) XSRETURN_EMPTY; 0 0 0
1076 0 c = ST(0);
1077 0 ▶ if (!pp_pending(aTHX_ c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_pending(aTHX_ c)) { 0 0 0
1078 0 ST(0) = sv_2mortal(pp_redirect(aTHX_ c, pp_cfg_sv(aTHX_ cfg, "login_path")));
1079 0 XSRETURN(1);
1080 }
1081 0 ST(0) = sv_2mortal(pp_render(aTHX_ cfg, c, 0));
1082 0 XSRETURN(1);
1083 }
1084  
1085 /* POST challenge_path */
1086 XS_INTERNAL(pp_r_post);
1087 0 XS_INTERNAL(pp_r_post)
1088 {
1089 0 dXSARGS;
1090 0 HV *cfg = pp_cfg_of(aTHX_ cv);
1091 SV *c, *id, *model, *user, *code, *ok, *argv[2], *name;
1092 HV *p;
1093 IV tries, limit;
1094  
1095 0 ▶ if (items < 1) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (items < 1) XSRETURN_EMPTY; 0 0 0
1096 0 c = ST(0);
1097 0 p = pp_pending(aTHX_ c);
1098 0 ▶ if (!p) {
Branch: 1 branch
BranchTrueFalseTotal
if (!p) { 0 0 0
1099 0 ST(0) = sv_2mortal(pp_redirect(aTHX_ c, pp_cfg_sv(aTHX_ cfg, "login_path")));
1100 0 XSRETURN(1);
1101 }
1102 0 id = pp_hget(aTHX_ p, "id");
1103  
1104 0 model = pp_model(aTHX_ cfg, c, "model");
1105 0 argv[0] = sv_2mortal(newSVpvs("id"));
1106 0 ▶ argv[1] = id ? id : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
argv[1] = id ? id : &PL_sv_undef; 0 0 0
1107 0 user = sv_2mortal(pp_call(aTHX_ model, "get", argv, 2));
1108 0 ▶ if (SvROK(user) && !pp_is_hash(user))
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(user) && !pp_is_hash(user)) 0 0 0
if (SvROK(user) && !pp_is_hash(user)) 0 0 0
1109 0 user = sv_2mortal(pp_await(aTHX_ c, user));
1110 0 ▶ if (!pp_is_hash(user)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_hash(user)) { 0 0 0
1111 0 (void)hv_delete(pp_session(aTHX_ c), "totp_pending", 12, G_DISCARD);
1112 0 ST(0) = sv_2mortal(pp_redirect(aTHX_ c, pp_cfg_sv(aTHX_ cfg, "login_path")));
1113 0 XSRETURN(1);
1114 }
1115  
1116 /* the count is read BEFORE the code is judged, and an account over the
1117 * limit is refused without judging it: a limit that still tells you
1118 * whether the guess was right is not a limit */
1119 0 limit = pp_cfg_iv(aTHX_ cfg, "attempts", 5);
1120 0 tries = pp_fail_count(aTHX_ cfg, (HV *)SvRV(user));
1121 0 ▶ if (tries >= limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (tries >= limit) { 0 0 0
1122 0 (void)hv_delete(pp_session(aTHX_ c), "totp_pending", 12, G_DISCARD);
1123 0 ST(0) = sv_2mortal(pp_redirect(aTHX_ c, pp_cfg_sv(aTHX_ cfg, "login_path")));
1124 0 XSRETURN(1);
1125 }
1126  
1127 0 name = sv_2mortal(newSVpvs("code"));
1128 0 code = sv_2mortal(pp_call(aTHX_ c, "param", &name, 1));
1129 0 ▶ if (!SvOK(code)) sv_setpvs(code, "");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(code)) sv_setpvs(code, ""); 0 0 0
1130  
1131 0 argv[0] = user;
1132 0 argv[1] = code;
1133 0 ok = sv_2mortal(pp_call(aTHX_ c, "totp_verify", argv, 2));
1134 0 ▶ if (!SvTRUE(ok))
Branch: 1 branch
BranchTrueFalseTotal
if (!SvTRUE(ok)) 0 0 0
1135 0 ok = sv_2mortal(pp_call(aTHX_ c, "totp_use_recovery", argv, 2));
1136 0 ▶ if (SvTRUE(ok)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTRUE(ok)) { 0 0 0
1137 SV *to;
1138 0 pp_fail_clear(aTHX_ cfg, c, (HV *)SvRV(user));
1139 0 to = sv_2mortal(pp_call(aTHX_ c, "totp_complete", NULL, 0));
1140 0 ▶ if (!SvOK(to)) sv_setpvs(to, "/");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(to)) sv_setpvs(to, "/"); 0 0 0
1141 0 ST(0) = sv_2mortal(pp_redirect(aTHX_ c, to));
1142 0 XSRETURN(1);
1143 }
1144  
1145 /* repeated failure clears the pending state entirely, dropping the
1146 * attacker back to needing the password again - a limit that only
1147 * delays is a limit a patient script waits out */
1148 /* a count that cannot be written is a limit that is not running, so the
1149 * failure spends the marker instead: safe, and loud enough to notice */
1150 0 tries = pp_fail_bump(aTHX_ cfg, c, (HV *)SvRV(user), tries) ? tries + 1
1151 0 ▶ : limit;
Branch: 1 branch
BranchTrueFalseTotal
: limit; 0 0 0
1152 0 p = pp_pending(aTHX_ c); /* re-read: Perl ran in between */
1153 0 ▶ if (!p || tries >= limit) {
Branch: 2 branches
BranchTrueFalseTotal
if (!p || tries >= limit) { 0 0 0
if (!p || tries >= limit) { 0 0 0
1154 0 (void)hv_delete(pp_session(aTHX_ c), "totp_pending", 12, G_DISCARD);
1155 0 ST(0) = sv_2mortal(pp_redirect(aTHX_ c, pp_cfg_sv(aTHX_ cfg, "login_path")));
1156 0 XSRETURN(1);
1157 }
1158 0 ST(0) = sv_2mortal(pp_render(aTHX_ cfg, c, 1));
1159 0 XSRETURN(1);
1160 }
1161  
1162 /* ---- the step-up guard -------------------------------------------------------
1163 * totp_guard() hands back a guard for an `under` chain. It sits AFTER
1164 * auth_guard, which established identity; it asks whether THIS session
1165 * satisfied the factor. */
1166  
1167 XS_INTERNAL(pp_guard);
1168 0 XS_INTERNAL(pp_guard)
1169 {
1170 0 dXSARGS;
1171 0 HV *cfg = pp_cfg_of(aTHX_ cv);
1172 SV *c, *at, *id;
1173 HV *s;
1174  
1175 0 ▶ if (items < 1) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (items < 1) XSRETURN_EMPTY; 0 0 0
1176 0 c = ST(0);
1177 0 s = pp_session(aTHX_ c);
1178 0 at = pp_hget(aTHX_ s, "totp_at");
1179 0 ▶ if (at && SvTRUE(at)) XSRETURN_EMPTY; /* continue */
Branch: 2 branches
BranchTrueFalseTotal
if (at && SvTRUE(at)) XSRETURN_EMPTY; /* continue */ 0 0 0
if (at && SvTRUE(at)) XSRETURN_EMPTY; /* continue */ 0 0 0
1180  
1181 0 id = sv_2mortal(pp_call(aTHX_ c, "auth_id", NULL, 0));
1182 0 ▶ if (SvOK(id)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(id)) { 0 0 0
1183 /* signed in without the factor: step up, and come back here */
1184 0 SV *req = sv_2mortal(pp_call(aTHX_ c, "req", NULL, 0));
1185 0 SV *path = sv_2mortal(pp_call(aTHX_ req, "path", NULL, 0));
1186 0 pp_set_pending(aTHX_ cfg, pp_session(aTHX_ c), id, path);
1187 }
1188 0 ▶ ST(0) = sv_2mortal(pp_redirect(aTHX_ c,
Branch: 1 branch
BranchTrueFalseTotal
ST(0) = sv_2mortal(pp_redirect(aTHX_ c, 0 0 0
1189 pp_cfg_sv(aTHX_ cfg, SvOK(id) ? "challenge_path" : "login_path")));
1190 0 XSRETURN(1);
1191 }
1192  
1193 /* the `totp_guard` keyword: returns a fresh guard closure */
1194 XS_INTERNAL(pp_kw_guard);
1195 0 XS_INTERNAL(pp_kw_guard)
1196 {
1197 0 dXSARGS;
1198 0 HV *cfg = pp_cfg_of(aTHX_ cv);
1199 PERL_UNUSED_VAR(items);
1200 0 ST(0) = sv_2mortal(pp_closure(aTHX_ pp_guard, cfg));
1201 0 XSRETURN(1);
1202 }
1203  
1204 /* The to_app callback: whether the application enabled `csrf`, read once
1205 * every keyword has recorded, so the answer cannot depend on whether the
1206 * `csrf` line sits above or below the `plugin` line. Presence of the key on
1207 * the registrar is the fact - `csrf 0` deletes it. */
1208 XS_INTERNAL(pp_oc_csrf);
1209 0 XS_INTERNAL(pp_oc_csrf)
1210 {
1211 0 dXSARGS;
1212 0 HV *cfg = pp_cfg_of(aTHX_ cv);
1213 0 int on = 0;
1214 0 ▶ if (items >= 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (items >= 1) { 0 0 0
1215 0 SV *app = ST(0);
1216 0 ▶ if (SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 0 0 0
if (SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 0 0 0
1217 0 on = hv_exists((HV *)SvRV(app), "csrf", 4) ? 1 : 0;
1218 }
1219 0 (void)hv_stores(cfg, "csrf_on", newSViv(on));
1220 0 XSRETURN_EMPTY;
1221 }
1222  
1223 /* ---- registration ------------------------------------------------------------ */
1224  
1225 0 static void pp_helper(pTHX_ SV *app, const char *name, XSUBADDR_t body, HV *cfg)
1226 {
1227 SV *argv[2];
1228 0 argv[0] = sv_2mortal(newSVpv(name, 0));
1229 0 argv[1] = sv_2mortal(pp_closure(aTHX_ body, cfg));
1230 0 SvREFCNT_dec(pp_call(aTHX_ app, "helper", argv, 2));
1231 0 }
1232  
1233 0 static void pp_route(pTHX_ SV *app, const char *method, SV *path,
1234 XSUBADDR_t body, HV *cfg)
1235 {
1236 SV *argv[3];
1237 0 argv[0] = sv_2mortal(newSVpv(method, 0));
1238 0 argv[1] = path;
1239 0 argv[2] = sv_2mortal(pp_closure(aTHX_ body, cfg));
1240 0 SvREFCNT_dec(pp_call(aTHX_ app, "route", argv, 3));
1241 0 }
1242  
1243 /* a config value: the option if given, else the default (which may be
1244 * NULL for "no default") */
1245 0 static SV *pp_opt_or(pTHX_ HV *opts, const char *k, SV *dflt)
1246 {
1247 0 SV *v = pp_hget(aTHX_ opts, k);
1248 0 ▶ if (v) {
Branch: 1 branch
BranchTrueFalseTotal
if (v) { 0 0 0
1249 0 ▶ if (dflt) SvREFCNT_dec(dflt);
Branch: 1 branch
BranchTrueFalseTotal
if (dflt) SvREFCNT_dec(dflt); 0 0 0
1250 0 return newSVsv(v);
1251 }
1252 0 return dflt;
1253 }
1254  
1255 0 static void pp_register(pTHX_ SV *app, SV *optsv)
1256 {
1257 static const char *const known[] = {
1258 "issuer", "algorithm", "digits", "period", "skew", "model",
1259 "fields", "recovery_model", "challenge_path", "login_path",
1260 "attempts", "attempt_window", "pending_ttl", "render", "sqitch" };
1261 static const char *const fkeys[] = { "secret", "counter", "enabled", "email",
1262 "failed", "failed_at" };
1263 HV *opts, *cfg, *fields;
1264 SV *pkgsv, *v;
1265 STRLEN pl;
1266 const char *pkg;
1267 char lower[8];
1268 int i;
1269  
1270 0 ▶ if (!PP_STATE) PP_STATE = newHV();
Branch: 1 branch
BranchTrueFalseTotal
if (!PP_STATE) PP_STATE = newHV(); 0 0 0
1271 0 ▶ if (SvOK(optsv) && !pp_is_hash(optsv))
Branch: 2 branches
BranchTrueFalseTotal
if (SvOK(optsv) && !pp_is_hash(optsv)) 0 0 0
if (SvOK(optsv) && !pp_is_hash(optsv)) 0 0 0
1272 0 croak("plugin 'TOTP' takes a hashref of options");
1273 0 opts = pp_is_hash(optsv) ? (HV *)SvRV(optsv)
1274 0 ▶ : (HV *)sv_2mortal((SV *)newHV());
Branch: 1 branch
BranchTrueFalseTotal
: (HV *)sv_2mortal((SV *)newHV()); 0 0 0
1275  
1276 0 pkgsv = sv_2mortal(pp_call(aTHX_ app, "caller_class", NULL, 0));
1277 0 pkg = SvPV_const(pkgsv, pl);
1278 0 ▶ if (hv_exists(PP_STATE, pkg, (I32)pl))
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists(PP_STATE, pkg, (I32)pl)) 0 0 0
1279 0 croak("plugin 'TOTP' already registered for %s", pkg);
1280  
1281 /* unknown options croak at boot, in sorted order so the message is
1282 * deterministic when several are wrong at once */
1283 {
1284 0 AV *keys = (AV *)sv_2mortal((SV *)newAV());
1285 HE *he;
1286 SSize_t ki, kn;
1287 0 hv_iterinit(opts);
1288 0 ▶ while ((he = hv_iternext(opts))) av_push(keys, newSVsv(hv_iterkeysv(he)));
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(opts))) av_push(keys, newSVsv(hv_iterkeysv(he))); 0 0 0
1289 0 ▶ if (av_len(keys) > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(keys) > 0) 0 0 0
1290 0 sortsv(AvARRAY(keys), (size_t)(av_len(keys) + 1), Perl_sv_cmp);
1291 0 kn = av_len(keys) + 1;
1292 0 ▶ for (ki = 0; ki < kn; ki++) {
Branch: 1 branch
BranchTrueFalseTotal
for (ki = 0; ki < kn; ki++) { 0 0 0
1293 0 const char *k = SvPV_nolen_const(*av_fetch(keys, ki, 0));
1294 0 int found = 0;
1295 0 ▶ for (i = 0; i < (int)(sizeof known / sizeof known[0]); i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < (int)(sizeof known / sizeof known[0]); i++) 0 0 0
1296 0 ▶ if (strEQ(k, known[i])) { found = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(k, known[i])) { found = 1; break; } 0 0 0
1297 0 ▶ if (!found) croak("unknown TOTP plugin option '%s'", k);
Branch: 1 branch
BranchTrueFalseTotal
if (!found) croak("unknown TOTP plugin option '%s'", k); 0 0 0
1298 }
1299 }
1300  
1301 0 cfg = (HV *)sv_2mortal((SV *)newHV()); /* owned by PP_STATE below */
1302 0 v = pp_opt_or(aTHX_ opts, "issuer", NULL);
1303 0 ▶ if (!v)
Branch: 1 branch
BranchTrueFalseTotal
if (!v) 0 0 0
1304 0 croak("TOTP issuer is required - it names the account in the "
1305 "authenticator app");
1306 0 (void)hv_stores(cfg, "issuer", v);
1307  
1308 /* algorithm, lowercased: the engine accepts any case, the
1309 * configuration stores one spelling */
1310 {
1311 0 SV *a = pp_hget(aTHX_ opts, "algorithm");
1312 0 STRLEN al = 4, j;
1313 0 ▶ const char *ap = a ? SvPV_const(a, al) : "sha1";
Branch: 1 branch
BranchTrueFalseTotal
const char *ap = a ? SvPV_const(a, al) : "sha1"; 0 0 0
1314 0 ▶ if (al >= sizeof lower)
Branch: 1 branch
BranchTrueFalseTotal
if (al >= sizeof lower) 0 0 0
1315 0 croak("TOTP algorithm must be sha1, sha256 or sha512, not '%.*s'",
1316 (int)al, ap);
1317 0 ▶ for (j = 0; j < al; j++) lower[j] = (char)toLOWER(ap[j]);
Branch: 2 branches
BranchTrueFalseTotal
for (j = 0; j < al; j++) lower[j] = (char)toLOWER(ap[j]); 0 0 0
for (j = 0; j < al; j++) lower[j] = (char)toLOWER(ap[j]); 0 0 0
1318 0 lower[al] = '\0';
1319 0 ▶ if (!strEQ(lower, "sha1") && !strEQ(lower, "sha256")
Branch: 2 branches
BranchTrueFalseTotal
if (!strEQ(lower, "sha1") && !strEQ(lower, "sha256") 0 0 0
if (!strEQ(lower, "sha1") && !strEQ(lower, "sha256") 0 0 0
1320 0 ▶ && !strEQ(lower, "sha512"))
Branch: 1 branch
BranchTrueFalseTotal
&& !strEQ(lower, "sha512")) 0 0 0
1321 0 croak("TOTP algorithm must be sha1, sha256 or sha512, not '%s'",
1322 lower);
1323 0 (void)hv_stores(cfg, "algorithm", newSVpv(lower, 0));
1324 }
1325 {
1326 0 ▶ IV d = (v = pp_hget(aTHX_ opts, "digits")) ? SvIV(v) : 6;
Branch: 1 branch
BranchTrueFalseTotal
IV d = (v = pp_hget(aTHX_ opts, "digits")) ? SvIV(v) : 6; 0 0 0
1327 0 ▶ if (d < 6 || d > 8) croak("TOTP digits must be 6, 7 or 8");
Branch: 2 branches
BranchTrueFalseTotal
if (d < 6 || d > 8) croak("TOTP digits must be 6, 7 or 8"); 0 0 0
if (d < 6 || d > 8) croak("TOTP digits must be 6, 7 or 8"); 0 0 0
1328 0 (void)hv_stores(cfg, "digits", newSViv(d));
1329 }
1330 0 (void)hv_stores(cfg, "period", pp_opt_or(aTHX_ opts, "period", newSViv(30)));
1331 0 (void)hv_stores(cfg, "skew", pp_opt_or(aTHX_ opts, "skew", newSViv(1)));
1332 0 (void)hv_stores(cfg, "model", pp_opt_or(aTHX_ opts, "model", newSVpvs("User")));
1333 0 (void)hv_stores(cfg, "recovery_model", pp_opt_or(aTHX_ opts, "recovery_model", newSVpvs("Token")));
1334 0 (void)hv_stores(cfg, "challenge_path", pp_opt_or(aTHX_ opts, "challenge_path", newSVpvs("/login/totp")));
1335 0 (void)hv_stores(cfg, "login_path", pp_opt_or(aTHX_ opts, "login_path", newSVpvs("/login")));
1336 /* both are checked because both fail in a direction that is easy to miss:
1337 * no attempts locks every account out for good, and no window means every
1338 * failure has already lapsed, which is a limit that never counts */
1339 {
1340 0 ▶ IV a = (v = pp_hget(aTHX_ opts, "attempts")) ? SvIV(v) : 5;
Branch: 1 branch
BranchTrueFalseTotal
IV a = (v = pp_hget(aTHX_ opts, "attempts")) ? SvIV(v) : 5; 0 0 0
1341 0 ▶ IV w = (v = pp_hget(aTHX_ opts, "attempt_window")) ? SvIV(v) : 900;
Branch: 1 branch
BranchTrueFalseTotal
IV w = (v = pp_hget(aTHX_ opts, "attempt_window")) ? SvIV(v) : 900; 0 0 0
1342 0 ▶ if (a < 1) croak("TOTP attempts must be 1 or more");
Branch: 1 branch
BranchTrueFalseTotal
if (a < 1) croak("TOTP attempts must be 1 or more"); 0 0 0
1343 0 ▶ if (w < 1) croak("TOTP attempt_window must be 1 second or more");
Branch: 1 branch
BranchTrueFalseTotal
if (w < 1) croak("TOTP attempt_window must be 1 second or more"); 0 0 0
1344 0 (void)hv_stores(cfg, "attempts", newSViv(a));
1345 0 (void)hv_stores(cfg, "attempt_window", newSViv(w));
1346 }
1347 0 (void)hv_stores(cfg, "pending_ttl", pp_opt_or(aTHX_ opts, "pending_ttl", newSViv(300)));
1348 0 ▶ if ((v = pp_hget(aTHX_ opts, "render")))
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ opts, "render"))) 0 0 0
1349 0 (void)hv_stores(cfg, "render", newSVsv(v));
1350  
1351 /* the fields map onto the application's own column names */
1352 0 fields = newHV();
1353 0 (void)hv_stores(fields, "secret", newSVpvs("totp_secret"));
1354 0 (void)hv_stores(fields, "counter", newSVpvs("totp_last_counter"));
1355 0 (void)hv_stores(fields, "enabled", newSVpvs("totp_enabled"));
1356 0 (void)hv_stores(fields, "email", newSVpvs("email"));
1357 0 (void)hv_stores(fields, "failed", newSVpvs("totp_failed"));
1358 0 (void)hv_stores(fields, "failed_at", newSVpvs("totp_failed_at"));
1359 0 (void)hv_stores(cfg, "fields", newRV_noinc((SV *)fields));
1360 0 ▶ if ((v = pp_hget(aTHX_ opts, "fields"))) {
Branch: 1 branch
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ opts, "fields"))) { 0 0 0
1361 HE *he;
1362 0 ▶ if (!pp_is_hash(v)) croak("TOTP fields must be a hashref");
Branch: 1 branch
BranchTrueFalseTotal
if (!pp_is_hash(v)) croak("TOTP fields must be a hashref"); 0 0 0
1363 0 hv_iterinit((HV *)SvRV(v));
1364 0 ▶ while ((he = hv_iternext((HV *)SvRV(v)))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext((HV *)SvRV(v)))) { 0 0 0
1365 0 const char *k = SvPV_nolen_const(hv_iterkeysv(he));
1366 0 int found = 0;
1367 0 ▶ for (i = 0; i < (int)(sizeof fkeys / sizeof fkeys[0]); i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < (int)(sizeof fkeys / sizeof fkeys[0]); i++) 0 0 0
1368 0 ▶ if (strEQ(k, fkeys[i])) { found = 1; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (strEQ(k, fkeys[i])) { found = 1; break; } 0 0 0
1369 0 ▶ if (!found) croak("unknown TOTP fields key '%s'", k);
Branch: 1 branch
BranchTrueFalseTotal
if (!found) croak("unknown TOTP fields key '%s'", k); 0 0 0
1370 0 (void)hv_store(fields, k, (I32)strlen(k),
1371 newSVsv(hv_iterval((HV *)SvRV(v), he)), 0);
1372 }
1373 }
1374  
1375 0 (void)hv_store(PP_STATE, pkg, (I32)pl, newRV_inc((SV *)cfg), 0);
1376  
1377 /* sqitch => 1: the three columns, shipped as the Sqitch project
1378 * `punk_totp` under lib/Punk/Plugin/TOTP/sqitch - one change requiring
1379 * punk_auth:users - and registered with Punk-Sqitch, which deploys it
1380 * after Punk::Auth's project and before the application's. Opt-in, as
1381 * `fields` exists for rows with other column names; asking without
1382 * Punk-Sqitch installed is an error, not a silence. */
1383 0 ▶ if ((v = pp_hget(aTHX_ opts, "sqitch")) && SvTRUE(v)) {
Branch: 2 branches
BranchTrueFalseTotal
if ((v = pp_hget(aTHX_ opts, "sqitch")) && SvTRUE(v)) { 0 0 0
if ((v = pp_hget(aTHX_ opts, "sqitch")) && SvTRUE(v)) { 0 0 0
1384 /* Located from Punk/TOTP.pm, the module this XS always loads through:
1385 * Punk/Plugin/TOTP.pm may never be in %INC at all, since Punk skips
1386 * the require when the package already has a register - which it
1387 * does the moment Punk::TOTP is loaded by anything. */
1388 0 SV **totppm = hv_fetchs(GvHV(PL_incgv), "Punk/TOTP.pm", 0);
1389 SV *dir, *argv[4], *cls, *r;
1390 AV *eng;
1391 0 eval_pv("require Punk::Plugin::Sqitch; 1", FALSE);
1392 0 ▶ if (SvTRUE(ERRSV))
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) 0 0 0
if (SvTRUE(ERRSV)) 0 0 0
1393 0 ▶ croak("plugin 'TOTP': sqitch => 1 needs Punk-Sqitch "
Branch: 1 branch
BranchTrueFalseTotal
croak("plugin 'TOTP': sqitch => 1 needs Punk-Sqitch " 0 0 0
1394 "(Punk::Plugin::Sqitch) installed: %s", SvPV_nolen(ERRSV));
1395 0 ▶ if (!(totppm && *totppm && SvOK(*totppm)))
Branch: 3 branches
BranchTrueFalseTotal
if (!(totppm && *totppm && SvOK(*totppm))) 0 0 0
if (!(totppm && *totppm && SvOK(*totppm))) 0 0 0
if (!(totppm && *totppm && SvOK(*totppm))) 0 0 0
1396 0 croak("plugin 'TOTP': cannot find Punk/TOTP.pm in %%INC to "
1397 "locate the punk_totp Sqitch project");
1398 0 dir = sv_2mortal(newSVsv(*totppm));
1399 { /* .../Punk/TOTP.pm -> .../Punk/Plugin/TOTP/sqitch */
1400 0 STRLEN dl; const char *dp = SvPV_const(dir, dl);
1401 0 ▶ if (dl >= 7 && memEQ(dp + dl - 7, "TOTP.pm", 7)) SvCUR_set(dir, dl - 7);
Branch: 2 branches
BranchTrueFalseTotal
if (dl >= 7 && memEQ(dp + dl - 7, "TOTP.pm", 7)) SvCUR_set(dir, dl - 7); 0 0 0
if (dl >= 7 && memEQ(dp + dl - 7, "TOTP.pm", 7)) SvCUR_set(dir, dl - 7); 0 0 0
1402 }
1403 0 sv_catpvs(dir, "Plugin/TOTP/sqitch");
1404 0 eng = newAV();
1405 0 av_push(eng, newSVpvs("sqlite"));
1406 0 av_push(eng, newSVpvs("pg"));
1407 0 av_push(eng, newSVpvs("mysql"));
1408 0 cls = sv_2mortal(newSVpvs("Punk::Plugin::Sqitch"));
1409 0 argv[0] = app;
1410 0 argv[1] = sv_2mortal(newSVpvs("punk_totp"));
1411 0 argv[2] = dir;
1412 0 argv[3] = sv_2mortal(newSVpvs("engines"));
1413 {
1414 0 SV *argv5[5] = { argv[0], argv[1], argv[2], argv[3],
1415 0 sv_2mortal(newRV_noinc((SV *)eng)) };
1416 0 r = pp_call(aTHX_ cls, "project", argv5, 5);
1417 }
1418 0 ▶ if (r) SvREFCNT_dec(r);
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); 0 0 0
1419 0 (void)hv_delete(cfg, "sqitch", 6, G_DISCARD);
1420 }
1421  
1422 /* the QR renderer, resolved now: fail at boot, not at enrolment */
1423 0 pp_qr_boot(aTHX);
1424  
1425 0 pp_helper(aTHX_ app, "totp_secret", pp_h_secret, cfg);
1426 0 pp_helper(aTHX_ app, "totp_uri", pp_h_uri, cfg);
1427 0 pp_helper(aTHX_ app, "totp_qr", pp_h_qr, cfg);
1428 0 pp_helper(aTHX_ app, "totp_verify", pp_h_verify, cfg);
1429 0 pp_helper(aTHX_ app, "totp_recovery_codes", pp_h_recovery_codes, cfg);
1430 0 pp_helper(aTHX_ app, "totp_use_recovery", pp_h_use_recovery, cfg);
1431 0 pp_helper(aTHX_ app, "totp_challenge", pp_h_challenge, cfg);
1432 0 pp_helper(aTHX_ app, "totp_complete", pp_h_complete, cfg);
1433  
1434 {
1435 0 SV *path = pp_cfg_sv(aTHX_ cfg, "challenge_path");
1436 SV *argv[6];
1437 0 pp_route(aTHX_ app, "GET", path, pp_r_get, cfg);
1438 0 pp_route(aTHX_ app, "POST", path, pp_r_post, cfg);
1439 /* per-address, on top of (not instead of) the tries clear */
1440 0 argv[0] = sv_2mortal(newSVpvs("for")); argv[1] = path;
1441 0 argv[2] = sv_2mortal(newSVpvs("limit")); argv[3] = sv_2mortal(newSViv(30));
1442 0 argv[4] = sv_2mortal(newSVpvs("window")); argv[5] = sv_2mortal(newSViv(60));
1443 0 SvREFCNT_dec(pp_call(aTHX_ app, "rate_limit", argv, 6));
1444 }
1445 {
1446 SV *argv[3];
1447 0 argv[0] = sv_2mortal(newSVpvs("totp_guard"));
1448 0 argv[1] = sv_2mortal(pp_closure(aTHX_ pp_kw_guard, cfg));
1449 0 argv[2] = sv_2mortal(newSVpvs("Punk::Plugin::TOTP"));
1450 0 SvREFCNT_dec(pp_call(aTHX_ app, "install_kw", argv, 3));
1451 }
1452  
1453 { /* csrf awareness for the default challenge form. Punk 0.31's
1454 * on_compile is the right moment - after every keyword has
1455 * recorded - so registration order cannot matter. An older Punk
1456 * has no on_compile; there the key is read here instead, which
1457 * works when `csrf` is declared above the `plugin` line, and when
1458 * it is not, the core csrf check refuses the tokenless form's
1459 * POST loudly rather than anything failing open. */
1460 0 SV *meth = sv_2mortal(newSVpvs("on_compile"));
1461 0 SV *has = sv_2mortal(pp_call(aTHX_ app, "can", &meth, 1));
1462 0 ▶ if (SvTRUE(has)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTRUE(has)) { 0 0 0
1463 SV *argv[2];
1464 0 argv[0] = sv_2mortal(pp_closure(aTHX_ pp_oc_csrf, cfg));
1465 0 argv[1] = sv_2mortal(newSVpvs("Punk::Plugin::TOTP"));
1466 0 SvREFCNT_dec(pp_call(aTHX_ app, "on_compile", argv, 2));
1467 }
1468 0 ▶ else if (SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV
Branch: 2 branches
BranchTrueFalseTotal
else if (SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV 0 0 0
else if (SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV 0 0 0
1469 0 ▶ && hv_exists((HV *)SvRV(app), "csrf", 4))
Branch: 1 branch
BranchTrueFalseTotal
&& hv_exists((HV *)SvRV(app), "csrf", 4)) 0 0 0
1470 0 (void)hv_stores(cfg, "csrf_on", newSViv(1));
1471 }
1472 0 }
1473  
1474 #endif /* PTOTP_PLUGIN_H */
« blib/lib/Punk/Plugin/TOTP.pm ↑ Summary xs/plugin.xs »