-
Notifications
You must be signed in to change notification settings - Fork 524
/
CSRFHandlerImpl.java
381 lines (330 loc) · 12.3 KB
/
CSRFHandlerImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
* Copyright 2015 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.web.handler.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxException;
import io.vertx.core.http.Cookie;
import io.vertx.core.http.CookieSameSite;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.ext.auth.VertxContextPRNG;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.ext.web.handler.CSRFHandler;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.impl.Origin;
import io.vertx.ext.web.impl.RoutingContextInternal;
import io.vertx.ext.web.impl.Signature;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import static io.vertx.ext.auth.impl.Codec.base64UrlEncode;
/**
* @author <a href="mailto:pmlopes@gmail.com">Paulo Lopes</a>
*/
public class CSRFHandlerImpl implements CSRFHandler {
private static final Logger LOG = LoggerFactory.getLogger(CSRFHandlerImpl.class);
private final VertxContextPRNG random;
private final Signature signature;
private boolean nagHttps;
private String cookieName = DEFAULT_COOKIE_NAME;
private String cookiePath = DEFAULT_COOKIE_PATH;
private String headerName = DEFAULT_HEADER_NAME;
private long timeout = SessionHandler.DEFAULT_SESSION_TIMEOUT;
private Origin origin;
private boolean httpOnly;
private boolean cookieSecure;
public CSRFHandlerImpl(final Vertx vertx, final String secret) {
random = VertxContextPRNG.current(vertx);
signature = new Signature(secret);
}
@Override
public CSRFHandler setOrigin(String origin) {
this.origin = Origin.parse(origin);
return this;
}
@Override
public CSRFHandler setCookieName(String cookieName) {
this.cookieName = cookieName;
return this;
}
@Override
public CSRFHandler setCookiePath(String cookiePath) {
this.cookiePath = cookiePath;
return this;
}
@Override
public CSRFHandler setCookieHttpOnly(boolean httpOnly) {
this.httpOnly = httpOnly;
return this;
}
@Override
public CSRFHandler setCookieSecure(boolean secure) {
this.cookieSecure = secure;
return this;
}
@Override
public CSRFHandler setHeaderName(String headerName) {
this.headerName = headerName;
return this;
}
@Override
public CSRFHandler setTimeout(long timeout) {
this.timeout = timeout;
return this;
}
@Override
public CSRFHandler setNagHttps(boolean nag) {
this.nagHttps = nag;
return this;
}
private String generateToken(RoutingContext ctx) {
byte[] salt = new byte[32];
random.nextBytes(salt);
String saltPlusToken = base64UrlEncode(salt) + "." + System.currentTimeMillis();
final String token = signature.sign(saltPlusToken);
// a new token was generated add it to the cookie
ctx.response()
.addCookie(
Cookie.cookie(cookieName, token)
.setPath(cookiePath)
.setHttpOnly(httpOnly)
.setSecure(cookieSecure)
// it's not an option to change the same site policy
.setSameSite(CookieSameSite.STRICT));
// only add the token to the session when the request ends successfully, doing this avoids storing a token that
// may due to error not make it to the browser. It is assumed that the token placed onto the context directly
// would only be returned to the user if the request completed successfully, thus they will remain in sync
ctx.addEndHandler(sessionTokenEndHandler(ctx, token));
return token;
}
private Handler<AsyncResult<Void>> sessionTokenEndHandler(RoutingContext ctx, String token) {
return ar -> {
if (ar.succeeded() && ctx.session() != null) {
Session session = ctx.session();
session.put(headerName, session.id() + "/" + token);
}
};
}
private String getTokenFromSession(RoutingContext ctx) {
Session session = ctx.session();
if (session == null) {
return null;
}
// get the token from the session
String sessionToken = session.get(headerName);
if (sessionToken != null) {
// attempt to parse the value
int idx = sessionToken.indexOf('/');
if (idx != -1 && session.id() != null && session.id().equals(sessionToken.substring(0, idx))) {
return sessionToken.substring(idx + 1);
}
}
// fail
return null;
}
/**
* Check if a string is null or empty (including containing only spaces)
*
* @param s Source string
* @return TRUE if source string is null or empty (including containing only spaces)
*/
private static boolean isBlank(String s) {
return s == null || s.trim().isEmpty();
}
private static long parseLong(String s) {
if (isBlank(s)) {
return -1;
}
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
LOG.trace("Invalid Token format", e);
// fallback as the token is expired
return -1;
}
}
private boolean isValidRequest(RoutingContext ctx) {
/* Verifying CSRF token using "Double Submit Cookie" approach */
final Cookie cookie = ctx.request().getCookie(cookieName);
String header = ctx.request().getHeader(headerName);
if (header == null) {
// fallback to form attributes
if (ctx.body().available()) {
header = ctx.request().getFormAttribute(headerName);
} else {
ctx.fail(new VertxException("BodyHandler is required to process POST requests", true));
return false;
}
}
// both the header and the cookie must be present, not null and not empty
if (header == null || cookie == null || isBlank(header)) {
ctx.fail(403, new IllegalArgumentException("Token provided via HTTP Header/Form is absent/empty"));
return false;
}
final String cookieValue = cookie.getValue();
if (cookieValue == null || isBlank(cookieValue)) {
ctx.fail(403, new IllegalArgumentException("Token provided via HTTP Header/Form is absent/empty"));
return false;
}
final byte[] headerBytes = header.getBytes(StandardCharsets.UTF_8);
final byte[] cookieBytes = cookieValue.getBytes(StandardCharsets.UTF_8);
//Verify that token from header and one from cookie are the same
if (!MessageDigest.isEqual(headerBytes, cookieBytes)) {
ctx.fail(403, new IllegalArgumentException("Token provided via HTTP Header and via Cookie are not equal"));
return false;
}
final Session session = ctx.session();
if (session != null) {
// get the token from the session
String sessionToken = session.get(headerName);
if (sessionToken != null) {
// attempt to parse the value
int idx = sessionToken.indexOf('/');
if (idx != -1 && session.id() != null && session.id().equals(sessionToken.substring(0, idx))) {
String challenge = sessionToken.substring(idx + 1);
// the challenge must match the user-agent input
if (!MessageDigest.isEqual(challenge.getBytes(StandardCharsets.UTF_8), headerBytes)) {
ctx.fail(403, new IllegalArgumentException("Token has been used or is outdated"));
return false;
}
} else {
ctx.fail(403, new IllegalArgumentException("Token has been issued for a different session"));
return false;
}
} else {
ctx.fail(403, new IllegalArgumentException("No Token has been added to the session"));
return false;
}
}
if (!signature.verify(header)) {
ctx.fail(403, new IllegalArgumentException("Token signature does not match"));
return false;
}
// if the token has expired remove the token from the session so that a new one can be acquired by a fresh GET
// provided the user is authenticated.
// We cannot simply remove it before these checks as this will invalidate the token even if the response is never
// written, requiring the user to GET another token even though the previous was valid
String[] tokens = header.split("\\.");
if (tokens.length != 3) {
if (session != null) {
session.remove(headerName);
}
ctx.fail(403);
return false;
}
final long ts = parseLong(tokens[1]);
if (ts == -1) {
if (session != null) {
session.remove(headerName);
}
ctx.fail(403);
return false;
}
// validate validity
if (System.currentTimeMillis() > ts + timeout) {
if (session != null) {
session.remove(headerName);
}
ctx.fail(403, new IllegalArgumentException("CSRF validity expired"));
return false;
}
return true;
}
@Override
public void handle(RoutingContext ctx) {
// we need to keep state since we can be called again on reroute
if (!((RoutingContextInternal) ctx).seenHandler(RoutingContextInternal.CSRF_HANDLER)) {
((RoutingContextInternal) ctx).visitHandler(RoutingContextInternal.CSRF_HANDLER);
} else {
ctx.next();
return;
}
if (nagHttps) {
String uri = ctx.request().absoluteURI();
if (uri != null && !uri.startsWith("https:")) {
LOG.trace("Using session cookies without https could make you susceptible to session hijacking: " + uri);
}
}
HttpMethod method = ctx.request().method();
Session session = ctx.session();
// if we're being strict with the origin
// ensure that they are always valid
if (!Origin.check(origin, ctx)) {
ctx.fail(403, new VertxException("Invalid Origin", true));
return;
}
switch (method.name()) {
case "GET":
final String token;
if (session == null) {
// if there's no session to store values, tokens are issued on every request
token = generateToken(ctx);
} else {
// get the token from the session, this also considers the fact
// that the token might be invalid as it was issued for a previous session id
// session id's change on session upgrades (unauthenticated -> authenticated; role change; etc...)
String sessionToken = getTokenFromSession(ctx);
// when there's no token in the session, then we behave just like when there is no session
// create a new token, but we also store it in the session for the next runs
if (sessionToken == null) {
token = generateToken(ctx);
} else {
String[] parts = sessionToken.split("\\.");
final long ts = parseLong(parts[1]);
if (ts == -1) {
// fallback as the token is expired
token = generateToken(ctx);
} else {
if (!(System.currentTimeMillis() > ts + timeout)) {
// we're still on the same session, no need to regenerate the token
// also note that the token isn't expired, so it can be reused
token = sessionToken;
// in this case specifically we don't issue the token as it is unchanged
// the user agent still has it from the previous interaction.
} else {
// fallback as the token is expired
token = generateToken(ctx);
}
}
}
}
// put the token in the context for users who prefer to render the token directly on the HTML
ctx.put(headerName, token);
ctx.next();
break;
case "POST":
case "PUT":
case "DELETE":
case "PATCH":
if (isValidRequest(ctx)) {
// it matches, so refresh the token to avoid replay attacks
token = generateToken(ctx);
// put the token in the context for users who prefer to
// render the token directly on the HTML
ctx.put(headerName, token);
ctx.next();
}
break;
default:
// ignore other methods
ctx.next();
break;
}
}
}