TODO Need to figure out what Organizations TGuard entities should be part of.
432238
public String getName() {
		if(name==null) {
			String temp = get("iv-user");
			if(temp==null)return null;
			StringBuilder sb = new StringBuilder();
			int at = temp.indexOf('@');
			if(at<0) {
				sb.append(temp);
			} else {
				sb.append(temp.substring(0, at));
			}
			if(temp.endsWith("@uverse.com"))sb.append("@uverse.tguard.att.com");
			else if(temp.endsWith("@att.com"))sb.append("@com.tguard.att.com");
			else if(temp.endsWith("@att.net"))sb.append("@net.tguard.att.com");
			else sb.append("@tguard.att.com");
			name = sb.toString();
		}
		return name;
	}
746211
private void getKeyTrustManagers(Map<String, Object> connectionInfo, SSLConfig sslConfig, List<KeyManager> kmHolder, List<TrustManager> tmHolder) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getKeyTrustManagers", new Object[] { connectionInfo, sslConfig });

        TrustManagerFactory trustManagerFactory = null;
        KeyManagerFactory keyManagerFactory = null;
        KeyStore keyStore = null;
        KeyStore trustStore = null;
        boolean createKeyMgr = true;

        String direction = Constants.DIRECTION_UNKNOWN;

        if (connectionInfo != null) {
            direction = (String) connectionInfo.get(Constants.CONNECTION_INFO_DIRECTION);
        }

        try {
            // Access a potentially set contextProvider.
            String trustFileName = getSSLContextProperty(Constants.SSLPROP_TRUST_STORE_NAME, sslConfig);
            WSKeyStore wsts = null;
            if (trustFileName != null)
                wsts = KeyStoreManager.getInstance().getKeyStore(trustFileName);

            if (wsts != null) {
                trustStore = wsts.getKeyStore(false, false);
            }

            String keyFileName = getSSLContextProperty(Constants.SSLPROP_KEY_STORE_NAME, sslConfig);
            WSKeyStore wsks = null;
            if (keyFileName != null)
                wsks = KeyStoreManager.getInstance().getKeyStore(keyFileName);

            if (wsks != null) {
                keyStore = wsks.getKeyStore(false, false);
            }

            boolean usingHwCryptoTrustStore = false;
            boolean usingHwCryptoKeyStore = false;
            String ctxtProvider = getSSLContextProperty(Constants.SSLPROP_CONTEXT_PROVIDER, sslConfig);
            String keyMgr = getSSLContextProperty(Constants.SSLPROP_KEY_MANAGER, sslConfig);
            String trustMgr = getSSLContextProperty(Constants.SSLPROP_TRUST_MANAGER, sslConfig);
            String clientAuthentication = getSSLContextProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION, sslConfig);
            String clientAliasName = getSSLContextProperty(Constants.SSLPROP_KEY_STORE_CLIENT_ALIAS, sslConfig);
            String serverAliasName = getSSLContextProperty(Constants.SSLPROP_KEY_STORE_SERVER_ALIAS, sslConfig);
            String tokenLibraryFile = getSSLContextProperty(Constants.SSLPROP_TOKEN_LIBRARY, sslConfig);
            String tokenPassword = getSSLContextProperty(Constants.SSLPROP_TOKEN_PASSWORD, sslConfig);
            String tokenType = getSSLContextProperty(Constants.SSLPROP_TOKEN_TYPE, sslConfig);
            String tokenSlot = getSSLContextProperty(Constants.SSLPROP_TOKEN_SLOT, sslConfig);
            char[] passPhrase = null;

            // ---------------------
            // Handle Trust Store
            // ---------------------
            if (trustStore != null) {
                // Trust store specified.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Using trust store: " + wsts.getLocation());
                }
            } else {
                // No trust store specified. Check if hw crypto is involved.
                if (tokenLibraryFile != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "No trust store specified, but found hardware crypto");
                    }

                    WSPKCSInKeyStore pKS = pkcsStoreList.insert(tokenType, tokenLibraryFile, tokenPassword, false, ctxtProvider);

                    if (pKS != null) {
                        trustStore = pKS.getTS();
                        trustManagerFactory = pKS.getTMF();
                        usingHwCryptoTrustStore = true;
                    }
                } else {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "No trust store specified and no hardware crypto defined");
                    }
                    // No hw crypto.
                    if (direction.equals(Constants.DIRECTION_INBOUND) && (clientAuthentication.equals(Constants.FALSE))) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "trust store permitted to be null since this is inbound and client auth is false");
                        }
                    } else {
                        throw new IllegalArgumentException("Invalid trust file name of null");
                    }
                }
            }

            if (!usingHwCryptoTrustStore) {
                // Get instance of trust manager factory. Use contextProvider if
                // available.
                // Already got trustManagerFactory for crypto
                trustManagerFactory = getTrustManagerFactoryInstance(trustMgr, ctxtProvider);
                String ldapCertstoreHost = System.getProperty(Constants.SSLPROP_LDAP_CERT_STORE_HOST);
                String ldapCertstorePortS = System.getProperty(Constants.SSLPROP_LDAP_CERT_STORE_PORT);
                int ldapCertstorePort = ldapCertstorePortS == null ? 389 : Integer.parseInt(ldapCertstorePortS);

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "certStoreHost: " + ldapCertstoreHost);
                    Tr.debug(tc, "certStorePort: " + ldapCertstorePort);
                    Tr.debug(tc, "trustManagerAlgorithm: " + trustManagerFactory.getAlgorithm());
                }

                if (ldapCertstoreHost != null && trustManagerFactory != null && (trustManagerFactory.getAlgorithm().equals("IbmPKIX"))) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Adding ldap cert store " + ldapCertstoreHost + ":" + ldapCertstorePort + " ");
                    }

                    PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustStore, new X509CertSelector());

                    // create the ldap parms
                    LDAPCertStoreParameters LDAPParms = new LDAPCertStoreParameters(ldapCertstoreHost, ldapCertstorePort);
                    pkixParams.addCertStore(CertStore.getInstance("LDAP", LDAPParms));

                    // enable revocation checking
                    pkixParams.setRevocationEnabled(true);

                    // Wrap them as trust manager parameters
                    ManagerFactoryParameters trustParams = new CertPathTrustManagerParameters(pkixParams);

                    trustManagerFactory.init(trustParams);
                } else if (null != trustManagerFactory) {
                    trustManagerFactory.init(trustStore);
                }
            }

            // ---------------------
            // Handle Key Store
            // ---------------------
            if (keyStore != null) {
                // Key store specified.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Using software keystore: " + wsks.getLocation());
                }
            } else {
                // No key store specified. Check if hw crypto is involved.
                if (tokenLibraryFile != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "No key store specified, but found hardware crypto");
                    }
                    // Hw crypto is involved. Build the trust store in a hw unique way.
                    // First check to see if the same keystore is used by the trust
                    // manager.
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Reusing key store from Trust Manager");
                    }

                    WSPKCSInKeyStore pKS = pkcsStoreList.insert(tokenType, tokenLibraryFile, tokenPassword, true, ctxtProvider);
                    if (pKS != null) {
                        keyStore = pKS.getKS();
                        keyManagerFactory = pKS.getKMF();
                        usingHwCryptoKeyStore = true;
                    }
                } else {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "No key store specified and no hardware crypto defined");
                    }
                    throw new IllegalArgumentException("No key store specified and no hardware crypto defined");
                }
            }

            if (!usingHwCryptoKeyStore) {
                // Get an instance of the key manager factory.
                keyManagerFactory = getKeyManagerFactoryInstance(keyMgr, ctxtProvider);
                String kspass = wsks.getPassword();
                if (!kspass.isEmpty()) {
                    try {
                        SerializableProtectedString keypass = wsks.getKeyPassword();
                        String decodedPass = WSKeyStore.decodePassword(new String(keypass.getChars()));
                        synchronized (_lockObj) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "Entering synchronized block around key manager factory init.");
                            }
                            keyManagerFactory.init(keyStore, decodedPass.toCharArray());
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "Exiting synchronized block around key manager factory init.");
                            }
                        }
                    } catch (UnrecoverableKeyException exc) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Error initializing key manager, the password can not be used to recover all keys");
                        }
                        Tr.error(tc, "ssl.unrecoverablekey.error.CWPKI0813E", new Object[] { wsks.getLocation(), exc.getMessage() });
                        throw new UnrecoverableKeyException(exc.getMessage() + ": invalid password for key in file '" + wsks.getLocation() + "'");
                    }
                } else {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "No password provide so do not create a keymanager");
                    }
                    createKeyMgr = false;
                }
            }

            if (createKeyMgr) {
                // Initialize the SSL context with the key and trust manager factories.
                WSX509KeyManager wsKeyManager = new WSX509KeyManager(keyStore, passPhrase, keyManagerFactory, sslConfig, null);

                if (serverAliasName != null && serverAliasName.length() > 0)
                    wsKeyManager.setServerAlias(serverAliasName);
                if (clientAliasName != null && clientAliasName.length() > 0)
                    wsKeyManager.setClientAlias(clientAliasName);

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "Initializing WSX509KeyManager.", new Object[] { serverAliasName, clientAliasName, tokenSlot });
                kmHolder.add(wsKeyManager);
            }

            // prepare trust manager wrapper.
            TrustManager[] defaultTMArray = trustManagerFactory.getTrustManagers();
            WSX509TrustManager wsTrustManager = new WSX509TrustManager(defaultTMArray, connectionInfo, sslConfig, trustFileName, wsts.getLocation());
            tmHolder.add(wsTrustManager);

        } catch (Exception e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Exception caught during init, " + e);
            FFDCFilter.processException(e, getClass().getName(), "getKeyTrustManagers", this);
            throw e;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getKeyTrustManagers");
    }
1276684
@Override public void attachInfo(Context context, ProviderInfo info) {
    super.attachInfo(context, info);

    // Sanity check our security
    if (info.exported) {
      throw new SecurityException("Provider must not be exported");
    }
    if (!info.grantUriPermissions) {
      throw new SecurityException("Provider must grant uri permissions");
    }

    mStrategy = getPathStrategy(context, info.authority);
  }
1088314
static protected function shouldProtectUser()
    {
        if ( !self::$isEnabled )
            return false;

        if ( !eZSession::hasStarted() )
            return false;

        if ( !eZUser::isCurrentUserRegistered() )
            return false;

        return true;
    }
1093317
public void configureWebApp() throws Exception
    {
        Set tlds = new HashSet();
        
        // Find tld's from web.xml
        // When the XMLConfigurator (or other configurator) parsed the web.xml,
        // It should have created aliases for all TLDs.  So search resources aliases
        // for aliases ending in tld
        if (_context.getResourceAliases()!=null)
        {
            Iterator iter=_context.getResourceAliases().values().iterator();
            while(iter.hasNext())
            {
                String location = (String)iter.next();
                if (location!=null && location.toLowerCase().endsWith(".tld"))
                {
                    if (!location.startsWith("/"))
                        location="/WEB-INF/"+location;
                    Resource l=_context.getBaseResource().addPath(location);
                    tlds.add(l);
                }
            }
        }
        
        // Look for any tlds in WEB-INF directly.
        if (_context.getWebInf()!=null)
        {
            String[] contents = _context.getWebInf().list();
            for (int i=0;i<contents.length;i++)
            {
                if (contents[i]!=null && contents[i].toLowerCase().endsWith(".tld"))
                {
                    Resource l=_context.getWebInf().addPath(contents[i]);
                    tlds.add(l);
                }
                
            }

            // Look for any tlds in the META-INF of included jars
            Resource lib=_context.getWebInf().addPath("lib/");
            if (lib.exists() && lib.isDirectory())
            {
                contents = lib.list();
                for (int i=0;i<contents.length;i++)
                {
                    if (contents[i]!=null && contents[i].toLowerCase().endsWith(".jar"))
                    {
                        Resource l=lib.addPath(contents[i]);
                        Resource meta=Resource.newResource("jar:"+l+"!/META-INF/");
                        if (meta.exists())
                        {
                            String[] meta_contents=meta.list();
                            
                            for (int j=0;j<meta_contents.length;j++)
                            {
                                if (meta_contents[j]!=null && meta_contents[j].toLowerCase().endsWith(".tld"))
                                {
                                    Resource t=meta.addPath(meta_contents[j]);
                                    tlds.add(t);
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // Create a TLD parser
        XmlParser parser = new XmlParser(false);
        
        parser.redirectEntity("web-jsptaglibrary_1_1.dtd",WebApplicationContext.class.getResource("/javax/servlet/jsp/resources/web-jsptaglibrary_1_1.dtd"));
        parser.redirectEntity("web-jsptaglibrary_1_2.dtd",WebApplicationContext.class.getResource("/javax/servlet/jsp/resources/web-jsptaglibrary_1_2.dtd"));
        parser.redirectEntity("web-jsptaglibrary_2_0.xsd",WebApplicationContext.class.getResource("/javax/servlet/jsp/resources/web-jsptaglibrary_2_0.xsd"));
        parser.setXpath("/taglib/listener/listener-class");
        // Parse all the discovered TLDs
        Iterator iter = tlds.iterator();
        while (iter.hasNext())
        {
            try
            {
                Resource tld = (Resource)iter.next();
                if (log.isDebugEnabled()) log.debug("TLD="+tld);
                
                XmlParser.Node root = parser.parse(tld.getURL());
                
                for (int i=0;i<root.size();i++)
                {
                    Object o=root.get(i);
                    if (o instanceof XmlParser.Node)
                    {
                        XmlParser.Node node = (XmlParser.Node)o;
                        if ("listener".equals(node.getTag()))
                        {
                            String className=node.getString("listener-class",false,true);
                            if (log.isDebugEnabled()) log.debug("listener="+className);
                            
                            try
                            {
                                Class listenerClass=getWebApplicationContext().loadClass(className);
                                EventListener l=(EventListener)listenerClass.newInstance();
                                _context.addEventListener(l);
                            }
                            catch(Exception e)
                            {
                                log.warn("Could not instantiate listener "+className,e);
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                log.warn(e);
            }
        }
    }
645222
private boolean checkRestrictorService(RestrictorCheck pCheck, Object ... args) {
        try {
            ServiceReference[] serviceRefs = bundleContext.getServiceReferences(Restrictor.class.getName(),null);
            if (serviceRefs != null) {
                boolean ret = true;
                boolean found = false;
                for (ServiceReference serviceRef : serviceRefs) {
                    Restrictor restrictor = (Restrictor) bundleContext.getService(serviceRef);
                    if (restrictor != null) {
                        ret = ret && pCheck.check(restrictor,args);
                        found = true;
                    }
                }
                return found && ret;
            } else {
                return false;
            }
        } catch (InvalidSyntaxException e) {
            // Will not happen, since we dont use a filter here
            throw new IllegalArgumentException("Impossible exception (we don't use a filter for fetching the services)",e);
        }
    }
918959
private int checkSecurity(String strClassResource, String strSecurityMap, int iAccessType, int iLevel)
    {
        int iAccessAllowed = Constants.ACCESS_DENIED;

        if (strSecurityMap == null)
            return iAccessAllowed;  // Denied
        if (LOGIN_REQUIRED.equalsIgnoreCase(strSecurityMap))
            return Constants.LOGIN_REQUIRED;  // Denied
        if (CREATE_USER_REQUIRED.equalsIgnoreCase(strSecurityMap))
            return Constants.CREATE_USER_REQUIRED;  // Denied
    	int startThin = strClassResource.indexOf(Constants.THIN_SUBPACKAGE, 0);
    	if (startThin != -1)	// Remove the ".thin" reference
    		strClassResource = strClassResource.substring(0, startThin) + strClassResource.substring(startThin + Constants.THIN_SUBPACKAGE.length());
        
        if (this.classMatch(strClassResource, BASE_CLASS))
            return Constants.NORMAL_RETURN;   // Allow access to all base classes
        StringTokenizer tokenizer = new StringTokenizer(strSecurityMap, TOKENS);
        try {
            while (tokenizer.hasMoreTokens())
            {
                String strClass = tokenizer.nextToken();
                String strAccess = tokenizer.nextToken();
                int iClassAccessType = Constants.READ_ACCESS;
                iClassAccessType = Integer.parseInt(strAccess);
                String strLevel = tokenizer.nextToken();
                int iClassLevel = Constants.LOGIN_USER;
                iClassLevel = Integer.parseInt(strLevel);
                
                if (this.classMatch(strClassResource, strClass))
                    if (iAccessType <= iClassAccessType)
                        if (iLevel >= iClassLevel)
                {
                    iAccessAllowed = Constants.NORMAL_RETURN;
                }
            }
        } catch (NoSuchElementException ex) {
            // Done
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        
        if (("1"/*DBConstants.ANON_USER_ID*/.equals(this.getProperty(Params.USER_ID)))
                || (this.getProperty(Params.USER_ID) == null))
            if (iAccessAllowed == Constants.ACCESS_DENIED)
                iAccessAllowed = Constants.LOGIN_REQUIRED;  // For anonymous access, logging in will always get you more
        
        return iAccessAllowed;
    }
339428
public void addGuarded(Guarded newGuarded, int mask) {
        this.guardedEntries.put(newGuarded, new Integer(mask));
        newGuarded.setEnabled(stateMatchesMask(getFormModelState(), mask));
    }
502270
@Override
    public List<Sync> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
        if (!checkConformance(t, args)) {
            return Collections.emptyList();
        }

        @SuppressWarnings("unchecked")
        List<VM> s = (List<VM>) params[0].transform(this, t, args.get(0));
        if (s == null) {
            return Collections.emptyList();
        }

        if (s.size() < 2) {
            t.ignoreError("Parameter '" + params[0].getName() + "' expects a list of at least 2 VMs");
            return Collections.emptyList();
        }
        return Collections.singletonList(new Sync(s));
    }
594476
protected void initSecurityConstraint(XmlParser.Node node)
    {
        try
        {
            SecurityConstraint scBase = new SecurityConstraint();
            XmlParser.Node auths = node.get("auth-constraint");
            if (auths != null)
            {
                scBase.setAuthenticate(true);
                // auth-constraint
                Iterator iter = auths.iterator("role-name");
                while (iter.hasNext())
                {
                    String role = ((XmlParser.Node) iter.next()).toString(false, true);
                    scBase.addRole(role);
                }
            }
            XmlParser.Node data = node.get("user-data-constraint");
            if (data != null)
            {
                data = data.get("transport-guarantee");
                String guarantee = data.toString(false, true).toUpperCase();
                if (guarantee == null || guarantee.length() == 0 || "NONE".equals(guarantee))
                    scBase.setDataConstraint(SecurityConstraint.DC_NONE);
                else if ("INTEGRAL".equals(guarantee))
                    scBase.setDataConstraint(SecurityConstraint.DC_INTEGRAL);
                else if ("CONFIDENTIAL".equals(guarantee))
                    scBase.setDataConstraint(SecurityConstraint.DC_CONFIDENTIAL);
                else
                {
                    log.warn("Unknown user-data-constraint:" + guarantee);
                    scBase.setDataConstraint(SecurityConstraint.DC_CONFIDENTIAL);
                }
            }
            Iterator iter = node.iterator("web-resource-collection");
            while (iter.hasNext())
            {
                XmlParser.Node collection = (XmlParser.Node) iter.next();
                String name = collection.getString("web-resource-name", false, true);
                SecurityConstraint sc = (SecurityConstraint) scBase.clone();
                sc.setName(name);
                Iterator iter2 = collection.iterator("http-method");
                while (iter2.hasNext())
                    sc.addMethod(((XmlParser.Node) iter2.next()).toString(false, true));
                iter2 = collection.iterator("url-pattern");
                while (iter2.hasNext())
                {
                    String url = ((XmlParser.Node) iter2.next()).toString(false, true);
                    getWebApplicationContext().addSecurityConstraint(url, sc);
                }
            }
        }
        catch (CloneNotSupportedException e)
        {
            log.fatal(e);
        }
    }
900987
private void configureSpringAuth() throws InstallationFailedException {
		String PATTERN = "${security.auth.filters}";
		String PATTERN_APIA = "${security.auth.filters.apia}";
		String PATTERN_REST = "${security.auth.filters.rest}";

		boolean fesl_authn_enabled = _opts.getBooleanValue(
InstallOptions.FESL_AUTHN_ENABLED, true);
		boolean apia_auth_required = _opts.getBooleanValue(
				InstallOptions.APIA_AUTH_REQUIRED, false);
		boolean upstream_auth_enabled = _opts.getBooleanValue(
				InstallOptions.UPSTREAM_AUTH_ENABLED, false);

		StringBuilder filters = new StringBuilder();
		StringBuilder filters_apia = new StringBuilder();
		StringBuilder filters_rest = new StringBuilder();

		boolean needsbugFix = false;

		if (fesl_authn_enabled) {
			filters.append("AuthFilterJAAS");
			filters_apia.append("AuthFilterJAAS");
			filters_rest.append("AuthFilterJAAS");
		} else if (upstream_auth_enabled) {
			// use upstream auth filter and nothing else
			String upstreamAuthFilter = "UpstreamAuthFilter";
			filters.append(upstreamAuthFilter);
			filters_apia.append(upstreamAuthFilter);
			filters_rest.append(upstreamAuthFilter);
		}
		else {
			filters.append("SetupFilter,XmlUserfileFilter,EnforceAuthnFilter,FinalizeFilter");
			if (apia_auth_required) {
				filters_apia
						.append("SetupFilter,XmlUserfileFilter,EnforceAuthnFilter,FinalizeFilter");
				filters_rest
						.append("SetupFilter,XmlUserfileFilter,EnforceAuthnFilter,FinalizeFilter");
			} else {
				filters_apia.append("");
				filters_rest
						.append("SetupFilter,XmlUserfileFilter,RestApiAuthnFilter,FinalizeFilter");
			}

			needsbugFix = true;
		}

		if (_opts.getBooleanValue(InstallOptions.FESL_AUTHZ_ENABLED, false)) {
			filters.append(",PEPFilter");
			filters_apia.append(",PEPFilter");
			filters_rest.append(",PEPFilter");
			copyFESLConfigs();
		}

		FileInputStream springConfig = null;
		PrintWriter writer = null;
		try {
			File xmlFile = new File(_installDir,
					"server/config/spring/web/security.xml");
			springConfig = new FileInputStream(xmlFile);
			String content = IOUtils.toString(springConfig)
					.replace(PATTERN, filters)
					.replace(PATTERN_APIA, filters_apia)
					.replace(PATTERN_REST, filters_rest);

			if (!needsbugFix) {
				/* Delete classic authN bugfix when not applicable */
				content = content.replaceFirst("(?s)<!-- BUG.+?/BUG -->", "");
			}

			springConfig.close();

			writer = new PrintWriter(new OutputStreamWriter(
					new FileOutputStream(xmlFile), "UTF-8"));
			writer.print(content);
			writer.close();
		} catch (Exception e) {
			IOUtils.closeQuietly(springConfig);
			IOUtils.closeQuietly(writer);
			throw new InstallationFailedException(e.getMessage(), e);
		}
	}
1077439
@Override
    public List<NoDelay> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
        if (checkConformance(t, args)) {
            @SuppressWarnings("unchecked")
            List<VM> s = (List<VM>) params[0].transform(this, t, args.get(0));
            return s != null ? NoDelay.newNoDelay(s) : Collections.emptyList();
        }
        return Collections.emptyList();
    }
903135
def setUp(self):
        '''
        '''
        toplist = filter(lambda wsa: wsa.ADDRESS==self.wsAddressURI, WSA_LIST)
        epr = 'EndpointReferenceType'
        for WSA in toplist+WSA_LIST:
            if (self.wsAddressURI is not None and self.wsAddressURI != WSA.ADDRESS) or \
                _has_type_definition(WSA.ADDRESS, epr) is True:
                break
        else:
            raise EvaluateException,\
                'enabling wsAddressing requires the inclusion of that namespace'

        self.wsAddressURI = WSA.ADDRESS
        self.anonymousURI = WSA.ANONYMOUS
        self._replyTo = WSA.ANONYMOUS
504869
private static TrustManagerFactory getTrustManagerFactory(InputStream trustStoreStream, StoreProperties storeProperties)
      throws IOException, GeneralSecurityException {

    // use provider if given, otherwise use the first matching security provider
    final KeyStore ks;
    if (StringUtils.isNotBlank(storeProperties.getProvider())) {
      ks = KeyStore.getInstance(storeProperties.getType(), storeProperties.getProvider());
    }
    else {
      ks = KeyStore.getInstance(storeProperties.getType());
    }

    ks.load(trustStoreStream, storeProperties.getPassword().toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(storeProperties.getManagerType());
    tmf.init(ks);
    return tmf;
  }
424831
void securityMessageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
        final boolean loggerIsEnabled = logger != null && logger.isTraceEnabled();

        if (! httpRequestMessageReceived(nextFilter, session, message)) return;

        HttpRequestMessage httpRequest = (HttpRequestMessage) message;
        ResourceAddress httpAddress = httpRequest.getLocalAddress();
        
        if (alreadyLoggedIn(httpRequest)) {
            // KG-3232, KG-3267: we should never leave the login context unset
            // for unprotected services.
            if (httpRequest.getLoginContext() == null) {
                setUnprotectedLoginContext(httpRequest);
            }
            if (loggerIsEnabled) {
                logger.trace("HttpSubjectSecurityFilter skipped because we are already allowed or logged in.");
            }

            super.doMessageReceived(nextFilter, session, message);
            return;
        }

        HttpRealmInfo[] realms = httpAddress.getOption(HttpResourceAddress.REALMS);
        if (realms.length == 0) {
            setUnprotectedLoginContext(httpRequest);
            if (loggerIsEnabled) {
                logger.trace("HttpSecurityStandardFilter skipped because no realm is configured.");
            }
            super.doMessageReceived(nextFilter, session, message);
            return;
        }
        
        String challengeIdentity = httpRequest.getHeader(HEADER_SEC_CHALLENGE_IDENTITY);
        LoginContext[] loginContexts = getLoginContexts(challengeIdentity);
        int realmIndex = findCurrentRealm(loginContexts);
        HttpRealmInfo realm = realms[realmIndex];

        AuthenticationTokenExtractor tokenExtractor = DefaultAuthenticationTokenExtractor.INSTANCE;

        //
        // Login using the token; if login fails, the appropriate reply has already been sent from this filter
        // so stop the filter chain here.
        //

        DefaultAuthenticationToken authToken = (DefaultAuthenticationToken) tokenExtractor.extract(httpRequest, realm);

        String expectedChallengeScheme = getBaseAuthScheme(realm.getChallengeScheme());

        // Now set the expected challenge scheme on the AuthToken.  If the
        // client provided a scheme, the above check ensures that the
        // provided scheme matches our expected scheme, so calling setScheme()
        // does not harm anything.  If the client did NOT provide a scheme,
        // this properly sets one, for the benefit of login modules which
        // check for such things.
        if(authToken.getScheme() == null) {
            authToken.setScheme(expectedChallengeScheme);
        }

        // Suspend incoming events into this filter. Will resume after LoginContext.login() completion
        suspendIncoming(session);

        TypedCallbackHandlerMap additionalCallbacks = null;
        if (realmIndex > 0) {
            additionalCallbacks = new TypedCallbackHandlerMap();
            Function<String, Subject> subjects = name -> findNamedSubject(name, realms, realmIndex, loginContexts);
            NamedSubjectCallbackHandler callbackHandler = new NamedSubjectCallbackHandler(subjects);
            additionalCallbacks.put(NamedSubjectCallback.class, callbackHandler);
        }

        // Schedule LoginContext.login() execution using a separate thread
        LoginContextTask loginContextTask = new LoginContextTask(nextFilter, session, httpRequest, authToken, additionalCallbacks, realms, realmIndex, loginContexts);
        scheduler.execute(loginContextTask);
    }
123096
function setupForCorporateProxy(proxyConfig) {
  if (!Array.isArray(proxyConfig)) {
    proxyConfig = [proxyConfig];
  }

  const proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;
  let agent = null;

  if (proxyServer) {
    console.log(`Using corporate proxy server: ${proxyServer}`);
    agent = new HttpsProxyAgent(proxyServer);
    proxyConfig.forEach(entry => { entry.agent = agent; });
  }

  return proxyConfig;
}
650189
public static void configureTls(ServerBuilder sb, Ssl ssl,
                                    @Nullable Supplier<KeyStore> keyStoreSupplier,
                                    @Nullable Supplier<KeyStore> trustStoreSupplier) {
        if (!ssl.isEnabled()) {
            return;
        }
        try {
            if (keyStoreSupplier == null && trustStoreSupplier == null &&
                ssl.getKeyStore() == null && ssl.getTrustStore() == null) {
                logger.warn("Configuring TLS with a self-signed certificate " +
                            "because no key or trust store was specified");
                sb.tlsSelfSigned();
                return;
            }

            final KeyManagerFactory keyManagerFactory = getKeyManagerFactory(ssl, keyStoreSupplier);
            final TrustManagerFactory trustManagerFactory = getTrustManagerFactory(ssl, trustStoreSupplier);

            sb.tls(keyManagerFactory, sslContextBuilder -> {
                sslContextBuilder.trustManager(trustManagerFactory);

                final SslProvider sslProvider = ssl.getProvider();
                if (sslProvider != null) {
                    sslContextBuilder.sslProvider(sslProvider);
                }
                final List<String> enabledProtocols = ssl.getEnabledProtocols();
                if (enabledProtocols != null) {
                    sslContextBuilder.protocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
                }
                final List<String> ciphers = ssl.getCiphers();
                if (ciphers != null) {
                    sslContextBuilder.ciphers(ImmutableList.copyOf(ciphers),
                                              SupportedCipherSuiteFilter.INSTANCE);
                }
                final ClientAuth clientAuth = ssl.getClientAuth();
                if (clientAuth != null) {
                    sslContextBuilder.clientAuth(clientAuth);
                }
            });
        } catch (Exception e) {
            throw new IllegalStateException("Failed to configure TLS: " + e, e);
        }
    }