HTTPAuthHandler.java 19.7 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.xss.XSSAPI
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.commons.codec.binary.Base64
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.ConfigurationPolicy
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.PropertyUnbounded
 *  org.apache.felix.scr.annotations.Reference
 *  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.spi.AbstractAuthenticationHandler
 *  org.apache.sling.commons.auth.spi.AuthenticationHandler
 *  org.apache.sling.commons.auth.spi.AuthenticationInfo
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.osgi.framework.BundleContext
 *  org.osgi.framework.ServiceRegistration
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.auth.impl;

import com.adobe.granite.xss.XSSAPI;
import com.day.cq.auth.impl.CugSupport;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Reference;
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.spi.AbstractAuthenticationHandler;
import org.apache.sling.commons.auth.spi.AuthenticationHandler;
import org.apache.sling.commons.auth.spi.AuthenticationInfo;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
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(metatype=1, label="%auth.http.name", description="%auth.http.description", name="com.day.cq.wcm.foundation.impl.HTTPAuthHandler", policy=ConfigurationPolicy.REQUIRE)
@Property(name="path", value={"/"})
public class HTTPAuthHandler
implements AuthenticationHandler {
    private final Logger log;
    private static final boolean DEFAULT_NO_LOGIN_FORM = false;
    @Property(boolValue={0})
    private static final String NO_LOGIN_FORM = "auth.http.nologin";
    private static final String DEFAULT_REALM = "Day Communique 5";
    @Property(value={"Day Communique 5"})
    private static final String REALM = "auth.http.realm";
    static final String REQUEST_LOGIN_PARAMETER = "sling:authRequestLogin";
    private static final String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
    private static final String HEADER_AUTHORIZATION = "Authorization";
    private static final String AUTHENTICATION_SCHEME_BASIC = "Basic";
    private static final String DEFAULT_DEFAULT_LOGIN_PAGE = "/libs/cq/core/content/login.html";
    @Property(value={"/libs/cq/core/content/login.html"})
    private static final String PROP_DEFAULT_LOGIN_PAGE = "auth.default.loginpage";
    private static final String PROP_FORM_LOGIN = "auth.cred.form";
    @Property(name="auth.cred.form", unbounded=PropertyUnbounded.ARRAY)
    private static final String[] DEFAULT_FORM_LOGIN = new String[]{"Firefox", "Shiretoko", "MSIE 7", "MSIE 6"};
    private static final String PROP_UTF8_CREDENTIALS = "auth.cred.utf8";
    @Property(name="auth.cred.utf8", unbounded=PropertyUnbounded.ARRAY)
    private static final String[] DEFAULT_UTF8_CREDENTIALS = new String[]{"Firefox", "Shiretoko", "Chrome", "Opera", "curl", "Wget"};
    static final String LOGIN_FORCED_FLAG = "cq.authhandler.dologin";
    @Property(name="service.description", propertyPrivate=1)
    private static final String DESCRIPTION = "HTTP Basic Authentication Handler";
    @Reference
    private SlingRepository repository;
    @Reference
    private ResourceResolverFactory resolverFactory;
    @Reference
    private CugSupport cugSupport;
    @Reference
    private XSSAPI xssAPI;
    private boolean noLoginForm;
    private String realm;
    private String defaultLoginPage;
    private String[] formSupportingUserAgents;
    private String[] utf8EncodingUserAgents;
    private ServiceRegistration registration;
    private Dictionary<?, ?> props;

    public HTTPAuthHandler() {
        this.log = LoggerFactory.getLogger((String)this.getClass().getName());
    }

    public AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response) {
        AuthenticationInfo info = this.extractAuthentication(request);
        if (info != null) {
            return info;
        }
        if (this.forceAuthentication(request, response)) {
            return AuthenticationInfo.DOING_AUTH;
        }
        return null;
    }

    /*
     * Enabled aggressive block sorting
     */
    public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String lpMessage;
        String rMessage;
        String resource;
        if (response.isCommitted()) {
            this.log.error("requestAuthentication: Response is committed, cannot request authentication");
            return true;
        }
        response.resetBuffer();
        if (request.getParameter("sling:authRequestLogin") != null) {
            response.sendError(403);
            response.flushBuffer();
            return true;
        }
        if (!this.doLoginForm(request)) {
            this.log.debug("requestAuthentication: Not authenticating here because login form is disabled and cq.authhandler.dologin request attribute is not set");
            return false;
        }
        if (!this.isLoginFormClient(request)) {
            this.sendUnauthorized(request, response);
            return true;
        }
        String loginPage = this.getLoginPage(request);
        if (loginPage == null) {
            loginPage = this.getDefaultLoginPage();
            lpMessage = "requestAuthentication: Using default login page ({})";
        } else {
            lpMessage = "requestAuthentication: Using login page: {}";
        }
        if (this.isLoginFormLoop(request, loginPage)) {
            this.log.warn("requestAuthentication: Authentication loop detected, sending 401/UNAUTHENICATED to force browser based authentication");
            this.log.warn("requestAuthentication: Authentication loop reason: Wrong login page configuration or credentials not accepted for login");
            this.sendUnauthorized(request, response);
            return true;
        }
        if (request.getContextPath() != null && !loginPage.startsWith(request.getContextPath())) {
            loginPage = request.getContextPath() + loginPage;
        }
        if ((resource = request.getParameter("resource")) == null) {
            resource = request.getRequestURI();
            rMessage = "requestAuthentication: Using current request as post-login target: {}";
        } else if (!AbstractAuthenticationHandler.isRedirectValid((HttpServletRequest)request, (String)resource)) {
            resource = "/";
            rMessage = "requestAuthentication: Post-login target {} is invalid; using '/'";
        } else {
            rMessage = "requestAuthentication: Reusing post-login target from request parameter: {}";
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug(lpMessage, (Object)loginPage);
            this.log.debug(rMessage, (Object)resource);
        }
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-control", "no-cache");
        response.addHeader("Cache-control", "no-store");
        response.setHeader("Dispatcher", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        PrintWriter w = response.getWriter();
        w.write("<html><head><script type=\"text/javascript\">");
        w.write("var u=\"");
        w.write(this.xssAPI.encodeForJSString(loginPage));
        w.write("?resource=");
        w.write(this.xssAPI.encodeForJSString(resource));
        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>");
        response.flushBuffer();
        return true;
    }

    public void dropCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (request.getHeader("Authorization") != null) {
            this.requestCredentials(request, response);
        }
    }

    private String getDefaultLoginPage() {
        return this.defaultLoginPage;
    }

    private String getLoginPage(HttpServletRequest request) {
        return null;
    }

    private String getRealm(HttpServletRequest request) {
        String realm = this.cugSupport.getRealm(request);
        this.log.info("CUG realm: {}", (Object)realm);
        return realm;
    }

    public String toString() {
        return "HTTP Basic Authentication Handler";
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Activate
    protected void activate(ComponentContext componentContext) {
        this.configure(componentContext.getProperties());
        ResourceResolver unprivilegedResourceResolver = null;
        try {
            unprivilegedResourceResolver = this.resolverFactory.getResourceResolver(null);
            this.registration = componentContext.getBundleContext().registerService(AuthenticationHandler.class.getName(), (Object)this, this.getProperties(unprivilegedResourceResolver));
        }
        catch (LoginException re) {
            this.log.error("bindRepository: Failed logging in, cannot handle Closed User Groups", (Throwable)re);
        }
        finally {
            if (unprivilegedResourceResolver != null) {
                unprivilegedResourceResolver.close();
            }
        }
    }

    private void configure(Dictionary<?, ?> properties) {
        this.noLoginForm = OsgiUtil.toBoolean(properties.get("auth.http.nologin"), false);
        this.realm = OsgiUtil.toString(properties.get("auth.http.realm"), "Day Communique 5");
        this.defaultLoginPage = OsgiUtil.toString(properties.get("auth.default.loginpage"), "/libs/cq/core/content/login.html");
        this.formSupportingUserAgents = OsgiUtil.toStringArray(properties.get("auth.cred.form"), DEFAULT_FORM_LOGIN);
        this.utf8EncodingUserAgents = OsgiUtil.toStringArray(properties.get("auth.cred.utf8"), DEFAULT_UTF8_CREDENTIALS);
        this.log.debug("configure: realm='{}', loginPage='{}'", (Object)this.realm, (Object)this.defaultLoginPage);
        this.props = properties;
    }

    @Deactivate
    protected void deactivate(ComponentContext componentContext) {
        if (this.registration != null) {
            this.registration.unregister();
            this.registration = null;
        }
    }

    private Dictionary<String, Object> getProperties(ResourceResolver resourceResolver) {
        Hashtable<String, Object> newProps = new Hashtable<String, Object>();
        Enumeration ke = this.props.keys();
        while (ke.hasMoreElements()) {
            Object key = ke.nextElement();
            newProps.put(key.toString(), this.props.get(key));
        }
        ArrayList<String> merged = new ArrayList<String>();
        HashSet<String> authReqs = new HashSet<String>();
        authReqs.add("-" + HTTPAuthHandler.toRawPath(this.getDefaultLoginPage(), resourceResolver));
        String[] paths = OsgiUtil.toStringArray(this.props.get("path"));
        if (paths != null) {
            merged.addAll(Arrays.asList(paths));
        }
        newProps.put("sling.auth.requirements", authReqs.toArray(new String[authReqs.size()]));
        newProps.put("path", merged.toArray(new String[merged.size()]));
        return newProps;
    }

    private static String toRawPath(String path, ResourceResolver resourceResolver) {
        Resource loginPageResource;
        if (resourceResolver != null && !ResourceUtil.isNonExistingResource((Resource)(loginPageResource = resourceResolver.resolve(path)))) {
            return resourceResolver.map(loginPageResource.getPath());
        }
        return path;
    }

    private AuthenticationInfo extractAuthentication(HttpServletRequest request) {
        char[] password;
        String user;
        String decoded;
        String authHeader = request.getHeader("Authorization");
        if (!(authHeader != null && authHeader.length() != 0 || authHeader != null && authHeader.length() != 0)) {
            return null;
        }
        int blank = (authHeader = authHeader.trim()).indexOf(32);
        if (blank <= 0) {
            return null;
        }
        String authType = authHeader.substring(0, blank);
        String authInfo = authHeader.substring(blank).trim();
        if (!authType.equalsIgnoreCase("Basic")) {
            return null;
        }
        try {
            byte[] encoded = authInfo.getBytes("ISO-8859-1");
            byte[] bytes = Base64.decodeBase64((byte[])encoded);
            decoded = new String(bytes, this.getCredentialsEncoding(request));
        }
        catch (UnsupportedEncodingException uee) {
            this.log.error("extractAuthentication: Cannot en/decode authentication info", (Throwable)uee);
            return null;
        }
        int colIdx = decoded.indexOf(58);
        if (colIdx < 0) {
            user = decoded;
            password = new char[]{};
        } else {
            user = decoded.substring(0, colIdx);
            password = decoded.substring(colIdx + 1).toCharArray();
        }
        return new AuthenticationInfo("BASIC", user, password);
    }

    private boolean forceAuthentication(HttpServletRequest request, HttpServletResponse response) {
        boolean authenticationForced = false;
        if (request.getParameter("sling:authRequestLogin") != null) {
            if (!response.isCommitted()) {
                authenticationForced = this.sendUnauthorized(request, response);
            } else {
                this.log.error("forceAuthentication: Response is committed, cannot request authentication");
            }
        } else {
            this.log.debug("forceAuthentication: Not forcing authentication because request parameter {} is not set", (Object)"sling:authRequestLogin");
        }
        return authenticationForced;
    }

    private boolean sendUnauthorized(HttpServletRequest request, HttpServletResponse response) {
        if (response.isCommitted()) {
            this.log.debug("sendUnauthorized: Response committed, cannot send 401/UNAUTHORIZED");
            return false;
        }
        String realm = this.getRealm(request);
        if (realm == null) {
            realm = this.realm;
        }
        response.reset();
        response.setStatus(401);
        response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
        try {
            response.flushBuffer();
            return true;
        }
        catch (IOException ioe) {
            this.log.error("sendUnauthorized: Failed requesting authentication", (Throwable)ioe);
            return false;
        }
    }

    private boolean doLoginForm(HttpServletRequest request) {
        if (request.getAttribute("cq.authhandler.dologin") != null) {
            return true;
        }
        return !this.noLoginForm;
    }

    private boolean isLoginFormClient(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (this.userAgentMatch(userAgent, this.formSupportingUserAgents)) {
            this.log.debug("isLoginFormClient: Client ({}) assumed to support form based authentication", (Object)userAgent);
            return true;
        }
        this.log.debug("isLoginFormClient: Client ({}) assumed to not support form based authentication, sending 401/UNAUTHORIZED", (Object)userAgent);
        return false;
    }

    private boolean isLoginFormLoop(HttpServletRequest request, String loginPage) {
        String loginUri;
        String ctxPath = request.getContextPath();
        String string = loginUri = ctxPath == null || ctxPath.length() == 0 ? loginPage : ctxPath.concat(loginPage);
        if (request.getRequestURI().equals(loginUri)) {
            return true;
        }
        String referer = request.getHeader("Referer");
        if (referer != null) {
            try {
                URI refererUri = new URI(referer);
                return loginUri.equals(refererUri.getPath());
            }
            catch (URISyntaxException e) {
                // empty catch block
            }
        }
        return false;
    }

    private String getCredentialsEncoding(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (this.userAgentMatch(userAgent, this.utf8EncodingUserAgents)) {
            this.log.debug("getCredentialsEncoding: User-Agent ({}) indicates UTF-8 encoding browser, using UTF-8", (Object)userAgent);
            return "UTF-8";
        }
        this.log.debug("getCredentialsEncoding: User-Agent ({}) indicates non-UTF-8 encoding browser, using ISO-8859-1", (Object)userAgent);
        return "ISO-8859-1";
    }

    private /* varargs */ boolean userAgentMatch(String userAgent, String ... options) {
        if (userAgent != null && options.length > 0) {
            for (String option : options) {
                if (!userAgent.contains(option)) continue;
                return true;
            }
        }
        return false;
    }

    protected void bindRepository(SlingRepository slingRepository) {
        this.repository = slingRepository;
    }

    protected void unbindRepository(SlingRepository slingRepository) {
        if (this.repository == slingRepository) {
            this.repository = null;
        }
    }

    protected void bindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        this.resolverFactory = resourceResolverFactory;
    }

    protected void unbindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        if (this.resolverFactory == resourceResolverFactory) {
            this.resolverFactory = null;
        }
    }

    protected void bindCugSupport(CugSupport cugSupport) {
        this.cugSupport = cugSupport;
    }

    protected void unbindCugSupport(CugSupport cugSupport) {
        if (this.cugSupport == cugSupport) {
            this.cugSupport = null;
        }
    }

    protected void bindXssAPI(XSSAPI xSSAPI) {
        this.xssAPI = xSSAPI;
    }

    protected void unbindXssAPI(XSSAPI xSSAPI) {
        if (this.xssAPI == xSSAPI) {
            this.xssAPI = null;
        }
    }
}