Search in sources :

Example 1 with WebScript

use of org.springframework.extensions.webscripts.WebScript in project alfresco-remote-api by Alfresco.

the class BlockingRemoteUserMapper method prepareMockRequest.

private WebScriptServletRequest prepareMockRequest(Set<String> families, String headerToAdd) {
    HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class);
    when(mockHttpRequest.getScheme()).thenReturn("http");
    if (headerToAdd != null) {
        when(mockHttpRequest.getHeader("Authorization")).thenReturn(headerToAdd);
    }
    WebScriptServletRequest mockRequest = mock(WebScriptServletRequest.class);
    when(mockRequest.getHttpServletRequest()).thenReturn(mockHttpRequest);
    WebScript mockWebScript = mock(WebScript.class);
    Match mockMatch = new Match("fake", Collections.EMPTY_MAP, "whatever", mockWebScript);
    when(mockRequest.getServiceMatch()).thenReturn(mockMatch);
    Description mockDescription = mock(Description.class);
    when(mockWebScript.getDescription()).thenReturn(mockDescription);
    when(mockDescription.getFamilys()).thenReturn(families);
    return mockRequest;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Description(org.springframework.extensions.webscripts.Description) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) WebScript(org.springframework.extensions.webscripts.WebScript) Match(org.springframework.extensions.webscripts.Match)

Example 2 with WebScript

use of org.springframework.extensions.webscripts.WebScript in project alfresco-remote-api by Alfresco.

the class RepositoryContainer method executeScriptInternal.

protected void executeScriptInternal(WebScriptRequest scriptReq, WebScriptResponse scriptRes, final Authenticator auth) throws IOException {
    final WebScript script = scriptReq.getServiceMatch().getWebScript();
    final Description desc = script.getDescription();
    final boolean debug = logger.isDebugEnabled();
    // Escalate the webscript declared level of authentication to the container required authentication
    // eg. must be guest if MT is enabled unless credentials are empty
    RequiredAuthentication containerRequiredAuthentication = getRequiredAuthentication();
    final RequiredAuthentication required = (desc.getRequiredAuthentication().compareTo(containerRequiredAuthentication) < 0 && !auth.emptyCredentials() ? containerRequiredAuthentication : desc.getRequiredAuthentication());
    final boolean isGuest = scriptReq.isGuest();
    if (required == RequiredAuthentication.none) {
        // TODO revisit - cleared here, in-lieu of WebClient clear
        // AuthenticationUtil.clearCurrentSecurityContext();
        transactionedExecuteAs(script, scriptReq, scriptRes);
    } else if ((required == RequiredAuthentication.user || required == RequiredAuthentication.admin) && isGuest) {
        throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script " + desc.getId() + " requires user authentication; however, a guest has attempted access.");
    } else {
        try {
            AuthenticationUtil.pushAuthentication();
            // 
            if (debug) {
                String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
                logger.debug("Current authentication: " + (currentUser == null ? "unauthenticated" : "authenticated as " + currentUser));
                logger.debug("Authentication required: " + required);
                logger.debug("Guest login requested: " + isGuest);
            }
            // 
            // Apply appropriate authentication to Web Script invocation
            // 
            RetryingTransactionCallback<Boolean> authWork = new RetryingTransactionCallback<Boolean>() {

                public Boolean execute() throws Exception {
                    if (auth == null || auth.authenticate(required, isGuest)) {
                        // Check to see if they supplied HTTP Auth or Ticket as guest, on a script that needs more
                        if (required == RequiredAuthentication.user || required == RequiredAuthentication.admin) {
                            String authenticatedUser = AuthenticationUtil.getFullyAuthenticatedUser();
                            String runAsUser = AuthenticationUtil.getRunAsUser();
                            if ((authenticatedUser == null) || (authenticatedUser.equals(runAsUser) && authorityService.hasGuestAuthority()) || (!authenticatedUser.equals(runAsUser) && authorityService.isGuestAuthority(authenticatedUser))) {
                                throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script " + desc.getId() + " requires user authentication; however, a guest has attempted access.");
                            }
                        }
                        // Check to see if they're admin or system on an Admin only script
                        if (required == RequiredAuthentication.admin && !(authorityService.hasAdminAuthority() || AuthenticationUtil.getFullyAuthenticatedUser().equals(AuthenticationUtil.getSystemUserName()))) {
                            throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Web Script " + desc.getId() + " requires admin authentication; however, a non-admin has attempted access.");
                        }
                        if (debug) {
                            String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
                            logger.debug("Authentication: " + (currentUser == null ? "unauthenticated" : "authenticated as " + currentUser));
                        }
                        return true;
                    }
                    return false;
                }
            };
            boolean readOnly = transactionService.isReadOnly();
            boolean requiresNew = !readOnly && AlfrescoTransactionSupport.getTransactionReadState() == TxnReadState.TXN_READ_ONLY;
            if (transactionService.getRetryingTransactionHelper().doInTransaction(authWork, readOnly, requiresNew)) {
                // Execute Web Script if authentication passed
                // The Web Script has its own txn management with potential runAs() user
                transactionedExecuteAs(script, scriptReq, scriptRes);
            } else {
                throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed for Web Script " + desc.getId());
            }
        } finally {
            // 
            // Reset authentication for current thread
            // 
            AuthenticationUtil.popAuthentication();
            if (debug) {
                String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
                logger.debug("Authentication reset: " + (currentUser == null ? "unauthenticated" : "authenticated as " + currentUser));
            }
        }
    }
}
Also used : Description(org.springframework.extensions.webscripts.Description) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) WebScript(org.springframework.extensions.webscripts.WebScript) SocketException(java.net.SocketException) TooBusyException(org.alfresco.repo.transaction.TooBusyException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) RequiredAuthentication(org.springframework.extensions.webscripts.Description.RequiredAuthentication)

Example 3 with WebScript

use of org.springframework.extensions.webscripts.WebScript in project alfresco-remote-api by Alfresco.

the class BlockingRemoteUserMapper method checkExtAuthStillWorks.

private void checkExtAuthStillWorks(RequiredAuthentication required, Set<String> families) {
    blockingRemoteUserMapper.reset();
    DefaultRemoteUserMapper defaultRemoteUserMapper = new DefaultRemoteUserMapper();
    defaultRemoteUserMapper.setActive(true);
    defaultRemoteUserMapper.setProxyUserName(null);
    defaultRemoteUserMapper.setPersonService(personService);
    remoteUserAuthenticatorFactory.setRemoteUserMapper(defaultRemoteUserMapper);
    HttpServletRequest mockHttpRequest = mock(HttpServletRequest.class);
    when(mockHttpRequest.getScheme()).thenReturn("http");
    final String userName = "RAFACAT_usr_" + (int) (Math.random() * 1000);
    when(mockHttpRequest.getHeader(proxyHeader)).thenReturn(userName);
    WebScriptServletRequest mockRequest = mock(WebScriptServletRequest.class);
    when(mockRequest.getHttpServletRequest()).thenReturn(mockHttpRequest);
    WebScript mockWebScript = mock(WebScript.class);
    Match mockMatch = new Match("fake", Collections.EMPTY_MAP, "whatever", mockWebScript);
    when(mockRequest.getServiceMatch()).thenReturn(mockMatch);
    Description mockDescription = mock(Description.class);
    when(mockWebScript.getDescription()).thenReturn(mockDescription);
    when(mockDescription.getFamilys()).thenReturn(families);
    WebScriptServletResponse mockResponse = prepareMockResponse();
    Authenticator authenticator = remoteUserAuthenticatorFactory.create(mockRequest, mockResponse);
    final boolean authenticated = authenticator.authenticate(required, false);
    assertTrue("This should be authenticating with external auth", authenticated);
    assertFalse("We have been using the DefaultRemoteUserMapper, so our BlockingRemoteUserMapper shouldn't have been called", blockingRemoteUserMapper.isWasInterrupted());
    assertEquals("BlockingRemoteUserMapper shouldn't have been called", blockingRemoteUserMapper.getTimePassed(), 0);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Description(org.springframework.extensions.webscripts.Description) DefaultRemoteUserMapper(org.alfresco.repo.security.authentication.external.DefaultRemoteUserMapper) WebScriptServletResponse(org.springframework.extensions.webscripts.servlet.WebScriptServletResponse) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) WebScript(org.springframework.extensions.webscripts.WebScript) Authenticator(org.springframework.extensions.webscripts.Authenticator) Match(org.springframework.extensions.webscripts.Match)

Example 4 with WebScript

use of org.springframework.extensions.webscripts.WebScript in project alfresco-remote-api by Alfresco.

the class XssVulnerabilityTest method testXssVulnerability.

public void testXssVulnerability() throws Throwable {
    webscriptsRegistry.reset();
    final int scriptsSize = webscriptsRegistry.getWebScripts().size();
    int i = 0, successCount = 0, wserrcount = 0, vulnCount = 0;
    LinkedList<String> vulnerabileURLS = new LinkedList<String>();
    for (WebScript ws : webscriptsRegistry.getWebScripts()) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("progress: " + ++i + "/" + scriptsSize);
        }
        Description wsDesc = ws.getDescription();
        if (SKIP_WEBSCRIPT_CHECK_ID_SET.contains(wsDesc.getId())) {
            // skip
            continue;
        }
        boolean isMethodCheck = METHODS_TO_CHECK_SET.contains(wsDesc.getMethod());
        boolean isFormatCheck = FORMATS_TO_CHECK_SET.contains(wsDesc.getDefaultFormat());
        if (isMethodCheck && isFormatCheck) {
            for (String malArg : MALICIOUS_ARGS) {
                String[] uris = wsDesc.getURIs();
                for (String uri : uris) {
                    if (isUriSkip(uri)) {
                        continue;
                    }
                    // always parse url because we cannot rely on getArguments():
                    // - sometimes getArguments() returns null although URI has arguments
                    // - sometimes getArguments() returns set of args that does not contain args from url
                    List<String> parsedArgs = parseArgsFromURI(uri);
                    if (0 == parsedArgs.size()) {
                        // no arguments in uri, skip
                        continue;
                    }
                    String url = substituteMaliciousArgInURI(uri, parsedArgs, malArg);
                    Response resp;
                    try {
                        resp = sendRequest(createRequest(wsDesc.getMethod(), url), -1);
                    } catch (WebScriptException e) {
                        // skip webscript errors
                        ++wserrcount;
                        continue;
                    }
                    String respString = resp.getContentAsString();
                    if (resp.getStatus() == Status.STATUS_OK) {
                        ++successCount;
                    }
                    // do case insensitive check because argument can be converted to lowercase on page
                    if (respString.toLowerCase().contains(malArg.toLowerCase())) {
                        vulnerabileURLS.add(wsDesc.getMethod() + " " + url);
                        vulnCount++;
                    }
                }
            }
        }
    }
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("OK html responses count: " + successCount);
        getLogger().debug("Webscript errors count: " + wserrcount);
        getLogger().debug("Vulnerabile URLs count: " + vulnCount);
    }
    for (String url : vulnerabileURLS) {
        getLogger().warn("Vulnerabile URL: " + url);
    }
    assertTrue("Vulnerabile URLs found: " + vulnerabileURLS, vulnerabileURLS.size() == 0);
}
Also used : Response(org.springframework.extensions.webscripts.TestWebScriptServer.Response) Description(org.springframework.extensions.webscripts.Description) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) WebScript(org.springframework.extensions.webscripts.WebScript) LinkedList(java.util.LinkedList)

Aggregations

Description (org.springframework.extensions.webscripts.Description)4 WebScript (org.springframework.extensions.webscripts.WebScript)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Match (org.springframework.extensions.webscripts.Match)2 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)2 WebScriptServletRequest (org.springframework.extensions.webscripts.servlet.WebScriptServletRequest)2 IOException (java.io.IOException)1 SocketException (java.net.SocketException)1 LinkedList (java.util.LinkedList)1 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)1 DefaultRemoteUserMapper (org.alfresco.repo.security.authentication.external.DefaultRemoteUserMapper)1 RetryingTransactionCallback (org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback)1 TooBusyException (org.alfresco.repo.transaction.TooBusyException)1 Authenticator (org.springframework.extensions.webscripts.Authenticator)1 RequiredAuthentication (org.springframework.extensions.webscripts.Description.RequiredAuthentication)1 Response (org.springframework.extensions.webscripts.TestWebScriptServer.Response)1 WebScriptServletResponse (org.springframework.extensions.webscripts.servlet.WebScriptServletResponse)1