Prepare endpoint url scheme security handler.

@param <T>             the type parameter
@param outboundContext the outbound context
@throws Exception the exception
358716
protected <T extends SAMLObject> void prepareEndpointURLSchemeSecurityHandler(final MessageContext<T> outboundContext) throws Exception {
        val handlerEnd = new EndpointURLSchemeSecurityHandler();
        handlerEnd.initialize();
        handlerEnd.invoke(outboundContext);
    }
919548
public Object openConnection(String proxyHost, int proxyPort, Proxy.Type proxyType) throws ConnectionException {
        try {
            String endpointUri = getEndpointUri();
            if (endpointUri == null)
                throw new ConnectionException("Missing endpoint URI");
            Map<String,String> params = getRequestParameters();
            if (params != null && !params.isEmpty()) {
                StringBuffer query = new StringBuffer();
                query.append(endpointUri.indexOf('?') < 0 ? '?' : '&');
                int count = 0;
                for (String name : params.keySet()) {
                    if (count > 0)
                        query.append('&');
                    String encoding = getUrlEncoding();
                    query.append(encoding == null ? name : URLEncoder.encode(name, encoding)).append("=");
                    query.append(encoding == null ? params.get(name) : URLEncoder.encode(params.get(name), encoding));
                    count++;
                }
                endpointUri += query;
            }
            logdebug("REST adapter endpoint: " + endpointUri);
            URL url = new URL(endpointUri);
            HttpConnection httpConnection;
            if ("PATCH".equals(getHttpMethod()))
                httpConnection = new HttpAltConnection(url);
            else
                httpConnection = new HttpConnection(url);

            if (proxyHost != null)
                httpConnection.setProxyHost(proxyHost);
            if (proxyPort > 0)
                httpConnection.setProxyPort(proxyPort);
            if (proxyType != null)
                httpConnection.setProxyType(proxyType);

            httpConnection.open();
            return httpConnection;
        }
        catch (Exception ex) {
            throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
        }
    }
1058711
protected void configureHandlerInterceptor(ApplicationContext context) {
        if (context.containsBean(ENDPOINT_INTERCEPTOR_BEAN_NAME)) {
            DelegatingEndpointInterceptor endpointInterceptor = context.getBean(ENDPOINT_INTERCEPTOR_BEAN_NAME, DelegatingEndpointInterceptor.class);
            endpointInterceptor.setInterceptors(adaptInterceptors(webServiceServer.getInterceptors()));
        }
    }
78388
public static HttpServletRequest getHttpServletRequestFromExternalWebflowContext(final RequestContext context) {
        Assert.isInstanceOf(ServletExternalContext.class, context.getExternalContext(),
            "Cannot obtain HttpServletRequest from event of type: "
                + context.getExternalContext().getClass().getName());

        return (HttpServletRequest) context.getExternalContext().getNativeRequest();
    }
714065
protected void addContext(String pathSpec, String dir, boolean isFiltered) throws IOException {
    if (0 == webServer.getHandlers().length) {
      throw new RuntimeException("Couldn't find handler");
    }
    WebAppContext webAppCtx = new WebAppContext();
    webAppCtx.setContextPath(pathSpec);
    webAppCtx.setWar(dir);
    addContext(webAppCtx, true);
  }
704992
public synchronized void setEndpoint(URI endpoint) {
        checkUpdatable();
        int port = endpoint.getPort();
        if (port==80||port==443) {
            if (MwsUtl.usesStandardPort(endpoint)) {
                try {
                    //some versions of apache http client cause signature errors when
                    //standard port is explicitly used, so remove that case.
                    endpoint = new URI(endpoint.getScheme(), endpoint.getHost(), 
                            endpoint.getPath(), endpoint.getFragment());
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        }
        this.endpoint = endpoint;
    }
719105
public void submitContextString(final String evaluatorConfigurationString,
                                  final String contextConfigurationString) {
    if (evaluatorConfigurationString.isEmpty()) {
      throw new RuntimeException("empty evaluatorConfigurationString provided.");
    }
    if (contextConfigurationString.isEmpty()) {
      throw new RuntimeException("empty contextConfigurationString provided.");
    }

    //When submit over the bridge, we would keep the contextConfigurationString as serialized strings.
    //public void submitContext(final String contextConfiguration)
    // is not exposed in the interface. Therefore cast is necessary.
    ((AllocatedEvaluatorImpl)jallocatedEvaluator).submitContext(
        evaluatorConfigurationString, contextConfigurationString);
  }
1334608
public void setOutboundInterface(SipURI outboundInterface) {
		checkSessionValidity();
		if(outboundInterface == null) {
			throw new NullPointerException("outbound Interface param shouldn't be null");
		}
		List<SipURI> list = proxy.getSipFactoryImpl().getSipNetworkInterfaceManager().getOutboundInterfaces();
		SipURI networkInterface = null;
		for(SipURI networkInterfaceURI : list) {
			if(networkInterfaceURI.equals(outboundInterface)) {
				networkInterface = networkInterfaceURI;
				break;
			}
		}
		
		if(networkInterface == null) throw new IllegalArgumentException("Network interface for " +
				outboundInterface + " not found");		
		
		this.outboundInterface = networkInterface;
	}
460583
@Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {
        if(exchange.isInIoThread()) {
            exchange.dispatch(this);
            return;
        }
        SecurityContext context = exchange.getSecurityContext();
        if (context.authenticate()) {
            if(!exchange.isComplete()) {
               next.handleRequest(exchange);
            }
        } else {
            if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
                ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                src.getOriginalResponse().sendError(exchange.getStatusCode());
            } else {
                exchange.endExchange();
            }
        }
    }
354644
protected void handleEndpointRequest(HttpServletRequest request, HttpServletResponse response,
			ServletContext servletContext) throws IOException {
		JwtRequest jwtRequest = getJwtRequest(request, response);
		if (jwtRequest == null) {
			// Error redirect already taken care of
			return;
		}

		String jwtConfigId = jwtRequest.getJwtConfigId();
		JwtConfig jwtConfig = getJwtConfig(response, jwtConfigId);
		if (jwtConfig == null) {
			// Error redirect already taken care of
			return;
		}

		EndpointType endpointType = jwtRequest.getType();
		handleJwtRequest(request, response, servletContext, jwtConfig, endpointType);

	}
275626
protected void dispatch(String pathInContext,
                            HttpServletRequest request,
                            HttpServletResponse response,
                            ServletHolder servletHolder, 
                            int type)
        throws ServletException, UnavailableException, IOException
    {
        if (type == Dispatcher.__REQUEST)
        {
            // This is NOT a dispatched request (it it is an initial request)
            ServletHttpRequest servletHttpRequest= (ServletHttpRequest)request;
            ServletHttpResponse servletHttpResponse= (ServletHttpResponse)response;  
            
            // protect web-inf and meta-inf
            if (StringUtil.startsWithIgnoreCase(pathInContext, "/web-inf") || StringUtil.startsWithIgnoreCase(pathInContext, "/meta-inf"))
            {
                response.sendError(HttpResponse.__404_Not_Found);
                return;
            }
            
            // Security Check
            if (!getHttpContext().checkSecurityConstraints(
                            pathInContext,
                            servletHttpRequest.getHttpRequest(),
                            servletHttpResponse.getHttpResponse()))
                return;
        }
        else
        {
            // This is a dispatched request.
            
            // Handle dispatch to j_security_check
            HttpContext context= getHttpContext();
            if (context != null
                    && context instanceof ServletHttpContext
                    && pathInContext != null
                    && pathInContext.endsWith(FormAuthenticator.__J_SECURITY_CHECK))
            {
                ServletHttpRequest servletHttpRequest=
                    (ServletHttpRequest)context.getHttpConnection().getRequest().getWrapper();
                ServletHttpResponse servletHttpResponse= servletHttpRequest.getServletHttpResponse();
                ServletHttpContext servletContext= (ServletHttpContext)context;
                
                if (!servletContext.jSecurityCheck(pathInContext,servletHttpRequest.getHttpRequest(),servletHttpResponse.getHttpResponse()))
                    return;
            }
        }
        
        // Build and/or cache filter chain
        FilterChain chain=null;
        if (pathInContext != null) {
            chain = getChainForPath(type, pathInContext, servletHolder);
        } else {
            chain = getChainForName(type, servletHolder);
        }

        if (log.isDebugEnabled()) log.debug("chain="+chain);
        
        // Do the handling thang
        if (chain!=null)
            chain.doFilter(request, response);
        else if (servletHolder != null)
            servletHolder.handle(request, response);    
        else // Not found
            notFound(request, response);
    }
1052185
@Override
    public void handle(RequestContext context, AccessDeniedException e) throws SecurityProviderException, IOException {
        saveException(context, e);

        if (StringUtils.isNotEmpty(getErrorPageUrl())) {
            forwardToErrorPage(context);
        } else {
            sendError(e, context);
        }
    }
1232938
public void useXopAttachmentServiceWithProxy() throws Exception {

        final String serviceURI = "http://localhost:" + port + "/services/attachments";
        
        XopAttachmentService proxy = JAXRSClientFactory.create(serviceURI, 
                                                               XopAttachmentService.class);
        
        XopBean xop = createXopBean();
        
        System.out.println();
        System.out.println("Posting a XOP attachment with a proxy");
                
        XopBean xopResponse = proxy.echoXopAttachment(xop);
        
        verifyXopResponse(xop, xopResponse);
    }
1063123
public void init() throws Exception {
    // configure the SSLContext with a TrustManager
    SSLContext ctx = SSLContext.getInstance("TLS");
    if (ignoreCertificates) {
      ctx.init(new KeyManager[0],
          new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
      SSLContext.setDefault(ctx);
    }
    HostnameVerifier hv = new IgnoreHostName();
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
  }
347641
protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters,
                                                HttpURLConnection connection) throws GeneralSecurityException {

        int hash = tlsClientParameters.hashCode();
        if (hash != lastTlsHash) {
            lastTlsHash = hash;
            socketFactory = null;
        }

        // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and
        // tlsClientParameters.sslSocketFactory to allow runtime configuration change
        if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) {
            socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        } else if (tlsClientParameters.getSSLSocketFactory() != null) {
            // see if an SSLSocketFactory was set. This allows easy interop
            // with not-yet-commons-ssl.jar, or even just people who like doing their
            // own JSSE.
            socketFactory = tlsClientParameters.getSSLSocketFactory();

        } else if (socketFactory == null) {
            // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust
            // Managers, Key Managers, etc

            SSLContext ctx = org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters);

            String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(),
                                                                      tlsClientParameters.getCipherSuitesFilter(),
                                                                      ctx.getSocketFactory().getDefaultCipherSuites(),
                                                                      SSLUtils.getSupportedCipherSuites(ctx),
                                                                      LOG);
            // The SSLSocketFactoryWrapper enables certain cipher suites
            // from the policy.
            String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters.getSecureSocketProtocol() : "TLS";
            socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, protocol);
            //recalc the hashcode since some of the above MAY have changed the tlsClientParameters
            lastTlsHash = tlsClientParameters.hashCode();
        } else {
            // ssl socket factory already initialized, reuse it to benefit of keep alive
        }

        HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils.getHostnameVerifier(tlsClientParameters);

        if (connection instanceof HttpsURLConnection) {
            // handle the expected case (javax.net.ssl)
            final HttpsURLConnection conn = (HttpsURLConnection) connection;
            conn.setHostnameVerifier(verifier);
            AccessController.doPrivileged(new PrivilegedAction<Void>() {

                @Override
                public Void run() {
                    conn.setSSLSocketFactory(socketFactory);
                    return null;
                }
            });
        } else {
            // handle the deprecated sun case and other possible hidden API's
            // that are similar to the Sun cases
            try {
                Method method = connection.getClass().getMethod("getHostnameVerifier");

                InvocationHandler handler = new ReflectionInvokationHandler(verifier) {
                    @Override
                    public Object invoke(Object proxy,
                                         Method method,
                                         Object[] args) throws Throwable {
                        try {
                            return super.invoke(proxy, method, args);
                        } catch (Exception ex) {
                            return false;
                        }
                    }
                };
                Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(),
                                                                        new Class[] { method.getReturnType() },
                                                                        handler);

                method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType());
                method.invoke(connection, proxy);
            } catch (Exception ex) {
                //Ignore this one
            }
            try {
                Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory");
                Method setSSLSocketFactory = connection.getClass().getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType());
                if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) {
                    setSSLSocketFactory.invoke(connection, socketFactory);
                } else {
                    //need to see if we can create one - mostly the weblogic case.   The
                    //weblogic SSLSocketFactory has a protected constructor that can take
                    //a JSSE SSLSocketFactory so we'll try and use that
                    Constructor<?> c = getSSLSocketFactory.getReturnType().getDeclaredConstructor(SSLSocketFactory.class);
                    ReflectionUtil.setAccessible(c);
                    setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory));
                }
            } catch (Exception ex) {
                if (connection.getClass().getName().contains("weblogic")) {
                    if (!weblogicWarned) {
                        weblogicWarned = true;
                        LOG.warning("Could not configure SSLSocketFactory on Weblogic.  "
                                    + " Use the Weblogic control panel to configure the SSL settings.");
                    }
                    return;
                }
                //if we cannot set the SSLSocketFactor, we're in serious trouble.
                throw new IllegalArgumentException("Error decorating connection class "
                                                   + connection.getClass().getName(), ex);
            }
        }
    }
1210111
protected void configureEndpointAccessToDenyUndefined(final HttpSecurity http,
                                                          final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests) {
        val endpoints = casProperties.getMonitor().getEndpoints().getEndpoint().keySet();
        val endpointDefaults = casProperties.getMonitor().getEndpoints().getDefaultEndpointProperties();
        pathMappedEndpoints.forEach(endpoint -> {
            val rootPath = endpoint.getRootPath();
            if (endpoints.contains(rootPath)) {
                LOGGER.trace("Endpoint security is defined for endpoint [{}]", rootPath);
            } else {
                val defaultAccessRules = endpointDefaults.getAccess();
                LOGGER.trace("Endpoint security is NOT defined for endpoint [{}]. Using default security rules [{}]", rootPath, endpointDefaults);
                val endpointRequest = EndpointRequest.to(rootPath).excludingLinks();
                defaultAccessRules.forEach(Unchecked.consumer(access ->
                    configureEndpointAccess(http, requests, access, endpointDefaults, endpointRequest)));
            }
        });
    }
564613
@Override
    public void handle(RequestContext context) throws SecurityProviderException, IOException {
        RedirectUtils.redirect(context.getRequest(), context.getResponse(), getTargetUrl());
    }