Extract the context session key from the gssContext. The subject is only
used if no support for extraction of the session key is not possible
with an API and is used as a fallback method.

@param subject
@return context session key
@throws GSSException
169316
Key searchSessionKey(Subject subject) throws GSSException{
        /*
        The kerberos session key is not accessible via the JGSS API IBM and 
        Oracle both implement a similar API to make an ExtendedGSSContext
        available.
        
        The older implementation to find the session key is still available as 
        a fallback, but it is not expected, that it works.
        
        From "JCIFS with Kerberos doesn't work on JDK 7":
        
        https://bugs.openjdk.java.net/browse/JDK-8031973:
        
        This is a bug in JCIFS. It seems the SMB packet it generates that 
        includes the AP-REQ token also includes something else that should be 
        encrypted with the *context* session key. The standard GSS-API does not
        provide such a method so it looks up the service ticket in the subject 
        and use its *ticket* session key instead. The context session key is not 
        the ticket session key if sub key is used.
         
        Possible patch: Fix jcifs.smb.Kerb5Context's searchSessionKey() method 
        to call Oracle JDK's 
        ExtendedGSSContext::inquireSecContext(InquireType.KRB5_GET_SESSION_KEY) 
        to get the real session key. The classes are defined in 
        com.sun.security.jgss. 
        */
        
        if (extendedGSSContextClass == null || inquireTypeSessionKey == null
                || inquireSecContext == null || gssContext == null) {
            
            if(log.level > 0 && (! deprecationWarningPrinted)) {
                log.print("WARNING: Kerberos Session Key is extracted from Kerberos Ticket. This is known to be problematic (See: https://bugs.openjdk.java.net/browse/JDK-8031973).");
                deprecationWarningPrinted = true;
            }
            
            MIEName src = new MIEName(gssContext.getSrcName().export());
            MIEName targ = new MIEName(gssContext.getTargName().export());
            for(KerberosTicket ticket: subject.getPrivateCredentials(KerberosTicket.class)) {
                MIEName client = new MIEName(gssContext.getMech(), ticket.getClient().getName());
                MIEName server = new MIEName(gssContext.getMech(), ticket.getServer().getName());
                if (src.equals(client) && targ.equals(server)) {
                    return ticket.getSessionKey();
                }
            }
            return null;
        } else {
            if (extendedGSSContextClass.isAssignableFrom(gssContext.getClass())) {
                try {
                    return (Key) inquireSecContext.invoke(gssContext, new Object[]{inquireTypeSessionKey});
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                    log.print("Reflective access to ExtendedGSSContext failed");
                    ex.printStackTrace(log);
                }
            }
            return null;
        }
    }
758595
private SslContext getSslContext() {
        final SslContext sslCtx;
        if (clientConfig.isEnableTls()) {
            try {
                SslContextBuilder clientSslCtxBuilder = SslContextBuilder.forClient();
                if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                    clientSslCtxBuilder = clientSslCtxBuilder.trustManager(FingerprintTrustManagerFactory
                                                                                   .getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
                    log.debug("SslContextBuilder was set to an instance of {}", FingerprintTrustManagerFactory.class);
                } else {
                    clientSslCtxBuilder = SslContextBuilder.forClient()
                                                           .trustManager(new File(clientConfig.getTrustStore()));
                }
                sslCtx = clientSslCtxBuilder.build();
            } catch (SSLException | NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        } else {
            sslCtx = null;
        }
        return sslCtx;
    }
197441
public static Subject getJ2CInvocationSubject() {
        Subject j2cSubject = null;
        for (J2CIdentityService j2cIdentityService : j2cIdentityServices) {
            if (j2cIdentityService.isJ2CThreadIdentityEnabled()) {
                Subject subject = j2cIdentityService.getJ2CInvocationSubject();
                if (subject != null) {
                    j2cSubject = subject;
                    break;
                }
            }
        }
        return j2cSubject;
    }
747322
public ReferenceCountedOpenSslContext buildClientReferenceCountedOpenSslContext() throws SSLException {
        if (sslConfig.getTrustStore() != null) {
            sslContextBuilder = clientContextBuilderWithKs(SslProvider.OPENSSL);
        } else {
            sslContextBuilder = clientContextBuilderWithCerts(SslProvider.OPENSSL);
        }
        setOcspStapling(sslContextBuilder, true);
        if (sslConfig.getCipherSuites() != null) {
            List<String> ciphers = Arrays.asList(sslConfig.getCipherSuites());
            setCiphers(sslContextBuilder, ciphers);
        }
        setSslProtocol(sslContextBuilder);
        ReferenceCountedOpenSslContext referenceCountedOpenSslCtx = (ReferenceCountedOpenSslContext) sslContextBuilder
                .build();
        int sessionTimeout = sslConfig.getSessionTimeOut();
        if (sessionTimeout > 0) {
            referenceCountedOpenSslCtx.sessionContext().setSessionTimeout(sessionTimeout);
        }
        return referenceCountedOpenSslCtx;
    }
1302595
private static Subject setCallerSubject(Subject s) {
        Subject currentCallerSubject = null;
        SubjectManagerService sms = smServiceRef.getService();
        if (sms != null) {
            if (s == null) {
                s = new Subject();
            }
            currentCallerSubject = sms.getCallerSubject();
            sms.setCallerSubject(s);
        }
        return currentCallerSubject;
    }
1124150
protected Subject doHashTableLogin(Subject clientSubject, JaspiRequest jaspiRequest) throws WSLoginFailedException {
        Subject authenticatedSubject = null;
        final Hashtable<String, Object> hashTable = getCustomCredentials(clientSubject);
        String unauthenticatedSubjectString = UNAUTHENTICATED_ID;
        String user = null;
        if (hashTable == null) {
            // The JASPI provider did not add creds to the clientSubject. If we
            // have a session subject then just return success and we'll use the
            // session subject which has already been set on the thread
            Subject sessionSubject = getSessionSubject(jaspiRequest);
            if (sessionSubject != null) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "No HashTable returned by the JASPI provider. Using JASPI session subject.");
                return sessionSubject;
            }
            MessageInfo msgInfo = jaspiRequest.getMessageInfo();
            boolean isProtected = Boolean.parseBoolean((String) msgInfo.getMap().get(IS_MANDATORY_POLICY));
            if (isProtected) {
                String msg = "JASPI HashTable login cannot be performed, JASPI provider did not return a HashTable.";
                throw new WSLoginFailedException(msg);
            } else {
                user = unauthenticatedSubjectString;
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Web resource is unprotected and Subject does not have a HashTable.");
            }
        } else {
            user = (String) hashTable.get(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME);
        }
        boolean isUnauthenticated = unauthenticatedSubjectString.equals(user);
        if (isUnauthenticated) {
            authenticatedSubject = getUnauthenticatedSubject();
            if (tc.isDebugEnabled())
                Tr.debug(tc, "JASPI Subject is unauthenticated, HashTable login is not necessary.");
        } else {
            if (user == null)
                user = "";
            Subject loginSubject = clientSubject;
            // If we have a session subject then do the hashtable login with the session subject
            // so we pick up all the creds from the original session login. Add the custom
            // credential hashtable (that the JASPI provider returned) to the session subject.
            // Note we must "clone" the session subject as it is read only
            final Subject sessionSubject = getSessionSubject(jaspiRequest);
            if (sessionSubject != null) {
                final Subject clone = new Subject();
                clone.getPrivateCredentials().addAll(sessionSubject.getPrivateCredentials());
                clone.getPublicCredentials().addAll(sessionSubject.getPublicCredentials());
                clone.getPrincipals().addAll(sessionSubject.getPrincipals());
                // add the hashtable from the JASPI provider
                clone.getPrivateCredentials().add(hashTable);
                loginSubject = clone;
            }
            final HttpServletRequest req = jaspiRequest.getHttpServletRequest();
            final HttpServletResponse res = (HttpServletResponse) jaspiRequest.getMessageInfo().getResponseMessage();
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "JASPI login with HashTable: " + hashTable);
            }
            AuthenticationResult result = getWebProviderAuthenticatorHelper().loginWithHashtable(req, res, loginSubject);

            authenticatedSubject = result.getSubject();
            // Remove the custom credential hashtable from the session subject
            if (sessionSubject != null) {
                removeCustomCredentials(sessionSubject, hashTable);
            }
            if (authenticatedSubject == null) {
                throw new WSLoginFailedException("JASPI HashTable login failed, user: " + user);
            }
        }
        return authenticatedSubject;
    }
695047
public static byte[] initiateSecurityContext(Subject subject, String servicePrincipalName) throws GSSException {
        GSSManager manager    = GSSManager.getInstance();
        GSSName    serverName = manager.createName(servicePrincipalName, GSSName.NT_HOSTBASED_SERVICE);

        final GSSContext context = manager.createContext(serverName, krb5Oid, null, GSSContext.DEFAULT_LIFETIME);

        // The GSS context initiation has to be performed as a privileged action.
        return Subject.doAs(subject,
                            (PrivilegedAction<byte[]>)() -> {
                                try {
                                    byte[] token = new byte[0];
                                    // This is a one pass context initialization.
                                    context.requestMutualAuth(false);
                                    context.requestCredDeleg(false);
                                    return context.initSecContext(token, 0,
                                                                  token.length);
                                } catch (GSSException e) {
                                    log.error(Util.getMessage("Krb5TokenKerberosContextProcessingException"),e);
                                    return null;
                                }
                            });
    }
975159
def get_object_from_session(entity, key):
    
    def object_from_session_function(service, message):
        """Actual implementation of get_object_from_session function.

        :param service: SelenolService object.
        :param message: SelenolMessage request.
        """
        id_ = get_value_from_session(key)(service, message)
        result = service.session.query(entity).get(id_)
        if not result:
            raise SelenolInvalidArgumentException(key, id_)
        return result
    return object_from_session_function
1249825
public static Subject getSubject(UserGroupInformation ugi) {
    if (ugi == null) {
      return null;
    }
    
    Set<Principal> principals =       // Number of principals = username + #groups 
      new HashSet<Principal>(ugi.getGroupNames().length+1);
    User userPrincipal = new User(ugi.getUserName()); 
    principals.add(userPrincipal);
    for (String group : ugi.getGroupNames()) {
      Group groupPrincipal = new Group(group);
      principals.add(groupPrincipal);
    }
    principals.add(ugi);
    Subject user = 
      new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
    
    return user;
  }
775657
@SuppressWarnings("unchecked")
    public static Map<String, Set<String>> getAttributes(Subject subject) {
        Map<String, Set<String>> attributes = null;

        if (subject.getPublicCredentials() == null) {
            return new HashMap<String, Set<String>>();
        }

        @SuppressWarnings("rawtypes")
        Iterator<HashMap> credentialObjects = subject.getPublicCredentials(HashMap.class).iterator();
        while (attributes == null && credentialObjects.hasNext()) {
            HashMap<?,?> credentialObject = credentialObjects.next();

            if (logger.isDebugEnabled()) {
                logger.debug("checking for attributes (class name): "
                        + credentialObject.getClass().getName());
            }

            Object key = null;
            Iterator<?> keys = null;

            keys = credentialObject.keySet().iterator();
            if (!keys.hasNext()) {
                continue;
            }

            key = keys.next();

            if (logger.isDebugEnabled()) {
                logger.debug("checking for attributes (key object name): "
                        + key.getClass().getName());
            }

            if (!(key instanceof String)) {
                continue;
            }

            keys = credentialObject.values().iterator();
            if (!keys.hasNext()) {
                continue;
            }

            key = keys.next();

            if (logger.isDebugEnabled()) {
                logger.debug("checking for attributes (value object name): "
                        + key.getClass().getName());
            }

            if (!(key instanceof HashSet)) {
                continue;
            }

            attributes = (Map<String, Set<String>>) credentialObject;
        }

        if (attributes == null) {
            attributes = new HashMap<String, Set<String>>();
            subject.getPublicCredentials().add(attributes);
        }

        return attributes;
    }
116066
public static String kerberosChallenge(String server) throws AuthenticationException
  {
    kerberosLock.lock();
    try {
      // This Oid for Kerberos GSS-API mechanism.
      Oid mechOid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
      GSSManager manager = GSSManager.getInstance();
      // GSS name for server
      GSSName serverName = manager.createName("HTTP@" + server, GSSName.NT_HOSTBASED_SERVICE);
      // Create a GSSContext for authentication with the service.
      // We're passing client credentials as null since we want them to be read from the Subject.
      GSSContext gssContext =
          manager.createContext(serverName.canonicalize(mechOid), mechOid, null, GSSContext.DEFAULT_LIFETIME);
      gssContext.requestMutualAuth(true);
      gssContext.requestCredDeleg(true);
      // Establish context
      byte[] inToken = new byte[0];
      byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
      gssContext.dispose();
      // Base64 encoded and stringified token for server
      return new String(StringUtils.encodeBase64(outToken), StandardCharsets.US_ASCII);
    }
    catch (GSSException | IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) {
      throw new AuthenticationException(e);
    }
    finally {
      kerberosLock.unlock();
    }
  }
448658
@Override
    public SSLContext getSSLContext() throws KeyManagementException, UnrecoverableKeyException,
            NoSuchAlgorithmException, KeyStoreException {

        final SSLContext context = SSLContext.getInstance("TLS");

        String httpProtocols = System.getProperty("https.protocols");
        System.setProperty("https.protocols", "TLSv1");

        if (httpProtocols != null) {
            System.setProperty("https.protocols", httpProtocols);
        }

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory
                .getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePassword.toCharArray());
        context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[] {};
                    }

                    @Override
                    public void checkClientTrusted(final X509Certificate[] arg0, final String arg1) {

                    }

                    @Override
                    public void checkServerTrusted(final X509Certificate[] arg0, final String arg1) {

                    }
                }
        }, new SecureRandom());

        return context;
    }
196143
public String getRealm(Subject subject) throws Exception {
        String realm = null;
        WSCredential credential = getWSCredential(subject);
        if (credential != null) {
            realm = credential.getRealmName();
        }
        return realm;
    }
1047372
public PrivateKey getPrivateKey()
	throws GSSException {
        try {
	    return (this.cred == null) ? null : this.cred.getPrivateKey();
	} catch (CredentialException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }
    }
1187929
private Set<String> getUserRoles(Subject subject) {
        Set<String> userRoles = null;

        // get roles from specified classes
        Set<Principal> principals = subject.getPrincipals();
        if (roleClassNames != null && roleClassNames.size() > 0) {
            for (Principal p : principals) {
                if (roleClassNames.contains(p.getClass().getName())) {
                    if (userRoles == null) userRoles = new HashSet<String>();
                    userRoles.add(p.getName());
                }
            }
        }

        // get roles from specified attributes
        Map<String, Set<String>> attributes =
                SubjectUtils.getAttributes(subject);
        for (String key : attributes.keySet()) {
            if (roleAttributeNames.contains(key)) {
                if (userRoles == null) userRoles = new HashSet<String>();
                userRoles.addAll(attributes.get(key));
            }
        }

        if (userRoles == null) userRoles = Collections.emptySet();
        if (logger.isDebugEnabled()) {
            for (String r : userRoles) {
                logger.debug("found role: {}", r);
            }
        }

        return userRoles;
    }
1094115
public Subject getSubject(Subject subject) {
		Subject result = null;
		if(isSecurityEnabled) {
			/*
			 * Check if the SIBSecurity Service is loaded. If it is not loaded,
			 * load SIBSecurity Service Invoke the Login method of the
			 * SIBSecurity Service to get the Subject
			 * 
			 * Existing Code 
			 * String userName = getAuthorisationUtils().getUserName(subject); 
			 * SibLoginFactory loginFactory = SibLoginFactory.getInstance(); 
			 * SibLogin myLogin = loginFactory.createNewSibLogin(); 
			 * subject = myLogin.login(theBus, subject);
			 */
		} else {
			/*
			 * Create a JAVA Subject and return it, anyways it does not matter
			 */
			result = new Subject();
		}
		return result;
	}
937690
@Override
    public SSLContext getSSLContextInstance(final SSLConfig config) throws SSLException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getSSLContextInstance");

        if (config == null) {
            throw new IllegalArgumentException("SSL configuration is not specified.");
        }

        // now generate a new SSLContext
        final String ctxtProvider = config.getProperty(Constants.SSLPROP_CONTEXT_PROVIDER);
        final String protocol = config.getProperty(Constants.SSLPROP_PROTOCOL);
        final String alias = config.getProperty(Constants.SSLPROP_ALIAS);
        final String configURL = config.getProperty(Constants.SSLPROP_CONFIGURL_LOADED_FROM);

        SSLContext sslContext = null;

        if (protocol == null) {
            throw new IllegalArgumentException("Protocol is not specified.");
        }

        try {
            sslContext = AccessController.doPrivileged(new PrivilegedExceptionAction<SSLContext>() {
                @Override
                public SSLContext run() throws NoSuchAlgorithmException, NoSuchProviderException {
                    if (ctxtProvider != null)
                        return SSLContext.getInstance(protocol, ctxtProvider);
                    return SSLContext.getInstance(protocol);
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Exception occurred getting SSL context.", new Object[] { ex });

            if (ex instanceof NoSuchAlgorithmException) {
                String message = TraceNLSHelper.getInstance().getFormattedMessage("ssl.no.such.algorithm.CWPKI0028E",
                                                                                  new Object[] { protocol, alias, configURL, ex.getMessage() },
                                                                                  "CWPKI0028E: SSL handshake protocol " + protocol
                                                                                                                                                + " is not valid.  This protocol is specified in the SSL configuration alias "
                                                                                                                                                + alias
                                                                                                                                                + " loaded from SSL configuration file "
                                                                                                                                                + configURL
                                                                                                                                                + ".  The extended error message is: "
                                                                                                                                                + ex.getMessage() + ".");
                Tr.error(tc, "ssl.no.such.algorithm.CWPKI0028E",
                         new Object[] { protocol, alias, configURL, ex.getMessage() });
                throw new SSLException(message, ex);
            } else if (ex instanceof NoSuchProviderException) {
                String message = TraceNLSHelper.getInstance().getFormattedMessage("ssl.invalid.context.provider.CWPKI0029E",
                                                                                  new Object[] { Constants.IBMJSSE2_NAME, alias, configURL, ex.getMessage() },
                                                                                  "CWPKI0029E: SSL context provider " + Constants.IBMJSSE2_NAME
                                                                                                                                                               + " is not valid.  This provider is specified in the SSL configuration alias "
                                                                                                                                                               + alias
                                                                                                                                                               + " loaded from SSL configuration file "
                                                                                                                                                               + configURL
                                                                                                                                                               + ".  The extended error message is: "
                                                                                                                                                               + ex.getMessage()
                                                                                                                                                               + ".");
                Tr.error(tc, "ssl.invalid.context.provider.CWPKI0029E",
                         new Object[] { Constants.IBMJSSE2_NAME, alias, configURL, ex.getMessage() });
                throw new SSLException(message, ex);
            } else {
                throw new SSLException(ex);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getSSLContextInstance");
        return sslContext;
    }