LoginSelectorHandler.java
24.4 KB
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* javax.servlet.http.HttpServletRequest
* javax.servlet.http.HttpServletResponse
* javax.servlet.http.HttpServletResponseWrapper
* org.apache.commons.collections.CollectionUtils
* org.apache.commons.collections.Predicate
* org.apache.commons.lang.ArrayUtils
* org.apache.commons.lang.StringEscapeUtils
* org.apache.commons.lang.StringUtils
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Deactivate
* org.apache.felix.scr.annotations.Modified
* org.apache.felix.scr.annotations.Properties
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.ReferenceCardinality
* org.apache.felix.scr.annotations.ReferencePolicy
* org.apache.sling.api.resource.LoginException
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ResourceResolverFactory
* org.apache.sling.api.resource.ResourceUtil
* org.apache.sling.auth.core.AuthUtil
* org.apache.sling.auth.core.spi.AuthenticationHandler
* org.apache.sling.auth.core.spi.AuthenticationHandler$FAILURE_REASON_CODES
* org.apache.sling.auth.core.spi.AuthenticationInfo
* org.osgi.framework.BundleContext
* org.osgi.framework.ServiceRegistration
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.auth.impl;
import com.day.cq.auth.impl.CugSupport;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.auth.core.AuthUtil;
import org.apache.sling.auth.core.spi.AuthenticationHandler;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6.
*/
@Component(label="%auth.loginselector.name", description="%auth.loginselector.description", name="com.day.cq.auth.impl.LoginSelectorHandler", metatype=1)
@Properties(value={@Property(name="path", value={"/"}), @Property(name="service.ranking", intValue={5000}, propertyPrivate=0), @Property(name="auth.loginselector.mappings", label="%auth.loginselector.mappings.name", description="%auth.loginselector.mappings.description", cardinality=100), @Property(name="auth.loginselector.changepw.mappings", label="%auth.loginselector.changepw.mappings.name", description="%auth.loginselector.changepw.mappings.description", cardinality=100), @Property(name="auth.loginselector.defaultloginpage", label="%auth.loginselector.defaultloginpage.name", description="%auth.loginselector.defaultloginpage.description", value={"/libs/cq/core/content/login"}), @Property(name="auth.loginselector.defaultchangepwpage", label="%auth.loginselector.defaultchangepwpage.name", description="%auth.loginselector.defaultchangepwpage.description", value={"/libs/granite/core/content/changepassword"})})
public class LoginSelectorHandler
implements AuthenticationHandler {
@Property(name="service.description")
private static final String DESCRIPTION = "Day CQ Login Selector Authentication Handler";
static final String PROPERTY_MAPPINGS_NAME = "auth.loginselector.mappings";
static final String PROPERTY_CHANGE_PW_MAPPINGS_NAME = "auth.loginselector.changepw.mappings";
static final String PROPERTY_DEFAULT_LOGIN_PAGE_NAME = "auth.loginselector.defaultloginpage";
static final String PROPERTY_DEFAULT_CHANGE_PW_PAGE_NAME = "auth.loginselector.defaultchangepwpage";
private static final String PAR_LOOP_PROTECT = "$$login$$";
private static final String[] DEFAULT_HANDLE_REGEXP = new String[]{"html", "htm"};
private static final boolean DEFAULT_HANDLE_ALL_EXTENSIONS = false;
@Property(cardinality=2000, value={"html", "htm"})
private static final String PROPERTY_HANDLE_REGEXP = "auth.loginselector.handle";
@Property(boolValue={0})
private static final String PROPERTY_HANDLE_ALL_EXTENSIONS = "auth.loginselector.handle.all.extensions";
@Reference
private ResourceResolverFactory resourceResolverFactory;
@Reference(cardinality=ReferenceCardinality.OPTIONAL_UNARY, policy=ReferencePolicy.DYNAMIC)
private volatile CugSupport cugSupport;
private final Logger log = LoggerFactory.getLogger(LoginSelectorHandler.class);
private String[] handleExtensions;
private Boolean allowAllExtensions;
private List<Mapping> loginMappings;
private List<Mapping> changePasswordMappings;
private String defaultLoginPath;
private String defaultChangePasswordPath;
private BundleContext bundleContext;
private Map<String, Object> properties;
private ServiceRegistration registration;
public AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response) {
return null;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
block11 : {
if (this.isRequestIgnored(request)) {
this.log.debug("requestCredentials: Not requesting credentials for this request");
return false;
}
if (this.isRequestForbidden(request)) {
this.log.debug("requestCredentials: Access forbidden");
request.setAttribute("j_reason", (Object)"Authentication Failed");
AuthUtil.sendInvalid((HttpServletRequest)request, (HttpServletResponse)response);
return true;
}
if (request.getParameter("$$login$$") != null) {
this.log.error("requestCredentials: Abort login due to apparent misconfiguration.");
this.log.error("requestCredentials: Possible reasons: login page not existing or not accessible");
request.setAttribute("j_reason", (Object)"Authentication Failed");
AuthUtil.sendInvalid((HttpServletRequest)request, (HttpServletResponse)response);
return true;
}
String reason = LoginSelectorHandler.getReason(request, "j_reason");
String reasonCode = LoginSelectorHandler.getReason(request, "j_reason_code");
ResourceResolver resolver = null;
try {
resolver = this.resourceResolverFactory.getAdministrativeResourceResolver(null);
String path = this.getMappingPage(request, resolver, reason);
if (!StringUtils.isNotBlank((String)path)) break block11;
path = this.rewrite(request, resolver, path);
LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
params.put("resource", AuthUtil.getLoginResource((HttpServletRequest)request, (String)null));
params.put("$$login$$", "$$login$$");
params.put("j_reason", reason);
params.put("j_reason_code", reasonCode);
try {
this.log.debug("redirected user to [{}] for request [{}].", (Object)path, (Object)request.getRequestURI());
AuthUtil.sendRedirect((HttpServletRequest)request, (HttpServletResponse)new IESaveRedirectSupportResponse(request, response), (String)path, params);
}
catch (IOException e2) {
this.log.error("Failed to redirect to the login / change password form [{}]", (Object)path, (Object)e2);
}
boolean e2 = true;
return e2;
}
catch (LoginException le) {
this.log.error("Unable to get admin resource resolver.", (Throwable)le);
}
finally {
if (resolver != null) {
resolver.close();
}
}
}
this.log.debug("no login mapping or default login page defined, not redirecting.");
return false;
}
private String rewrite(HttpServletRequest request, ResourceResolver resolver, String path) {
String target = StringUtils.endsWith((String)path, (String)".html") ? path : path.concat(".html");
return resolver.map(request, target);
}
public void dropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
}
@Activate
private void activate(BundleContext bundleContext, Map<String, Object> properties) {
this.bundleContext = bundleContext;
this.configure(bundleContext, properties);
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
@Modified
private void configure(BundleContext context, Map<String, Object> config) {
HashMap<String, Object> properties = config != null ? config : new HashMap<String, Object>();
String defaultLoginPath = OsgiUtil.toString(properties.get("auth.loginselector.defaultloginpage"), null);
this.log.debug("configure: defaultLoginPath={}", (Object)(defaultLoginPath == null ? "-" : defaultLoginPath));
String defaultChangePasswordPath = OsgiUtil.toString(properties.get("auth.loginselector.defaultchangepwpage"), null);
this.log.debug("configure: defaultChangePasswordPath={}", (Object)(defaultChangePasswordPath == null ? "-" : defaultChangePasswordPath));
boolean allowAllExtensions = OsgiUtil.toBoolean(properties.get("auth.loginselector.handle.all.extensions"), false);
this.log.debug("configure: auth.loginselector.handle.all.extensions={}", (Object)allowAllExtensions);
String[] handleExtensions = DEFAULT_HANDLE_REGEXP;
if (!allowAllExtensions) {
handleExtensions = LoginSelectorHandler.getValidatedExtensions(OsgiUtil.toStringArray(properties.get("auth.loginselector.handle")));
if (handleExtensions.length == 0) {
handleExtensions = DEFAULT_HANDLE_REGEXP;
}
this.log.debug("configure: auth.loginselector.handle={}", Arrays.asList(handleExtensions));
}
if (null != this.registration) {
this.registration.unregister();
this.registration = null;
}
this.properties = properties;
this.handleExtensions = handleExtensions;
this.loginMappings = this.getMappings(properties, "auth.loginselector.mappings");
this.changePasswordMappings = this.getMappings(properties, "auth.loginselector.changepw.mappings");
this.allowAllExtensions = allowAllExtensions;
this.defaultLoginPath = defaultLoginPath;
this.defaultChangePasswordPath = defaultChangePasswordPath;
ResourceResolver resolver = null;
try {
resolver = this.resourceResolverFactory.getAdministrativeResourceResolver(null);
this.registration = this.bundleContext.registerService(AuthenticationHandler.class.getName(), (Object)this, this.getProperties(resolver));
}
catch (LoginException le) {
this.log.error("Unable to get admin resource resolver.", (Throwable)le);
}
finally {
if (resolver != null) {
resolver.close();
}
}
}
private List<Mapping> getMappings(Map<String, Object> config, String configMappingsKey) {
String[] entries;
ArrayList<Mapping> mappings = new ArrayList<Mapping>();
for (String entry : entries = OsgiUtil.toStringArray(config.get(configMappingsKey), new String[0])) {
Mapping mapping = Mapping.create(entry);
if (mapping != null) {
mappings.add(mapping);
this.log.info("configure: added mapping [{}] from service config.", (Object)mapping);
continue;
}
this.log.warn("configure: invalid mapping [{}] defined in service configuration.", (Object)entry);
}
return mappings;
}
private static String getReason(HttpServletRequest request, String parameter) {
Object reason = request.getAttribute(parameter);
if (null == reason) {
reason = request.getParameter(parameter);
}
if (null == reason) {
reason = AuthenticationHandler.FAILURE_REASON_CODES.UNKNOWN;
}
return reason instanceof Enum ? ((Enum)reason).name().toLowerCase() : reason.toString();
}
private static String[] getValidatedExtensions(String[] handleExtensions) {
Object[] extensions = new String[]{};
if (null != handleExtensions) {
for (String ext : handleExtensions) {
if (ext == null) continue;
extensions = (String[])ArrayUtils.add((Object[])extensions, (Object)ext);
}
}
return extensions;
}
@Deactivate
private void deactivate(BundleContext bundleContext) {
if (this.registration != null) {
this.registration.unregister();
this.registration = null;
}
}
private boolean isRequestIgnored(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
if (userAgent == null || !userAgent.contains("Mozilla") && !userAgent.contains("Opera")) {
this.log.debug("ignoreRequest: Ignoring non-browser request from User-Agent {}", (Object)(userAgent == null ? "unknown" : userAgent));
return true;
}
return false;
}
private boolean isRequestForbidden(HttpServletRequest request) {
String[] handleExtensions;
String pathInfo = request.getPathInfo();
String method = request.getMethod();
String requestUri = request.getRequestURI();
if (!("GET".equals(method) || "HEAD".equals(method) || "POST".equals(method) && requestUri.endsWith("/j_security_check"))) {
this.log.debug("ignoreRequest: Ignoring non-GET request {} {}", (Object)method, (Object)(pathInfo == null ? "" : pathInfo));
return true;
}
if (request.getHeader("Referer") == null) {
this.log.debug("ignoreRequest: Handle request {} without referer", (Object)request.getRequestURI());
return false;
}
if (pathInfo == null || pathInfo.length() == 0 || pathInfo.endsWith("/")) {
this.log.debug("ignoreRequest: Handle request {} without extension", (Object)(pathInfo == null ? "" : pathInfo));
return false;
}
String ext = LoginSelectorHandler.findResourceExtension(pathInfo);
if (ext.length() == 0) {
this.log.debug("ignoreRequest: Handle request {} without extension", (Object)pathInfo);
return false;
}
if (this.allowAllExtensions.booleanValue()) {
this.log.debug("ignoreRequest: Extension {} of request {} is being handled", (Object)ext, (Object)pathInfo);
return false;
}
for (String handleExtension : handleExtensions = this.handleExtensions) {
if (!ext.equals(handleExtension)) continue;
this.log.debug("ignoreRequest: Extension {} of request {} is being handled", (Object)ext, (Object)pathInfo);
return false;
}
this.log.debug("ignoreRequest: Extension {} of request {} is not handled", (Object)ext, (Object)pathInfo);
return true;
}
private static String findResourceExtension(String pathInfo) {
if (pathInfo == null) {
return "";
}
int lastSlash = pathInfo.lastIndexOf(47);
String lastPart = pathInfo.substring(lastSlash + 1);
int lastDot = lastPart.lastIndexOf(46);
return lastDot < 0 ? "" : lastPart.substring(lastDot + 1);
}
private String getCugRootLoginPage(HttpServletRequest request) {
CugSupport cugSupport = this.cugSupport;
if (cugSupport != null) {
return cugSupport.getLoginPage(request);
}
return null;
}
private String getMappingPage(final HttpServletRequest request, ResourceResolver resolver, String reason) {
Mapping mapping;
List<Mapping> mappings;
String defaultPath;
String path = null;
if ("password_expired".equals(reason)) {
mappings = this.changePasswordMappings;
defaultPath = this.defaultChangePasswordPath;
} else {
mappings = this.loginMappings;
path = this.getCugRootLoginPage(request);
String string = defaultPath = null != this.defaultLoginPath ? this.defaultLoginPath : "/system/sling/cqform/defaultlogin";
}
if (null == path && (mapping = (Mapping)CollectionUtils.find(mappings, (Predicate)new Predicate(){
public boolean evaluate(Object object) {
Mapping m = (Mapping)object;
return m.handles(request.getRequestURI());
}
})) != null) {
this.log.debug("found mapping [{}] for request [{}].", (Object)mapping, (Object)request.getRequestURI());
String p = mapping.getLoginPath();
if (this.resolve(resolver, p) != null) {
path = p;
}
}
if (null == path && null != this.resolve(resolver, defaultPath)) {
this.log.debug("requestCredentials: using default login page [{}] for request [{}].", (Object)defaultPath, (Object)request.getRequestURI());
path = defaultPath;
}
return path;
}
private Dictionary<String, Object> getProperties(ResourceResolver resolver) {
Hashtable<String, Object> newProps = new Hashtable<String, Object>();
for (String key : this.properties.keySet()) {
newProps.put(key, this.properties.get(key));
}
HashSet<String> authReqs = new HashSet<String>();
if (StringUtils.isNotBlank((String)this.defaultLoginPath)) {
authReqs.add("-" + this.toRawPath(resolver, this.defaultLoginPath));
}
if (StringUtils.isNotBlank((String)this.defaultChangePasswordPath)) {
authReqs.add("-" + this.toRawPath(resolver, this.defaultChangePasswordPath));
}
ArrayList<Mapping> authReqMappings = new ArrayList<Mapping>();
authReqMappings.addAll(this.loginMappings);
authReqMappings.addAll(this.changePasswordMappings);
for (Mapping m : authReqMappings) {
authReqs.add("-" + this.toRawPath(resolver, m.getLoginPath()));
}
newProps.put("sling.auth.requirements", authReqs.toArray(new String[authReqs.size()]));
return newProps;
}
private String toRawPath(ResourceResolver resolver, String path) {
Resource loginPageResource = this.resolve(resolver, path);
if (loginPageResource != null) {
return resolver.map(loginPageResource.getPath());
}
return path;
}
private Resource resolve(ResourceResolver resolver, String path) {
Resource loginPageResource = resolver.resolve(path);
if (!ResourceUtil.isNonExistingResource((Resource)loginPageResource)) {
return loginPageResource;
}
return null;
}
protected void bindResourceResolverFactory(ResourceResolverFactory resourceResolverFactory) {
this.resourceResolverFactory = resourceResolverFactory;
}
protected void unbindResourceResolverFactory(ResourceResolverFactory resourceResolverFactory) {
if (this.resourceResolverFactory == resourceResolverFactory) {
this.resourceResolverFactory = null;
}
}
protected void bindCugSupport(CugSupport cugSupport) {
this.cugSupport = cugSupport;
}
protected void unbindCugSupport(CugSupport cugSupport) {
if (this.cugSupport == cugSupport) {
this.cugSupport = null;
}
}
private static class IESaveRedirectSupportResponse
extends HttpServletResponseWrapper {
final HttpServletRequest request;
public IESaveRedirectSupportResponse(HttpServletRequest request, HttpServletResponse response) {
super(response);
this.request = request;
}
private boolean isFragmentHandleRequired() {
String userAgent = this.request.getHeader("User-Agent");
String extension = LoginSelectorHandler.findResourceExtension(this.request.getPathInfo()).toLowerCase();
if ((extension.equals("html") || extension.equals("htm")) && userAgent != null && userAgent.indexOf("MSIE") != -1) {
int version;
String regex = "MSIE ([0-9]{1,})";
Pattern p = Pattern.compile("MSIE ([0-9]{1,})");
Matcher m = p.matcher(userAgent);
if (m.find() && (version = Integer.parseInt(m.group(1).trim())) <= 9) {
return true;
}
}
return false;
}
public void sendRedirect(String location) throws IOException {
if (this.isFragmentHandleRequired()) {
this.setStatus(200);
this.setContentType("text/html");
this.setCharacterEncoding("UTF-8");
this.setHeader("Cache-control", "no-cache");
this.addHeader("Cache-control", "no-store");
this.setHeader("Dispatcher", "no-cache");
this.setHeader("Pragma", "no-cache");
this.setHeader("Expires", "0");
PrintWriter w = this.getWriter();
w.write("<html><head><script type=\"text/javascript\">");
w.write("var u=\"");
w.write(StringEscapeUtils.escapeJavaScript((String)location));
w.write("\"; if ( window.location.hash) {");
w.write("u = u + window.location.hash;");
w.write("} document.location = u;");
w.write("</script></head><body>");
w.write("<!-- QUICKSTART_HOMEPAGE - (string used for readyness detection, do not remove) -->");
w.write("</body></html>");
w.flush();
this.flushBuffer();
} else {
super.sendRedirect(location);
}
}
}
private static final class Mapping {
private String loginPath;
private String treePath;
static Mapping create(String s) {
String[] segments = StringUtils.split((String)s, (char)':');
if (segments.length == 2) {
return new Mapping(segments[0], segments[1]);
}
return null;
}
private Mapping(String loginPath, String treePath) {
this.loginPath = loginPath;
this.treePath = treePath;
}
public String getLoginPath() {
return this.loginPath;
}
public String getTreePath() {
return this.treePath;
}
public String toString() {
return "Mapping{loginPath='" + this.loginPath + '\'' + ", treePath='" + this.treePath + '\'' + '}';
}
public boolean handles(String requestURI) {
return StringUtils.startsWith((String)requestURI, (String)this.getTreePath());
}
}
}