include/psaml/psaml_request.h

filter: Statementstmt 97.0% 162 / 167 Branchbran 77.6% 73 / 94 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 90.0% 235 / 261 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/psaml/psaml_idp.h ↑ Summary include/psaml/psaml_xml.h »
1 #ifndef PSAML_REQUEST_H
2 #define PSAML_REQUEST_H
3  
4 /* The AuthnRequest, the HTTP-Redirect binding, and the signature over it.
5 *
6 * Assembled as a string rather than built as a tree. The phase-1 parser is
7 * a reader; this dist writes three small fixed documents and a general
8 * serialiser would be more code than the plugin. What that needs from XML
9 * is one escape, and psaml_xml.h has it.
10 *
11 * Must be included after psaml_b64.h, psaml_deflate.h, psaml_time.h,
12 * psaml_xml.h and psaml_boot.h. */
13  
14 #include "psaml_abi.h"
15 #include "psaml_b64.h"
16 #include "psaml_deflate.h"
17 #include "psaml_time.h"
18 #include "psaml_xml.h"
19 #include "psaml_error.h"
20  
21 #define PSAML_BIND_POST \
22 "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
23 #define PSAML_SIGALG_RSA_SHA256 \
24 "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
25 #define PSAML_SIGALG_ECDSA_SHA256 \
26 "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
27  
28 /* ---- the request id --------------------------------------------------- */
29  
30 /* An underscore and 32 hex characters.
31 *
32 * The underscore is not decoration. The ID attribute is xs:ID, whose
33 * lexical space is an XML Name, and an XML Name may not begin with a
34 * digit. A provider that validates the schema refuses a request whose ID
35 * does, and half of a random hex string starts with one, so the failure
36 * would be intermittent and look like anything but this. */
37 84 PERL_STATIC_INLINE SV *psaml_request_id(pTHX) {
38 static const char hex[] = "0123456789abcdef";
39 84 SV *raw = psaml_jws(aTHX)->random_bytes(aTHX_ 16);
40 SV *out;
41 STRLEN n, i;
42 const unsigned char *p;
43 84 ▶ if (!raw) croak("%s: the CSPRNG failed", PSAML_WHO);
Branch: 1 branch
BranchTrueFalseTotal
if (!raw) croak("%s: the CSPRNG failed", PSAML_WHO); 0 84 84
44 84 p = (const unsigned char *)SvPVbyte(raw, n);
45 84 out = newSVpvs("_");
46 1428 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 1344 84 1428
47 char pair[2];
48 1344 pair[0] = hex[(p[i] >> 4) & 0xF];
49 1344 pair[1] = hex[p[i] & 0xF];
50 1344 sv_catpvn(out, pair, 2);
51 }
52 84 SvREFCNT_dec(raw);
53 84 return out;
54 }
55  
56 /* ---- the one URL encoder ---------------------------------------------- */
57  
58 /* RFC 3986 unreserved passed through, everything else percent-encoded with
59 * UPPER-case hex.
60 *
61 * There is exactly one of these, and that is the point rather than an
62 * economy. The redirect signature is computed over the query string AS
63 * SENT, so the bytes that are signed and the bytes that go out must come
64 * from the same function. Encoders disagree about `~` (RFC 2396 escaped
65 * it, RFC 3986 does not), about space as `+` or `%20`, and about the case
66 * of the hex digits; any of those differences produces a signature the
67 * provider cannot reproduce, and what it reports is "invalid signature"
68 * with no indication that the disagreement is about a tilde. */
69 91 PERL_STATIC_INLINE void psaml_urlenc_cat(pTHX_ SV *out, const char *in,
70 STRLEN n) {
71 static const char hex[] = "0123456789ABCDEF";
72 STRLEN i;
73 26711 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 26620 91 26711
74 26620 unsigned char c = (unsigned char)in[i];
75 26620 ▶ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
Branch: 4 branches
BranchTrueFalseTotal
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') 21733 4887 26620
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') 9921 11812 21733
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') 9881 4927 14808
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') 2 9879 9881
76 4929 ▶ || (c >= '0' && c <= '9')
Branch: 2 branches
BranchTrueFalseTotal
|| (c >= '0' && c <= '9') 4771 158 4929
|| (c >= '0' && c <= '9') 61 4710 4771
77 219 ▶ || c == '-' || c == '_' || c == '.' || c == '~') {
Branch: 4 branches
BranchTrueFalseTotal
|| c == '-' || c == '_' || c == '.' || c == '~') { 214 5 219
|| c == '-' || c == '_' || c == '.' || c == '~') { 174 40 214
|| c == '-' || c == '_' || c == '.' || c == '~') { 169 5 174
|| c == '-' || c == '_' || c == '.' || c == '~') { 1 168 169
78 26452 sv_catpvn(out, (const char *)&c, 1);
79 }
80 else {
81 char esc[3];
82 168 esc[0] = '%';
83 168 esc[1] = hex[(c >> 4) & 0xF];
84 168 esc[2] = hex[c & 0xF];
85 168 sv_catpvn(out, esc, 3);
86 }
87 }
88 91 }
89  
90 91 PERL_STATIC_INLINE SV *psaml_urlenc(pTHX_ SV *sv) {
91 STRLEN n;
92 91 const char *p = SvPVbyte(sv, n);
93 91 SV *out = newSVpvs("");
94 91 psaml_urlenc_cat(aTHX_ out, p, n);
95 91 return out;
96 }
97  
98 /* ---- the document ----------------------------------------------------- */
99  
100 354 PERL_STATIC_INLINE void psaml_cat_escaped(pTHX_ SV *out, SV *v) {
101 STRLEN n, need;
102 const char *p;
103 char *dst;
104 STRLEN wrote, cur;
105 354 ▶ if (!v || !SvOK(v)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!v || !SvOK(v)) return; 354 0 354
if (!v || !SvOK(v)) return; 0 354 354
106 354 p = SvPVbyte(v, n);
107 354 need = psaml_xml_escaped_max(n);
108 354 cur = SvCUR(out);
109 354 ▶ dst = SvGROW(out, cur + need + 1) + cur;
Branch: 2 branches
BranchTrueFalseTotal
dst = SvGROW(out, cur + need + 1) + cur; 354 0 354
dst = SvGROW(out, cur + need + 1) + cur; 319 35 354
110 354 wrote = psaml_xml_escape(dst, p, n);
111 354 SvCUR_set(out, cur + wrote);
112 354 *SvEND(out) = '\0';
113 }
114  
115 311 PERL_STATIC_INLINE void psaml_cat_attr(pTHX_ SV *out, const char *name,
116 SV *v) {
117 311 sv_catpvs(out, " ");
118 311 sv_catpv(out, name);
119 311 sv_catpvs(out, "=\"");
120 311 psaml_cat_escaped(aTHX_ out, v);
121 311 sv_catpvs(out, "\"");
122 311 }
123  
124 /* The AuthnRequest. `id` and `instant` are passed in rather than made
125 * here, because the caller has to keep the id in the flow record and the
126 * test has to be able to pin the instant. */
127 42 PERL_STATIC_INLINE SV *psaml_authn_request(pTHX_ SV *id, SV *instant,
128 SV *destination, SV *acs_url,
129 SV *issuer, SV *name_id_format,
130 int force_authn) {
131 42 SV *out = newSVpvs(
132 "<samlp:AuthnRequest"
133 " xmlns:samlp=\"" PSAML_NS_PROTOCOL "\""
134 " xmlns:saml=\"" PSAML_NS_ASSERTION "\"");
135 42 psaml_cat_attr(aTHX_ out, "ID", id);
136 42 sv_catpvs(out, " Version=\"2.0\"");
137 42 psaml_cat_attr(aTHX_ out, "IssueInstant", instant);
138 /* Destination is the SSO URL as configured, copied and never derived:
139 * some providers compare it against the URL they received the request
140 * on and refuse a mismatch. */
141 42 psaml_cat_attr(aTHX_ out, "Destination", destination);
142 42 psaml_cat_attr(aTHX_ out, "AssertionConsumerServiceURL", acs_url);
143 42 sv_catpvs(out, " ProtocolBinding=\"" PSAML_BIND_POST "\"");
144 /* ForceAuthn only when true: providers differ on whether they read a
145 * literal "false", and the default is what everyone tests against. */
146 42 ▶ if (force_authn) sv_catpvs(out, " ForceAuthn=\"true\"");
Branch: 1 branch
BranchTrueFalseTotal
if (force_authn) sv_catpvs(out, " ForceAuthn=\"true\""); 1 41 42
147 42 sv_catpvs(out, ">");
148  
149 42 sv_catpvs(out, "<saml:Issuer>");
150 42 psaml_cat_escaped(aTHX_ out, issuer);
151 42 sv_catpvs(out, "</saml:Issuer>");
152  
153 /* NameIDPolicy only when asked for. A policy the provider cannot
154 * satisfy comes back as a Responder status and a failed login with
155 * nothing useful in it; letting the provider choose is what works
156 * everywhere. */
157 42 ▶ if (name_id_format && SvOK(name_id_format) && SvCUR(name_id_format)) {
Branch: 3 branches
BranchTrueFalseTotal
if (name_id_format && SvOK(name_id_format) && SvCUR(name_id_format)) { 1 41 42
if (name_id_format && SvOK(name_id_format) && SvCUR(name_id_format)) { 1 0 1
if (name_id_format && SvOK(name_id_format) && SvCUR(name_id_format)) { 1 0 1
158 1 sv_catpvs(out, "<samlp:NameIDPolicy");
159 1 psaml_cat_attr(aTHX_ out, "Format", name_id_format);
160 1 sv_catpvs(out, " AllowCreate=\"true\"/>");
161 }
162  
163 42 sv_catpvs(out, "</samlp:AuthnRequest>");
164 42 return out;
165 }
166  
167 /* ---- the redirect binding --------------------------------------------- */
168  
169 /* base64(rawdeflate(xml)), which is what SAMLRequest carries before it is
170 * URL-encoded. Raw DEFLATE with NO header: not zlib, not gzip. A header is
171 * the single most common reason a provider answers "invalid request" with
172 * no further detail. */
173 41 PERL_STATIC_INLINE SV *psaml_deflate_b64(pTHX_ SV *xml) {
174 STRLEN n, zlen, blen;
175 41 const char *p = SvPVbyte(xml, n);
176 41 SV *z = newSV(psaml_deflate_bound(n) + 1);
177 SV *out;
178 41 SvPOK_on(z);
179 41 zlen = psaml_deflate_stored((unsigned char *)SvPVX(z),
180 (const unsigned char *)p, n);
181 41 SvCUR_set(z, zlen);
182 41 *SvEND(z) = '\0';
183 41 out = newSV(psaml_b64_encoded_len(zlen) + 1);
184 41 SvPOK_on(out);
185 41 blen = psaml_b64_encode(SvPVX(out), (const unsigned char *)SvPVX(z), zlen);
186 41 SvCUR_set(out, blen);
187 41 *SvEND(out) = '\0';
188 41 SvREFCNT_dec(z);
189 41 return out;
190 }
191  
192 /* The SigAlg URI and the JWS algorithm for the SP key.
193 *
194 * Both families, because phase 2's mapping table already names both and a
195 * deployer whose SP key is EC would otherwise be stuck with a plugin that
196 * can only say rsa-sha256. RSA is what every provider expects and what
197 * `punk saml key` will make.
198 *
199 * The key type is read through Crypt::JWS's Perl surface rather than the
200 * C table, because jws_abi has no entry for it: the table can make a key
201 * from a PEM and sign with it, but it cannot say what kind of key it got.
202 * That is one extra parse per login start, which is microseconds against
203 * a redirect, and the alternative is guessing from the PEM header or
204 * signing twice to see which works. If this ever matters, a `key_kind`
205 * entry appended to jws_abi is the fix. */
206 4 PERL_STATIC_INLINE const char *psaml_sigalg_for(pTHX_ SV *pem,
207 const char **jws_alg) {
208 4 const jws_abi *J = psaml_jws(aTHX);
209 4 SV *cls = sv_2mortal(newSVpvs("Crypt::JWS::Key"));
210 SV *argv[1];
211 SV *keyobj, *kty;
212 STRLEN n, pemlen;
213 const char *p;
214 4 const char *pemp = SvPVbyte(pem, pemlen);
215 void *probe;
216  
217 /* The table's key_from_pem answers NULL rather than croaking, so the
218 * refusal is checked here and reported in this dist's words. The Perl
219 * call below croaks in Crypt::JWS's words, and a plugin that let a
220 * dependency's message reach a deployer configuring `key` would be
221 * telling them about a module they did not name. */
222 4 probe = J->key_from_pem(aTHX_ pemp, pemlen);
223 4 ▶ if (!probe)
Branch: 1 branch
BranchTrueFalseTotal
if (!probe) 1 3 4
224 1 croak("%s: `key` will not parse as a PEM private key", PSAML_WHO);
225 3 J->key_free(aTHX_ probe);
226  
227 3 argv[0] = pem;
228 3 keyobj = sv_2mortal(psaml_call(aTHX_ cls, "from_pem", argv, 1));
229 3 ▶ if (!keyobj || !SvOK(keyobj))
Branch: 2 branches
BranchTrueFalseTotal
if (!keyobj || !SvOK(keyobj)) 3 0 3
if (!keyobj || !SvOK(keyobj)) 0 3 3
230 0 croak("%s: `key` will not parse as a PEM private key", PSAML_WHO);
231 3 kty = sv_2mortal(psaml_call(aTHX_ keyobj, "kty", NULL, 0));
232 3 ▶ if (!kty || !SvOK(kty))
Branch: 2 branches
BranchTrueFalseTotal
if (!kty || !SvOK(kty)) 3 0 3
if (!kty || !SvOK(kty)) 0 3 3
233 0 croak("%s: could not read the type of `key`", PSAML_WHO);
234 3 p = SvPV_const(kty, n);
235 3 ▶ if (n == 3 && memEQ(p, "RSA", 3)) {
Branch: 2 branches
BranchTrueFalseTotal
if (n == 3 && memEQ(p, "RSA", 3)) { 2 1 3
if (n == 3 && memEQ(p, "RSA", 3)) { 2 0 2
236 2 *jws_alg = "RS256";
237 2 return PSAML_SIGALG_RSA_SHA256;
238 }
239 1 ▶ if (n == 2 && memEQ(p, "EC", 2)) {
Branch: 2 branches
BranchTrueFalseTotal
if (n == 2 && memEQ(p, "EC", 2)) { 1 0 1
if (n == 2 && memEQ(p, "EC", 2)) { 1 0 1
240 1 *jws_alg = "ES256";
241 1 return PSAML_SIGALG_ECDSA_SHA256;
242 }
243 0 croak("%s: `key` is a %.*s key; the redirect signature needs RSA or EC",
244 PSAML_WHO, (int)n, p);
245 return NULL;
246 }
247  
248 /* The signed string of Bindings 3.4.4.1.
249 *
250 * The order is fixed by the specification and RelayState is omitted
251 * ENTIRELY when there is none, rather than sent as an empty value: a
252 * provider reconstructing the string follows the same rule, and an empty
253 * `&RelayState=` between the other two is a different string.
254 *
255 * Every value is appended through the SAME encoder that builds the query,
256 * and the query is built from these bytes, so what was signed and what is
257 * sent cannot differ. */
258 4 PERL_STATIC_INLINE SV *psaml_signed_string(pTHX_ SV *enc_req, SV *enc_relay,
259 SV *enc_sigalg) {
260 4 SV *out = newSVpvs("SAMLRequest=");
261 4 sv_catsv(out, enc_req);
262 4 ▶ if (enc_relay) {
Branch: 1 branch
BranchTrueFalseTotal
if (enc_relay) { 3 1 4
263 3 sv_catpvs(out, "&RelayState=");
264 3 sv_catsv(out, enc_relay);
265 }
266 4 sv_catpvs(out, "&SigAlg=");
267 4 sv_catsv(out, enc_sigalg);
268 4 return out;
269 }
270  
271 /* The full redirect URL.
272 *
273 * `key_pem` is the SP private key in PEM, or NULL for an unsigned
274 * request. `relay` is the flow id, and it is a flow id: the
275 * return path lives in the flow record on this side, where neither the
276 * provider nor an attacker can rewrite it. */
277 40 PERL_STATIC_INLINE SV *psaml_redirect_url(pTHX_ SV *sso_url, SV *xml,
278 SV *relay, SV *key_pem) {
279 40 SV *payload = psaml_deflate_b64(aTHX_ xml);
280 40 SV *enc_req = sv_2mortal(psaml_urlenc(aTHX_ payload));
281 80 ▶ SV *enc_relay = (relay && SvOK(relay) && SvCUR(relay))
Branch: 2 branches
BranchTrueFalseTotal
SV *enc_relay = (relay && SvOK(relay) && SvCUR(relay)) 39 1 40
SV *enc_relay = (relay && SvOK(relay) && SvCUR(relay)) 39 0 39
282 80 ▶ ? sv_2mortal(psaml_urlenc(aTHX_ relay)) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
? sv_2mortal(psaml_urlenc(aTHX_ relay)) : NULL; 40 0 40
283 SV *out;
284 STRLEN sl;
285 40 const char *sp = SvPV_const(sso_url, sl);
286  
287 40 SvREFCNT_dec(payload);
288  
289 40 out = newSVpvn(sp, sl);
290 /* after `?`, or after `&` when the SSO URL already carries a query,
291 * which several providers' do */
292 40 ▶ sv_catpvn(out, memchr(sp, '?', sl) ? "&" : "?", 1);
Branch: 1 branch
BranchTrueFalseTotal
sv_catpvn(out, memchr(sp, '?', sl) ? "&" : "?", 1); 1 39 40
293 40 sv_catpvs(out, "SAMLRequest=");
294 40 sv_catsv(out, enc_req);
295 40 ▶ if (enc_relay) {
Branch: 1 branch
BranchTrueFalseTotal
if (enc_relay) { 39 1 40
296 39 sv_catpvs(out, "&RelayState=");
297 39 sv_catsv(out, enc_relay);
298 }
299  
300 40 ▶ if (key_pem && SvOK(key_pem) && SvCUR(key_pem)) {
Branch: 3 branches
BranchTrueFalseTotal
if (key_pem && SvOK(key_pem) && SvCUR(key_pem)) { 6 34 40
if (key_pem && SvOK(key_pem) && SvCUR(key_pem)) { 3 3 6
if (key_pem && SvOK(key_pem) && SvCUR(key_pem)) { 3 0 3
301 3 const jws_abi *J = psaml_jws(aTHX);
302 3 const char *jws_alg = NULL;
303 3 const char *sigalg = psaml_sigalg_for(aTHX_ key_pem, &jws_alg);
304 2 SV *sigalg_sv = sv_2mortal(newSVpv(sigalg, 0));
305 2 SV *enc_sigalg = sv_2mortal(psaml_urlenc(aTHX_ sigalg_sv));
306 2 SV *signed_str = sv_2mortal(
307 psaml_signed_string(aTHX_ enc_req, enc_relay, enc_sigalg));
308 STRLEN inlen, siglen, pemlen;
309 2 ▶ const char *inp = SvPVbyte(signed_str, inlen);
Branch: 1 branch
BranchTrueFalseTotal
const char *inp = SvPVbyte(signed_str, inlen); 2 0 2
310 2 const char *pemp = SvPVbyte(key_pem, pemlen);
311 2 void *k = J->key_from_pem(aTHX_ pemp, pemlen);
312 SV *raw;
313 2 ▶ if (!k) croak("%s: `key` will not parse as a PEM private key",
Branch: 1 branch
BranchTrueFalseTotal
if (!k) croak("%s: `key` will not parse as a PEM private key", 0 2 2
314 PSAML_WHO);
315 2 raw = J->sign(aTHX_ k, jws_alg, strlen(jws_alg),
316 (const unsigned char *)inp, inlen);
317 2 J->key_free(aTHX_ k);
318 2 ▶ if (!raw)
Branch: 1 branch
BranchTrueFalseTotal
if (!raw) 0 2 2
319 0 croak("%s: the redirect signature failed", PSAML_WHO);
320 {
321 const unsigned char *rp =
322 2 (const unsigned char *)SvPVbyte(raw, siglen);
323 2 SV *b64 = newSV(psaml_b64_encoded_len(siglen) + 1);
324 STRLEN bn;
325 2 SvPOK_on(b64);
326 2 bn = psaml_b64_encode(SvPVX(b64), rp, siglen);
327 2 SvCUR_set(b64, bn);
328 2 *SvEND(b64) = '\0';
329 2 sv_catpvs(out, "&SigAlg=");
330 2 sv_catsv(out, enc_sigalg);
331 2 sv_catpvs(out, "&Signature=");
332 {
333 2 SV *enc_sig = sv_2mortal(psaml_urlenc(aTHX_ b64));
334 2 sv_catsv(out, enc_sig);
335 }
336 2 SvREFCNT_dec(b64);
337 }
338 2 SvREFCNT_dec(raw);
339 }
340  
341 39 return out;
342 }
343  
344 /* ---- the inbound field ------------------------------------------------ */
345  
346 /* SAMLResponse as it arrives: strict base64, decoded, with the size
347 * checked BEFORE decoding.
348 *
349 * The cap is on the encoded field because that is the byte count an
350 * attacker controls at the door; checking after decoding means the
351 * allocation has already happened.
352 *
353 * Whitespace is the one leniency, because several providers wrap the
354 * base64 at 76 columns and every other implementation accepts that. The
355 * url alphabet is still refused: `-` and `_` here would mean a token from
356 * somewhere else decoded to something plausible.
357 *
358 * No inflate. The POST binding never compresses, and a Response that
359 * arrives deflated is malformed rather than clever. */
360 47 PERL_STATIC_INLINE SV *psaml_decode_field(pTHX_ SV *field, IV max_bytes) {
361 STRLEN n, out_len;
362 const char *p;
363 SV *out;
364 47 ▶ if (!field || !SvOK(field))
Branch: 2 branches
BranchTrueFalseTotal
if (!field || !SvOK(field)) 47 0 47
if (!field || !SvOK(field)) 0 47 47
365 0 psaml_throw(aTHX_ PSAML_E_BAD_BASE64, "the field was not sent");
366 47 p = SvPVbyte(field, n);
367 47 ▶ if (max_bytes > 0 && (IV)n > max_bytes)
Branch: 2 branches
BranchTrueFalseTotal
if (max_bytes > 0 && (IV)n > max_bytes) 43 4 47
if (max_bytes > 0 && (IV)n > max_bytes) 1 42 43
368 1 psaml_throw(aTHX_ PSAML_E_BAD_BASE64,
369 "the encoded field is %" UVuf " bytes, over the "
370 "max_response of %" IVdf, (UV)n, max_bytes);
371 46 out = newSV(psaml_b64_decoded_max(n) + 1);
372 46 SvPOK_on(out);
373 46 out_len = psaml_b64_decode_xml((unsigned char *)SvPVX(out), p, n);
374 46 ▶ if (out_len == (STRLEN)-1) {
Branch: 1 branch
BranchTrueFalseTotal
if (out_len == (STRLEN)-1) { 3 43 46
375 3 SvREFCNT_dec(out);
376 3 psaml_throw(aTHX_ PSAML_E_BAD_BASE64,
377 "the field is not standard base64");
378 }
379 43 SvCUR_set(out, out_len);
380 43 *SvEND(out) = '\0';
381 43 return out;
382 }
383  
384 #endif /* PSAML_REQUEST_H */
« include/psaml/psaml_idp.h ↑ Summary include/psaml/psaml_xml.h »