Search in sources :

Example 46 with GSSCredential

use of org.ietf.jgss.GSSCredential in project polymap4-core by Polymap4.

the class SpnegoAuthenticator method doSpnegoAuth.

/**
 * Performs authentication using the SPNEGO mechanism.
 *
 * <p>
 * Returns null if authentication failed or if the provided
 * the auth scheme did not contain the SPNEGO/GSS token.
 * </p>
 *
 * @return SpnegoPrincipal for the given auth scheme.
 */
private SpnegoPrincipal doSpnegoAuth(final SpnegoAuthScheme scheme, final SpnegoHttpServletResponse resp) throws GSSException, IOException {
    final String principal;
    final byte[] gss = scheme.getToken();
    if (0 == gss.length) {
        LOGGER.finer("GSS data was NULL.");
        return null;
    }
    GSSContext context = null;
    GSSCredential delegCred = null;
    try {
        byte[] token = null;
        SpnegoAuthenticator.LOCK.lock();
        try {
            context = SpnegoAuthenticator.MANAGER.createContext(this.serverCredentials);
            token = context.acceptSecContext(gss, 0, gss.length);
        } finally {
            SpnegoAuthenticator.LOCK.unlock();
        }
        if (null == token) {
            LOGGER.finer("Token was NULL.");
            return null;
        }
        resp.setHeader(Constants.AUTHN_HEADER, Constants.NEGOTIATE_HEADER + ' ' + Base64.encode(token));
        if (!context.isEstablished()) {
            LOGGER.fine("context not established");
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED, true);
            return null;
        }
        principal = context.getSrcName().toString();
        if (this.allowDelegation && context.getCredDelegState()) {
            delegCred = context.getDelegCred();
        }
    } finally {
        if (null != context) {
            SpnegoAuthenticator.LOCK.lock();
            try {
                context.dispose();
            } finally {
                SpnegoAuthenticator.LOCK.unlock();
            }
        }
    }
    return new SpnegoPrincipal(principal, KerberosPrincipal.KRB_NT_PRINCIPAL, delegCred);
}
Also used : GSSCredential(org.ietf.jgss.GSSCredential) GSSContext(org.ietf.jgss.GSSContext)

Example 47 with GSSCredential

use of org.ietf.jgss.GSSCredential in project mssql-jdbc by Microsoft.

the class ConstrainedSample method main.

public static void main(String... args) throws Exception {
    Class.forName(DRIVER_CLASS_NAME).getConstructor().newInstance();
    System.out.println("Service subject: " + doInitialLogin());
    // Get impersonated user credentials thanks S4U2self mechanism
    GSSCredential impersonatedUserCreds = impersonate();
    System.out.println("Credentials for " + TARGET_USER_NAME + ": " + impersonatedUserCreds);
    // Create a connection for target service thanks S4U2proxy mechanism
    try (Connection con = createConnection(impersonatedUserCreds)) {
        System.out.println("Connection succesfully: " + con);
    }
}
Also used : GSSCredential(org.ietf.jgss.GSSCredential) ExtendedGSSCredential(com.sun.security.jgss.ExtendedGSSCredential) Connection(java.sql.Connection)

Example 48 with GSSCredential

use of org.ietf.jgss.GSSCredential in project mssql-jdbc by Microsoft.

the class SQLServerConnectionSecurityManager method connectInternal.

/**
 * Establish a physical database connection based on the user specified connection properties. Logon to the database.
 *
 * @param propsIn
 *            the connection properties
 * @param pooledConnection
 *            a parent pooled connection if this is a logical connection
 * @throws SQLServerException
 * @return the database connection
 */
Connection connectInternal(Properties propsIn, SQLServerPooledConnection pooledConnection) throws SQLServerException {
    try {
        activeConnectionProperties = (Properties) propsIn.clone();
        pooledConnectionParent = pooledConnection;
        String sPropKey;
        String sPropValue;
        sPropKey = SQLServerDriverStringProperty.USER.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = SQLServerDriverStringProperty.USER.getDefaultValue();
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        ValidateMaxSQLLoginName(sPropKey, sPropValue);
        sPropKey = SQLServerDriverStringProperty.PASSWORD.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = SQLServerDriverStringProperty.PASSWORD.getDefaultValue();
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        ValidateMaxSQLLoginName(sPropKey, sPropValue);
        sPropKey = SQLServerDriverStringProperty.DATABASE_NAME.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        ValidateMaxSQLLoginName(sPropKey, sPropValue);
        // if the user does not specify a default timeout,
        int loginTimeoutSeconds = SQLServerDriverIntProperty.LOGIN_TIMEOUT.getDefaultValue();
        // default is 15 per spec
        sPropValue = activeConnectionProperties.getProperty(SQLServerDriverIntProperty.LOGIN_TIMEOUT.toString());
        if (null != sPropValue && sPropValue.length() > 0) {
            try {
                loginTimeoutSeconds = Integer.parseInt(sPropValue);
            } catch (NumberFormatException e) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidTimeOut"));
                Object[] msgArgs = { sPropValue };
                SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
            }
            if (loginTimeoutSeconds < 0 || loginTimeoutSeconds > 65535) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidTimeOut"));
                Object[] msgArgs = { sPropValue };
                SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
            }
        }
        // Translates the serverName from Unicode to ASCII Compatible Encoding (ACE), as defined by the ToASCII operation of RFC 3490.
        sPropKey = SQLServerDriverBooleanProperty.SERVER_NAME_AS_ACE.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.SERVER_NAME_AS_ACE.getDefaultValue());
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        serverNameAsACE = booleanPropertyOn(sPropKey, sPropValue);
        // get the server name from the properties if it has instance name in it, getProperty the instance name
        // if there is a port number specified do not get the port number from the instance name
        sPropKey = SQLServerDriverStringProperty.SERVER_NAME.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = "localhost";
        }
        String sPropKeyPort = SQLServerDriverIntProperty.PORT_NUMBER.toString();
        String sPropValuePort = activeConnectionProperties.getProperty(sPropKeyPort);
        int px = sPropValue.indexOf('\\');
        String instanceValue = null;
        String instanceNameProperty = SQLServerDriverStringProperty.INSTANCE_NAME.toString();
        // found the instance name with the severname
        if (px >= 0) {
            instanceValue = sPropValue.substring(px + 1, sPropValue.length());
            ValidateMaxSQLLoginName(instanceNameProperty, instanceValue);
            sPropValue = sPropValue.substring(0, px);
        }
        trustedServerNameAE = sPropValue;
        if (true == serverNameAsACE) {
            try {
                sPropValue = IDN.toASCII(sPropValue);
            } catch (IllegalArgumentException ex) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_InvalidConnectionSetting"));
                Object[] msgArgs = { "serverNameAsACE", sPropValue };
                throw new SQLServerException(form.format(msgArgs), ex);
            }
        }
        activeConnectionProperties.setProperty(sPropKey, sPropValue);
        String instanceValueFromProp = activeConnectionProperties.getProperty(instanceNameProperty);
        // property takes precedence
        if (null != instanceValueFromProp)
            instanceValue = instanceValueFromProp;
        if (instanceValue != null) {
            ValidateMaxSQLLoginName(instanceNameProperty, instanceValue);
            // only get port if the port is not specified
            activeConnectionProperties.setProperty(instanceNameProperty, instanceValue);
            trustedServerNameAE += "\\" + instanceValue;
        }
        if (null != sPropValuePort) {
            trustedServerNameAE += ":" + sPropValuePort;
        }
        sPropKey = SQLServerDriverStringProperty.APPLICATION_NAME.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue != null)
            ValidateMaxSQLLoginName(sPropKey, sPropValue);
        else
            activeConnectionProperties.setProperty(sPropKey, SQLServerDriver.DEFAULT_APP_NAME);
        sPropKey = SQLServerDriverBooleanProperty.LAST_UPDATE_COUNT.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.LAST_UPDATE_COUNT.getDefaultValue());
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        sPropKey = SQLServerDriverStringProperty.COLUMN_ENCRYPTION.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null == sPropValue) {
            sPropValue = SQLServerDriverStringProperty.COLUMN_ENCRYPTION.getDefaultValue();
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        columnEncryptionSetting = ColumnEncryptionSetting.valueOfString(sPropValue).toString();
        sPropKey = SQLServerDriverStringProperty.KEY_STORE_AUTHENTICATION.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null != sPropValue) {
            keyStoreAuthentication = KeyStoreAuthentication.valueOfString(sPropValue).toString();
        }
        sPropKey = SQLServerDriverStringProperty.KEY_STORE_SECRET.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null != sPropValue) {
            keyStoreSecret = sPropValue;
        }
        sPropKey = SQLServerDriverStringProperty.KEY_STORE_LOCATION.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null != sPropValue) {
            keyStoreLocation = sPropValue;
        }
        registerKeyStoreProviderOnConnection(keyStoreAuthentication, keyStoreSecret, keyStoreLocation);
        sPropKey = SQLServerDriverBooleanProperty.MULTI_SUBNET_FAILOVER.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.MULTI_SUBNET_FAILOVER.getDefaultValue());
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        multiSubnetFailover = booleanPropertyOn(sPropKey, sPropValue);
        sPropKey = SQLServerDriverBooleanProperty.TRANSPARENT_NETWORK_IP_RESOLUTION.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            userSetTNIR = false;
            sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.TRANSPARENT_NETWORK_IP_RESOLUTION.getDefaultValue());
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        transparentNetworkIPResolution = booleanPropertyOn(sPropKey, sPropValue);
        sPropKey = SQLServerDriverBooleanProperty.ENCRYPT.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.ENCRYPT.getDefaultValue());
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        // Set requestedEncryptionLevel according to the value of the encrypt connection property
        requestedEncryptionLevel = booleanPropertyOn(sPropKey, sPropValue) ? TDS.ENCRYPT_ON : TDS.ENCRYPT_OFF;
        sPropKey = SQLServerDriverBooleanProperty.TRUST_SERVER_CERTIFICATE.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.TRUST_SERVER_CERTIFICATE.getDefaultValue());
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        trustServerCertificate = booleanPropertyOn(sPropKey, sPropValue);
        trustManagerClass = activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_MANAGER_CLASS.toString());
        trustManagerConstructorArg = activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_MANAGER_CONSTRUCTOR_ARG.toString());
        sPropKey = SQLServerDriverStringProperty.SELECT_METHOD.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null)
            sPropValue = SQLServerDriverStringProperty.SELECT_METHOD.getDefaultValue();
        if ("cursor".equalsIgnoreCase(sPropValue) || "direct".equalsIgnoreCase(sPropValue)) {
            activeConnectionProperties.setProperty(sPropKey, sPropValue.toLowerCase(Locale.ENGLISH));
        } else {
            MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidselectMethod"));
            Object[] msgArgs = { sPropValue };
            SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
        }
        sPropKey = SQLServerDriverStringProperty.RESPONSE_BUFFERING.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null)
            sPropValue = SQLServerDriverStringProperty.RESPONSE_BUFFERING.getDefaultValue();
        if ("full".equalsIgnoreCase(sPropValue) || "adaptive".equalsIgnoreCase(sPropValue)) {
            activeConnectionProperties.setProperty(sPropKey, sPropValue.toLowerCase(Locale.ENGLISH));
        } else {
            MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidresponseBuffering"));
            Object[] msgArgs = { sPropValue };
            SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
        }
        sPropKey = SQLServerDriverStringProperty.APPLICATION_INTENT.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null)
            sPropValue = SQLServerDriverStringProperty.APPLICATION_INTENT.getDefaultValue();
        applicationIntent = ApplicationIntent.valueOfString(sPropValue);
        activeConnectionProperties.setProperty(sPropKey, applicationIntent.toString());
        sPropKey = SQLServerDriverBooleanProperty.SEND_TIME_AS_DATETIME.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = Boolean.toString(SQLServerDriverBooleanProperty.SEND_TIME_AS_DATETIME.getDefaultValue());
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        }
        sendTimeAsDatetime = booleanPropertyOn(sPropKey, sPropValue);
        // Must be set before DISABLE_STATEMENT_POOLING
        sPropKey = SQLServerDriverIntProperty.STATEMENT_POOLING_CACHE_SIZE.toString();
        if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) {
            try {
                int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey));
                this.setStatementPoolingCacheSize(n);
            } catch (NumberFormatException e) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_statementPoolingCacheSize"));
                Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
            }
        }
        // Must be set after STATEMENT_POOLING_CACHE_SIZE
        sPropKey = SQLServerDriverBooleanProperty.DISABLE_STATEMENT_POOLING.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null != sPropValue) {
            setDisableStatementPooling(booleanPropertyOn(sPropKey, sPropValue));
        }
        sPropKey = SQLServerDriverBooleanProperty.INTEGRATED_SECURITY.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue != null) {
            integratedSecurity = booleanPropertyOn(sPropKey, sPropValue);
        }
        // Ignore authenticationScheme setting if integrated authentication not specified
        if (integratedSecurity) {
            sPropKey = SQLServerDriverStringProperty.AUTHENTICATION_SCHEME.toString();
            sPropValue = activeConnectionProperties.getProperty(sPropKey);
            if (sPropValue != null) {
                intAuthScheme = AuthenticationScheme.valueOfString(sPropValue);
            }
        }
        if (intAuthScheme == AuthenticationScheme.javaKerberos) {
            sPropKey = SQLServerDriverObjectProperty.GSS_CREDENTIAL.toString();
            if (activeConnectionProperties.containsKey(sPropKey))
                ImpersonatedUserCred = (GSSCredential) activeConnectionProperties.get(sPropKey);
        }
        sPropKey = SQLServerDriverStringProperty.AUTHENTICATION.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (sPropValue == null) {
            sPropValue = SQLServerDriverStringProperty.AUTHENTICATION.getDefaultValue();
        }
        authenticationString = SqlAuthentication.valueOfString(sPropValue).toString();
        if ((true == integratedSecurity) && (!authenticationString.equalsIgnoreCase(SqlAuthentication.NotSpecified.toString()))) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_SetAuthenticationWhenIntegratedSecurityTrue"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_SetAuthenticationWhenIntegratedSecurityTrue"), null);
        }
        if (authenticationString.equalsIgnoreCase(SqlAuthentication.ActiveDirectoryIntegrated.toString()) && ((!activeConnectionProperties.getProperty(SQLServerDriverStringProperty.USER.toString()).isEmpty()) || (!activeConnectionProperties.getProperty(SQLServerDriverStringProperty.PASSWORD.toString()).isEmpty()))) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_IntegratedAuthenticationWithUserPassword"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_IntegratedAuthenticationWithUserPassword"), null);
        }
        if (authenticationString.equalsIgnoreCase(SqlAuthentication.ActiveDirectoryPassword.toString()) && ((activeConnectionProperties.getProperty(SQLServerDriverStringProperty.USER.toString()).isEmpty()) || (activeConnectionProperties.getProperty(SQLServerDriverStringProperty.PASSWORD.toString()).isEmpty()))) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_NoUserPasswordForActivePassword"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_NoUserPasswordForActivePassword"), null);
        }
        if (authenticationString.equalsIgnoreCase(SqlAuthentication.SqlPassword.toString()) && ((activeConnectionProperties.getProperty(SQLServerDriverStringProperty.USER.toString()).isEmpty()) || (activeConnectionProperties.getProperty(SQLServerDriverStringProperty.PASSWORD.toString()).isEmpty()))) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_NoUserPasswordForSqlPassword"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_NoUserPasswordForSqlPassword"), null);
        }
        sPropKey = SQLServerDriverStringProperty.ACCESS_TOKEN.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null != sPropValue) {
            accessTokenInByte = sPropValue.getBytes(UTF_16LE);
        }
        if ((null != accessTokenInByte) && 0 == accessTokenInByte.length) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_AccessTokenCannotBeEmpty"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_AccessTokenCannotBeEmpty"), null);
        }
        if ((true == integratedSecurity) && (null != accessTokenInByte)) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_SetAccesstokenWhenIntegratedSecurityTrue"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_SetAccesstokenWhenIntegratedSecurityTrue"), null);
        }
        if ((!authenticationString.equalsIgnoreCase(SqlAuthentication.NotSpecified.toString())) && (null != accessTokenInByte)) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_SetBothAuthenticationAndAccessToken"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_SetBothAuthenticationAndAccessToken"), null);
        }
        if ((null != accessTokenInByte) && ((!activeConnectionProperties.getProperty(SQLServerDriverStringProperty.USER.toString()).isEmpty()) || (!activeConnectionProperties.getProperty(SQLServerDriverStringProperty.PASSWORD.toString()).isEmpty()))) {
            if (connectionlogger.isLoggable(Level.SEVERE)) {
                connectionlogger.severe(toString() + " " + SQLServerException.getErrString("R_AccessTokenWithUserPassword"));
            }
            throw new SQLServerException(SQLServerException.getErrString("R_AccessTokenWithUserPassword"), null);
        }
        // Turn off TNIR for FedAuth if user does not set TNIR explicitly
        if (!userSetTNIR) {
            if ((!authenticationString.equalsIgnoreCase(SqlAuthentication.NotSpecified.toString())) || (null != accessTokenInByte)) {
                transparentNetworkIPResolution = false;
            }
        }
        sPropKey = SQLServerDriverStringProperty.WORKSTATION_ID.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        ValidateMaxSQLLoginName(sPropKey, sPropValue);
        int nPort = 0;
        sPropKey = SQLServerDriverIntProperty.PORT_NUMBER.toString();
        try {
            String strPort = activeConnectionProperties.getProperty(sPropKey);
            if (null != strPort) {
                nPort = Integer.parseInt(strPort);
                if ((nPort < 0) || (nPort > 65535)) {
                    MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidPortNumber"));
                    Object[] msgArgs = { Integer.toString(nPort) };
                    SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
                }
            }
        } catch (NumberFormatException e) {
            MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidPortNumber"));
            Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
            SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
        }
        // Handle optional packetSize property
        sPropKey = SQLServerDriverIntProperty.PACKET_SIZE.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null != sPropValue && sPropValue.length() > 0) {
            try {
                requestedPacketSize = Integer.parseInt(sPropValue);
                // -1 --> Use server default
                if (-1 == requestedPacketSize)
                    requestedPacketSize = TDS.SERVER_PACKET_SIZE;
                else // 0 --> Use maximum size
                if (0 == requestedPacketSize)
                    requestedPacketSize = TDS.MAX_PACKET_SIZE;
            } catch (NumberFormatException e) {
                // Ensure that an invalid prop value results in an invalid packet size that
                // is not acceptable to the server.
                requestedPacketSize = TDS.INVALID_PACKET_SIZE;
            }
            if (TDS.SERVER_PACKET_SIZE != requestedPacketSize) {
                // Complain if the packet size is not in the range acceptable to the server.
                if (requestedPacketSize < TDS.MIN_PACKET_SIZE || requestedPacketSize > TDS.MAX_PACKET_SIZE) {
                    MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidPacketSize"));
                    Object[] msgArgs = { sPropValue };
                    SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
                }
            }
        }
        // Note booleanPropertyOn will throw exception if parsed value is not valid.
        // have to check for null before calling booleanPropertyOn, because booleanPropertyOn
        // assumes that the null property defaults to false.
        sPropKey = SQLServerDriverBooleanProperty.SEND_STRING_PARAMETERS_AS_UNICODE.toString();
        if (null == activeConnectionProperties.getProperty(sPropKey)) {
            sendStringParametersAsUnicode = SQLServerDriverBooleanProperty.SEND_STRING_PARAMETERS_AS_UNICODE.getDefaultValue();
        } else {
            sendStringParametersAsUnicode = booleanPropertyOn(sPropKey, activeConnectionProperties.getProperty(sPropKey));
        }
        sPropKey = SQLServerDriverBooleanProperty.LAST_UPDATE_COUNT.toString();
        lastUpdateCount = booleanPropertyOn(sPropKey, activeConnectionProperties.getProperty(sPropKey));
        sPropKey = SQLServerDriverBooleanProperty.XOPEN_STATES.toString();
        xopenStates = booleanPropertyOn(sPropKey, activeConnectionProperties.getProperty(sPropKey));
        sPropKey = SQLServerDriverStringProperty.SELECT_METHOD.toString();
        selectMethod = null;
        if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) {
            selectMethod = activeConnectionProperties.getProperty(sPropKey);
        }
        sPropKey = SQLServerDriverStringProperty.RESPONSE_BUFFERING.toString();
        responseBuffering = null;
        if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) {
            responseBuffering = activeConnectionProperties.getProperty(sPropKey);
        }
        sPropKey = SQLServerDriverIntProperty.LOCK_TIMEOUT.toString();
        int defaultLockTimeOut = SQLServerDriverIntProperty.LOCK_TIMEOUT.getDefaultValue();
        // Wait forever
        nLockTimeout = defaultLockTimeOut;
        if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) {
            try {
                int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey));
                if (n >= defaultLockTimeOut)
                    nLockTimeout = n;
                else {
                    MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidLockTimeOut"));
                    Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                    SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
                }
            } catch (NumberFormatException e) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidLockTimeOut"));
                Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
            }
        }
        sPropKey = SQLServerDriverIntProperty.QUERY_TIMEOUT.toString();
        int defaultQueryTimeout = SQLServerDriverIntProperty.QUERY_TIMEOUT.getDefaultValue();
        // Wait forever
        queryTimeoutSeconds = defaultQueryTimeout;
        if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) {
            try {
                int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey));
                if (n >= defaultQueryTimeout) {
                    queryTimeoutSeconds = n;
                } else {
                    MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidQueryTimeout"));
                    Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                    SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
                }
            } catch (NumberFormatException e) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidQueryTimeout"));
                Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
            }
        }
        sPropKey = SQLServerDriverIntProperty.SOCKET_TIMEOUT.toString();
        int defaultSocketTimeout = SQLServerDriverIntProperty.SOCKET_TIMEOUT.getDefaultValue();
        // Wait forever
        socketTimeoutMilliseconds = defaultSocketTimeout;
        if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) {
            try {
                int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey));
                if (n >= defaultSocketTimeout) {
                    socketTimeoutMilliseconds = n;
                } else {
                    MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidSocketTimeout"));
                    Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                    SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
                }
            } catch (NumberFormatException e) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidSocketTimeout"));
                Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
            }
        }
        sPropKey = SQLServerDriverIntProperty.SERVER_PREPARED_STATEMENT_DISCARD_THRESHOLD.toString();
        if (activeConnectionProperties.getProperty(sPropKey) != null && activeConnectionProperties.getProperty(sPropKey).length() > 0) {
            try {
                int n = Integer.parseInt(activeConnectionProperties.getProperty(sPropKey));
                setServerPreparedStatementDiscardThreshold(n);
            } catch (NumberFormatException e) {
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_serverPreparedStatementDiscardThreshold"));
                Object[] msgArgs = { activeConnectionProperties.getProperty(sPropKey) };
                SQLServerException.makeFromDriverError(this, this, form.format(msgArgs), null, false);
            }
        }
        sPropKey = SQLServerDriverBooleanProperty.ENABLE_PREPARE_ON_FIRST_PREPARED_STATEMENT.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null != sPropValue) {
            setEnablePrepareOnFirstPreparedStatementCall(booleanPropertyOn(sPropKey, sPropValue));
        }
        sPropKey = SQLServerDriverStringProperty.SSL_PROTOCOL.toString();
        sPropValue = activeConnectionProperties.getProperty(sPropKey);
        if (null == sPropValue) {
            sPropValue = SQLServerDriverStringProperty.SSL_PROTOCOL.getDefaultValue();
            activeConnectionProperties.setProperty(sPropKey, sPropValue);
        } else {
            activeConnectionProperties.setProperty(sPropKey, SSLProtocol.valueOfString(sPropValue).toString());
        }
        FailoverInfo fo = null;
        String databaseNameProperty = SQLServerDriverStringProperty.DATABASE_NAME.toString();
        String serverNameProperty = SQLServerDriverStringProperty.SERVER_NAME.toString();
        String failOverPartnerProperty = SQLServerDriverStringProperty.FAILOVER_PARTNER.toString();
        String failOverPartnerPropertyValue = activeConnectionProperties.getProperty(failOverPartnerProperty);
        // failoverPartner and multiSubnetFailover=true cannot be used together
        if (multiSubnetFailover && failOverPartnerPropertyValue != null) {
            SQLServerException.makeFromDriverError(this, this, SQLServerException.getErrString("R_dbMirroringWithMultiSubnetFailover"), null, false);
        }
        // transparentNetworkIPResolution is ignored if multiSubnetFailover or DBMirroring is true and user does not set TNIR explicitly
        if (multiSubnetFailover || (null != failOverPartnerPropertyValue)) {
            if (!userSetTNIR) {
                transparentNetworkIPResolution = false;
            }
        }
        // failoverPartner and applicationIntent=ReadOnly cannot be used together
        if ((applicationIntent != null) && applicationIntent.equals(ApplicationIntent.READ_ONLY) && failOverPartnerPropertyValue != null) {
            SQLServerException.makeFromDriverError(this, this, SQLServerException.getErrString("R_dbMirroringWithReadOnlyIntent"), null, false);
        }
        // check to see failover specified without DB error here if not.
        if (null != activeConnectionProperties.getProperty(databaseNameProperty)) {
            // look to see if there exists a failover
            fo = FailoverMapSingleton.getFailoverInfo(this, activeConnectionProperties.getProperty(serverNameProperty), activeConnectionProperties.getProperty(instanceNameProperty), activeConnectionProperties.getProperty(databaseNameProperty));
        } else {
            // it is an error to specify failover without db.
            if (null != failOverPartnerPropertyValue)
                SQLServerException.makeFromDriverError(this, this, SQLServerException.getErrString("R_failoverPartnerWithoutDB"), null, true);
        }
        String mirror = null;
        if (null == fo)
            mirror = failOverPartnerPropertyValue;
        long startTime = System.currentTimeMillis();
        login(activeConnectionProperties.getProperty(serverNameProperty), instanceValue, nPort, mirror, fo, loginTimeoutSeconds, startTime);
        // that the final negotiated TDS packet size is no larger than the SSL record size.
        if (TDS.ENCRYPT_ON == negotiatedEncryptionLevel || TDS.ENCRYPT_REQ == negotiatedEncryptionLevel) {
            // IBM (Websphere) security provider uses 8K SSL record size. All others use 16K.
            int sslRecordSize = Util.isIBM() ? 8192 : 16384;
            if (tdsPacketSize > sslRecordSize) {
                if (connectionlogger.isLoggable(Level.FINER)) {
                    connectionlogger.finer(toString() + " Negotiated tdsPacketSize " + tdsPacketSize + " is too large for SSL with JRE " + Util.SYSTEM_JRE + " (max size is " + sslRecordSize + ")");
                }
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_packetSizeTooBigForSSL"));
                Object[] msgArgs = { Integer.toString(sslRecordSize) };
                terminate(SQLServerException.DRIVER_ERROR_UNSUPPORTED_CONFIG, form.format(msgArgs));
            }
        }
        state = State.Opened;
        if (connectionlogger.isLoggable(Level.FINER)) {
            connectionlogger.finer(toString() + " End of connect");
        }
    } finally {
        // states, Opened or Closed(if an exception occurred)
        if (!state.equals(State.Opened)) {
            // if connection is not closed, close it
            if (!state.equals(State.Closed))
                this.close();
        }
    }
    return this;
}
Also used : MessageFormat(java.text.MessageFormat) GSSCredential(org.ietf.jgss.GSSCredential) Savepoint(java.sql.Savepoint)

Example 49 with GSSCredential

use of org.ietf.jgss.GSSCredential in project teiid by teiid.

the class WSConnectionImpl method setDispatchProperties.

private <T> void setDispatchProperties(Dispatch<T> dispatch, String binding) {
    if (this.mcf.getAsSecurityType() == WSManagedConnectionFactory.SecurityType.HTTPBasic || this.mcf.getAsSecurityType() == WSManagedConnectionFactory.SecurityType.Digest) {
        String userName = this.mcf.getAuthUserName();
        String password = this.mcf.getAuthPassword();
        // if security-domain is specified and caller identity is used; then use
        // credentials from subject
        Subject subject = ConnectionContext.getSubject();
        if (subject != null) {
            userName = ConnectionContext.getUserName(subject, this.mcf, userName);
            password = ConnectionContext.getPassword(subject, this.mcf, userName, password);
        }
        AuthorizationPolicy policy = new AuthorizationPolicy();
        policy.setUserName(userName);
        policy.setPassword(password);
        if (this.mcf.getAsSecurityType() == WSManagedConnectionFactory.SecurityType.Digest) {
            policy.setAuthorizationType("Digest");
        } else {
            policy.setAuthorizationType("Basic");
        }
        dispatch.getRequestContext().put(AuthorizationPolicy.class.getName(), policy);
    } else if (this.mcf.getAsSecurityType() == WSManagedConnectionFactory.SecurityType.Kerberos) {
        boolean credentialFound = false;
        Subject subject = ConnectionContext.getSubject();
        if (subject != null) {
            GSSCredential credential = ConnectionContext.getSecurityCredential(subject, GSSCredential.class);
            if (credential != null) {
                dispatch.getRequestContext().put(GSSCredential.class.getName(), credential);
                credentialFound = true;
            }
        }
        if (!credentialFound) {
            // $NON-NLS-1$
            throw new WebServiceException(WSManagedConnectionFactory.UTIL.getString("no_gss_credential"));
        }
    } else if (this.mcf.getAsSecurityType() == WSManagedConnectionFactory.SecurityType.OAuth) {
        boolean credentialFound = false;
        Subject subject = ConnectionContext.getSubject();
        if (subject != null) {
            OAuthCredential credential = ConnectionContext.getSecurityCredential(subject, OAuthCredential.class);
            if (credential != null) {
                dispatch.getRequestContext().put(OAuthCredential.class.getName(), credential);
                credentialFound = true;
            }
        }
        if (!credentialFound) {
            // $NON-NLS-1$
            throw new WebServiceException(WSManagedConnectionFactory.UTIL.getString("no_oauth_credential"));
        }
    }
    if (this.mcf.getRequestTimeout() != null) {
        dispatch.getRequestContext().put(RECEIVE_TIMEOUT, this.mcf.getRequestTimeout());
    }
    if (this.mcf.getConnectTimeout() != null) {
        dispatch.getRequestContext().put(CONNECTION_TIMEOUT, this.mcf.getConnectTimeout());
    }
    if (HTTPBinding.HTTP_BINDING.equals(binding)) {
        Map<String, List<String>> httpHeaders = (Map<String, List<String>>) dispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS);
        if (httpHeaders == null) {
            httpHeaders = new HashMap<String, List<String>>();
        }
        // $NON-NLS-1$ //$NON-NLS-2$
        httpHeaders.put("Content-Type", Collections.singletonList("text/xml; charset=utf-8"));
        // $NON-NLS-1$ //$NON-NLS-2$
        httpHeaders.put("User-Agent", Collections.singletonList("Teiid Server"));
        dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
    }
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) WebServiceException(javax.xml.ws.WebServiceException) GSSCredential(org.ietf.jgss.GSSCredential) List(java.util.List) ArrayList(java.util.ArrayList) OAuthCredential(org.teiid.OAuthCredential) Map(java.util.Map) HashMap(java.util.HashMap) Subject(javax.security.auth.Subject)

Example 50 with GSSCredential

use of org.ietf.jgss.GSSCredential in project calcite-avatica by apache.

the class PropertyBasedSpnegoLoginService method login.

@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
    String encodedAuthToken = (String) credentials;
    byte[] authToken = B64Code.decode(encodedAuthToken);
    GSSManager manager = GSSManager.getInstance();
    try {
        // http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/jgss-features.html
        Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
        Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssName = manager.createName(serverPrincipal, null);
        // CALCITE-1922 Providing both OIDs is the bug in Jetty we're working around. By specifying
        // only one, we're requiring that clients *must* provide us the SPNEGO OID to authenticate
        // via Kerberos which is wrong. Best as I can tell, the SPNEGO OID is meant as another
        // layer of indirection (essentially is equivalent to setting the Kerberos OID).
        GSSCredential serverCreds = manager.createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME, new Oid[] { krb5Oid, spnegoOid }, GSSCredential.ACCEPT_ONLY);
        GSSContext gContext = manager.createContext(serverCreds);
        if (gContext == null) {
            LOG.debug("SpnegoUserRealm: failed to establish GSSContext");
        } else {
            while (!gContext.isEstablished()) {
                authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
            }
            if (gContext.isEstablished()) {
                String clientName = gContext.getSrcName().toString();
                String role = clientName.substring(clientName.indexOf('@') + 1);
                LOG.debug("SpnegoUserRealm: established a security context");
                LOG.debug("Client Principal is: {}", gContext.getSrcName());
                LOG.debug("Server Principal is: {}", gContext.getTargName());
                LOG.debug("Client Default Role: {}", role);
                SpnegoUserPrincipal user = new SpnegoUserPrincipal(clientName, authToken);
                Subject subject = new Subject();
                subject.getPrincipals().add(user);
                return _identityService.newUserIdentity(subject, user, new String[] { role });
            }
        }
    } catch (GSSException gsse) {
        LOG.warn("Caught GSSException trying to authenticate the client", gsse);
    }
    return null;
}
Also used : GSSName(org.ietf.jgss.GSSName) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) Oid(org.ietf.jgss.Oid) SpnegoUserPrincipal(org.eclipse.jetty.security.SpnegoUserPrincipal) Subject(javax.security.auth.Subject)

Aggregations

GSSCredential (org.ietf.jgss.GSSCredential)65 GSSManager (org.ietf.jgss.GSSManager)38 Oid (org.ietf.jgss.Oid)36 GSSName (org.ietf.jgss.GSSName)34 GSSException (org.ietf.jgss.GSSException)33 GSSContext (org.ietf.jgss.GSSContext)28 Subject (javax.security.auth.Subject)22 PrivilegedActionException (java.security.PrivilegedActionException)19 Principal (java.security.Principal)18 IOException (java.io.IOException)9 LoginContext (javax.security.auth.login.LoginContext)9 LoginException (javax.security.auth.login.LoginException)9 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)8 KerberosCredentials (org.apache.http.auth.KerberosCredentials)7 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)6 SaslException (javax.security.sasl.SaslException)6 SPNegoSchemeFactory (org.apache.http.impl.auth.SPNegoSchemeFactory)4 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)4 Test (org.junit.Test)4 ExtendedGSSContext (com.sun.security.jgss.ExtendedGSSContext)3