private String getEncodedKerberosTicket(boolean spnego) throws Exception { System.setProperty("java.security.auth.login.config", "src/test/resources/kerberos.jaas"); System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true"); Oid kerberos5Oid = null; if (spnego) { kerberos5Oid = new Oid("1.3.6.1.5.5.2"); } else { kerberos5Oid = new Oid("1.2.840.113554.1.2.2"); } GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName("*****@*****.**", GSSName.NT_HOSTBASED_SERVICE); GSSContext context = manager.createContext( serverName.canonicalize(kerberos5Oid), kerberos5Oid, null, GSSContext.DEFAULT_LIFETIME); context.requestCredDeleg(true); final byte[] token = new byte[0]; String contextName = "alice"; LoginContext lc = new LoginContext(contextName); lc.login(); byte[] ticket = (byte[]) Subject.doAs(lc.getSubject(), new CreateServiceTicketAction(context, token)); return Base64.encode(ticket); }
/** @since 4.4 */ protected byte[] generateGSSToken( final byte[] input, final Oid oid, final String authServer, final Credentials credentials) throws GSSException { byte[] inputBuff = input; if (inputBuff == null) { inputBuff = new byte[0]; } final GSSManager manager = getManager(); final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); final GSSCredential gssCredential; if (credentials instanceof KerberosCredentials) { gssCredential = ((KerberosCredentials) credentials).getGSSCredential(); } else { gssCredential = null; } final GSSContext gssContext = manager.createContext( serverName.canonicalize(oid), oid, gssCredential, GSSContext.DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); return gssContext.initSecContext(inputBuff, 0, inputBuff.length); }
@Override public String run() throws HttpAuthenticationException { // Get own Kerberos credentials for accepting connection GSSManager manager = GSSManager.getInstance(); GSSContext gssContext = null; String serverPrincipal = getPrincipalWithoutRealm(serviceUGI.getUserName()); try { // This Oid for Kerberos GSS-API mechanism. Oid kerberosMechOid = new Oid("1.2.840.113554.1.2.2"); // Oid for SPNego GSS-API mechanism. Oid spnegoMechOid = new Oid("1.3.6.1.5.5.2"); // Oid for kerberos principal name Oid krb5PrincipalOid = new Oid("1.2.840.113554.1.2.2.1"); // GSS name for server GSSName serverName = manager.createName(serverPrincipal, krb5PrincipalOid); // GSS credentials for server GSSCredential serverCreds = manager.createCredential( serverName, GSSCredential.DEFAULT_LIFETIME, new Oid[] {kerberosMechOid, spnegoMechOid}, GSSCredential.ACCEPT_ONLY); // Create a GSS context gssContext = manager.createContext(serverCreds); // Get service ticket from the authorization header String serviceTicketBase64 = getAuthHeader(request, authType); byte[] inToken = Base64.decodeBase64(serviceTicketBase64.getBytes()); gssContext.acceptSecContext(inToken, 0, inToken.length); // Authenticate or deny based on its context completion if (!gssContext.isEstablished()) { throw new HttpAuthenticationException( "Kerberos authentication failed: " + "unable to establish context with the service ticket " + "provided by the client."); } else { return getPrincipalWithoutRealmAndHost(gssContext.getSrcName().toString()); } } catch (GSSException e) { throw new HttpAuthenticationException("Kerberos authentication failed: ", e); } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // No-op } } } }
/** * Closes the session. If any {@link GSSContext} is present in the session then it is closed. * * @param message the error message */ @Override protected void closeSession(String message) { GSSContext ctx = (GSSContext) getSession().getAttribute(GSS_CONTEXT); if (ctx != null) { try { ctx.dispose(); } catch (GSSException e) { e.printStackTrace(); super.closeSession(message, e); return; } } super.closeSession(message); }
@Override public GSSResult run() { GSSContext context = null; try { GSSManager manager = GSSManager.getInstance(); context = manager.createContext((GSSCredential) null); this.serviceTicket = context.acceptSecContext(this.serviceTicket, 0, this.serviceTicket.length); return new GSSResult(context, serviceTicket); } catch (GSSException e) { LogManager.logError( LogConstants.CTX_SECURITY, e, RuntimePlugin.Util.gs(RuntimePlugin.Event.TEIID40014)); } return null; }
protected byte[] generateGSSToken(final byte[] input, final Oid oid, final String authServer) throws GSSException { byte[] token = input; if (token == null) { token = new byte[0]; } final GSSManager manager = getManager(); final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); final GSSContext gssContext = manager.createContext(serverName.canonicalize(oid), oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); return gssContext.initSecContext(token, 0, token.length); }
public void authorize(GSSContext context, String host) throws AuthorizationException { String localID = this.getLocalID(context, host); if (localID == null) { String srcName; try { srcName = context == null ? "" : context.getSrcName().toString(); } catch (GSSException e) { srcName = ""; } throw new AuthorizationException("No local mapping for :" + srcName); } peerSubject = new Subject(); GlobusPrincipal nm; try { nm = JaasGssUtil.toGlobusPrincipal(context.getSrcName()); } catch (GSSException e) { throw new AuthorizationException("Cannot get peer DN"); } peerSubject.getPrincipals().add(nm); peerSubject.getPrincipals().add(new UserNamePrincipal(localID)); }
public String getValidatedPrincipal() { if (validatedContext == null) { return null; } try { return validatedContext.getSrcName().toString(); } catch (GSSException e) { logger.error("Error getting name: " + e); } return null; }
public byte[] createClientContext(ORB orb, Codec codec, CompoundSecMechList csmList) { byte[] contextToken = new byte[0]; if (csmList != null) { try { byte[] target = csmList.mechanism_list[0].as_context_mech.target_name; Oid krb5Oid = new Oid(KRB5MechOID.value.substring(4)); GSSManager gssManager = GSSManager.getInstance(); GSSName myPeer = gssManager.createName(target, null, krb5Oid); if (clientCreds == null) { clientCreds = gssManager.createCredential( null, GSSCredential.INDEFINITE_LIFETIME, krb5Oid, GSSCredential.INITIATE_ONLY); } GSSContext myContext = gssManager.createContext(myPeer, krb5Oid, clientCreds, GSSContext.INDEFINITE_LIFETIME); contextToken = myContext.initSecContext(contextToken, 0, contextToken.length); } catch (Exception e) { logger.error("Error creating Kerberos context: " + e); } } return contextToken; }
/** {@inheritDoc} */ @Override public Principal authenticate(GSSContext gssContext, boolean storeCred) { if (gssContext.isEstablished()) { GSSName gssName = null; try { gssName = gssContext.getSrcName(); } catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); } if (gssName != null) { String name = gssName.toString(); if (isStripRealmForGss()) { int i = name.indexOf('@'); if (i > 0) { // Zero so we don;t leave a zero length name name = name.substring(0, i); } } GSSCredential gssCredential = null; if (storeCred && gssContext.getCredDelegState()) { try { gssCredential = gssContext.getDelegCred(); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("realmBase.delegatedCredentialFail", name), e); } } } return getPrincipal(name, gssCredential); } } // Fail in all other cases return null; }
public byte[] createTicket() throws GSSException { // GSSAPI is generic, but if you give it the following Object ID, // it will create Kerberos 5 service tickets Oid kerberos5Oid = new Oid("1.2.840.113554.1.2.2"); // create a GSSManager, which will do the work GSSManager gssManager = GSSManager.getInstance(); // tell the GSSManager the Kerberos name of the client and service (substitute your appropriate // names here) GSSName clientName = gssManager.createName(client + "@INFINISPAN.ORG", GSSName.NT_USER_NAME); GSSName serviceName = gssManager.createName(service + "/[email protected]", GSSName.NT_HOSTBASED_SERVICE); // get the client's credentials. note that this run() method was called by Subject.doAs(), // so the client's credentials (Kerberos TGT or Ticket-Granting Ticket) are already available in // the Subject GSSCredential clientCredentials = gssManager.createCredential( clientName, 8 * 60 * 60, kerberos5Oid, GSSCredential.INITIATE_ONLY); // create a security context between the client and the service GSSContext gssContext = gssManager.createContext( serviceName, kerberos5Oid, clientCredentials, GSSContext.DEFAULT_LIFETIME); // initialize the security context // this operation will cause a Kerberos request of Active Directory, // to create a service ticket for the client to use the service byte[] serviceTicket = gssContext.initSecContext(new byte[0], 0, 0); System.out.println(new BASE64Encoder().encode(serviceTicket)); gssContext.dispose(); // return the Kerberos service ticket as an array of encrypted bytes return serviceTicket; }
Principal getPrincipal() { if (isEstablished() == false) { throw new IllegalStateException("No established GSSContext to use for the Principal."); } if (principal == null) { try { principal = new KerberosPrincipal(gssContext.getSrcName().toString()); } catch (GSSException e) { throw new IllegalStateException("Unable to create Principal", e); } } return principal; }
public Void run() throws GSSException { NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY); if (negContext == null) { negContext = new NegotiationContext(); exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext); // Also cache it on the connection for future calls. exchange.getConnection().putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext); } GSSContext gssContext = negContext.getGssContext(); if (gssContext == null) { GSSManager manager = GSSManager.getInstance(); gssContext = manager.createContext((GSSCredential) null); negContext.setGssContext(gssContext); } byte[] respToken = gssContext.acceptSecContext( challenge.array(), challenge.arrayOffset(), challenge.limit()); negContext.setResponseToken(respToken); if (negContext.isEstablished()) { result.setResult( new AuthenticationResult( negContext.getPrincipal(), AuthenticationOutcome.AUTHENTICATED)); } else { // This isn't a failure but as the context is not established another round trip with the // client is needed. result.setResult( new AuthenticationResult( negContext.getPrincipal(), AuthenticationOutcome.NOT_AUTHENTICATED)); } return null; }
public boolean validateContext(ORB orb, Codec codec, byte[] contextToken) { byte[] token = null; try { Oid krb5Oid = new Oid(KRB5MechOID.value.substring(4)); GSSManager gssManager = GSSManager.getInstance(); if (targetCreds == null) { targetCreds = gssManager.createCredential( null, GSSCredential.INDEFINITE_LIFETIME, krb5Oid, GSSCredential.ACCEPT_ONLY); } validatedContext = gssManager.createContext(targetCreds); token = validatedContext.acceptSecContext(contextToken, 0, contextToken.length); } catch (GSSException e) { logger.error("Error accepting Kerberos context: " + e); } if (token == null) { logger.warn("Could not accept token"); return false; } return true; }
public byte[] run() throws GSSException { return context.initSecContext(token, 0, token.length); }
/** * Encodes the authentication packet for supported authentication methods. * * @param request the socks proxy request data * @return the encoded buffer * @throws GSSException when something fails while using GSSAPI */ private IoBuffer encodeGSSAPIAuthenticationPacket(final SocksProxyRequest request) throws GSSException { GSSContext ctx = (GSSContext) getSession().getAttribute(GSS_CONTEXT); if (ctx == null) { // first step in the authentication process GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName(request.getServiceKerberosName(), null); Oid krb5OID = new Oid(SocksProxyConstants.KERBEROS_V5_OID); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Available mechs:"); for (Oid o : manager.getMechs()) { if (o.equals(krb5OID)) { LOGGER.debug("Found Kerberos V OID available"); } LOGGER.debug("{} with oid = {}", manager.getNamesForMech(o), o); } } ctx = manager.createContext(serverName, krb5OID, null, GSSContext.DEFAULT_LIFETIME); ctx.requestMutualAuth(true); // Mutual authentication ctx.requestConf(false); ctx.requestInteg(false); getSession().setAttribute(GSS_CONTEXT, ctx); } byte[] token = (byte[]) getSession().getAttribute(GSS_TOKEN); if (token != null) { LOGGER.debug(" Received Token[{}] = {}", token.length, ByteUtilities.asHex(token)); } IoBuffer buf = null; if (!ctx.isEstablished()) { // token is ignored on the first call if (token == null) { token = new byte[32]; } token = ctx.initSecContext(token, 0, token.length); // Send a token to the server if one was generated by // initSecContext if (token != null) { LOGGER.debug(" Sending Token[{}] = {}", token.length, ByteUtilities.asHex(token)); getSession().setAttribute(GSS_TOKEN, token); buf = IoBuffer.allocate(4 + token.length); buf.put( new byte[] { SocksProxyConstants.GSSAPI_AUTH_SUBNEGOTIATION_VERSION, SocksProxyConstants.GSSAPI_MSG_TYPE }); buf.put(ByteUtilities.intToNetworkByteOrder(token.length, 2)); buf.put(token); } } return buf; }
/** * Handle a SOCKS v5 response from the proxy server. * * @param nextFilter the next filter * @param buf the buffered data received * @param step the current step in the authentication process */ protected void handleResponse(final NextFilter nextFilter, final IoBuffer buf, int step) throws Exception { int len = 2; if (step == SocksProxyConstants.SOCKS5_GREETING_STEP) { // Send greeting message byte method = buf.get(1); if (method == SocksProxyConstants.NO_ACCEPTABLE_AUTH_METHOD) { throw new IllegalStateException( "No acceptable authentication method to use with " + "the socks proxy server"); } getSession().setAttribute(SELECTED_AUTH_METHOD, method); } else if (step == SocksProxyConstants.SOCKS5_AUTH_STEP) { // Authentication to the SOCKS server byte method = (Byte) getSession().getAttribute(Socks5LogicHandler.SELECTED_AUTH_METHOD); if (method == SocksProxyConstants.GSSAPI_AUTH) { int oldPos = buf.position(); if (buf.get(0) != 0x01) { throw new IllegalStateException("Authentication failed"); } if (buf.get(1) == 0xFF) { throw new IllegalStateException( "Authentication failed: GSS API Security Context Failure"); } if (buf.remaining() >= 2) { byte[] size = new byte[2]; buf.get(size); int s = ByteUtilities.makeIntFromByte2(size); if (buf.remaining() >= s) { byte[] token = new byte[s]; buf.get(token); getSession().setAttribute(GSS_TOKEN, token); len = 0; } else { // buf.position(oldPos); return; } } else { buf.position(oldPos); return; } } else if (buf.get(1) != SocksProxyConstants.V5_REPLY_SUCCEEDED) { throw new IllegalStateException("Authentication failed"); } } else if (step == SocksProxyConstants.SOCKS5_REQUEST_STEP) { // Send the request byte addressType = buf.get(3); len = 6; if (addressType == SocksProxyConstants.IPV6_ADDRESS_TYPE) { len += 16; } else if (addressType == SocksProxyConstants.IPV4_ADDRESS_TYPE) { len += 4; } else if (addressType == SocksProxyConstants.DOMAIN_NAME_ADDRESS_TYPE) { len += 1 + (buf.get(4)); } else { throw new IllegalStateException("Unknwon address type"); } if (buf.remaining() >= len) { // handle response byte status = buf.get(1); LOGGER.debug(" response status: {}", SocksProxyConstants.getReplyCodeAsString(status)); if (status == SocksProxyConstants.V5_REPLY_SUCCEEDED) { buf.position(buf.position() + len); setHandshakeComplete(); return; } throw new Exception( "Proxy handshake failed - Code: 0x" + ByteUtilities.asHex(new byte[] {status})); } return; } if (len > 0) { buf.position(buf.position() + len); } // Move to the handshaking next step if not in the middle of // the authentication process boolean isAuthenticating = false; if (step == SocksProxyConstants.SOCKS5_AUTH_STEP) { byte method = (Byte) getSession().getAttribute(Socks5LogicHandler.SELECTED_AUTH_METHOD); if (method == SocksProxyConstants.GSSAPI_AUTH) { GSSContext ctx = (GSSContext) getSession().getAttribute(GSS_CONTEXT); if (ctx == null || !ctx.isEstablished()) { isAuthenticating = true; } } } if (!isAuthenticating) { getSession().setAttribute(HANDSHAKE_STEP, ++step); } doHandshake(nextFilter); }
boolean isEstablished() { return gssContext != null ? gssContext.isEstablished() : false; }
@Override public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException { if (checkForCachedAuthentication(request, response, true)) { return true; } MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization"); if (authorization == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("authenticator.noAuthHeader")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.authHeaderNotNego")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorizationBC.setOffset(authorizationBC.getOffset() + 10); byte[] decoded = Base64.decodeBase64( authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength()); if (getApplyJava8u40Fix()) { SpnegoTokenFixer.fix(decoded); } if (decoded.length == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.authHeaderNoToken")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } LoginContext lc = null; GSSContext gssContext = null; byte[] outToken = null; Principal principal = null; try { try { lc = new LoginContext(getLoginConfigName()); lc.login(); } catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } Subject subject = lc.getSubject(); // Assume the GSSContext is stateless // TODO: Confirm this assumption final GSSManager manager = GSSManager.getInstance(); // IBM JDK only understands indefinite lifetime final int credentialLifetime; if (Globals.IS_IBM_JVM) { credentialLifetime = GSSCredential.INDEFINITE_LIFETIME; } else { credentialLifetime = GSSCredential.DEFAULT_LIFETIME; } final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws GSSException { return manager.createCredential( null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); } }; gssContext = manager.createContext(Subject.doAs(subject, action)); outToken = Subject.doAs(lc.getSubject(), new AcceptAction(gssContext, decoded)); if (outToken == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail")); } // Start again response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } principal = Subject.doAs( subject, new AuthenticateAction(context.getRealm(), gssContext, storeDelegatedCredential)); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if (cause instanceof GSSException) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); } } else { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } } // Send response token on success and failure response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encodeBase64String(outToken)); if (principal != null) { register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null); Pattern p = noKeepAliveUserAgents; if (p != null) { MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue("user-agent"); if (ua != null && p.matcher(ua.toString()).matches()) { response.setHeader("Connection", "close"); } } return true; } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }
public Object run() { try { org.ietf.jgss.Oid desiredMechs[] = new org.ietf.jgss.Oid[1]; desiredMechs[0] = new org.ietf.jgss.Oid("1.2.840.113554.1.2.2"); GSSManager manager = GSSManager.getInstance(); GSSName clientName = manager.createName(user, GSSName.NT_USER_NAME); GSSCredential clientCreds = manager.createCredential(clientName, 8 * 3600, desiredMechs, GSSCredential.INITIATE_ONLY); GSSName serverName = manager.createName(kerberosServerName + "@" + host, GSSName.NT_HOSTBASED_SERVICE); GSSContext secContext = manager.createContext( serverName, desiredMechs[0], clientCreds, GSSContext.DEFAULT_LIFETIME); secContext.requestMutualAuth(true); byte inToken[] = new byte[0]; byte outToken[] = null; boolean established = false; while (!established) { outToken = secContext.initSecContext(inToken, 0, inToken.length); if (outToken != null) { if (logger.logDebug()) logger.debug(" FE=> Password(GSS Authentication Token)"); pgStream.SendChar('p'); pgStream.SendInteger4(4 + outToken.length); pgStream.Send(outToken); pgStream.flush(); } if (!secContext.isEstablished()) { int response = pgStream.ReceiveChar(); // Error if (response == 'E') { int l_elen = pgStream.ReceiveInteger4(); ServerErrorMessage l_errorMsg = new ServerErrorMessage(pgStream.ReceiveString(l_elen - 4), logger.getLogLevel()); if (logger.logDebug()) logger.debug(" <=BE ErrorMessage(" + l_errorMsg + ")"); return new PSQLException(l_errorMsg); } else if (response == 'R') { if (logger.logDebug()) logger.debug(" <=BE AuthenticationGSSContinue"); int len = pgStream.ReceiveInteger4(); int type = pgStream.ReceiveInteger4(); // should check type = 8 inToken = pgStream.Receive(len - 8); } else { // Unknown/unexpected message type. return new PSQLException( GT.tr("Protocol error. Session setup failed."), PSQLState.CONNECTION_UNABLE_TO_CONNECT); } } else { established = true; } } } catch (IOException e) { return e; } catch (GSSException gsse) { return new PSQLException( GT.tr("GSS Authentication failed"), PSQLState.CONNECTION_FAILURE, gsse); } return null; }
public SpnegoAuthUser(GSSContext context) throws GSSException { this.principal = context.getSrcName().toString(); this.expiration = new Date().getTime() + 1000L * context.getLifetime(); }
@Override public byte[] run() throws GSSException { return gssContext.acceptSecContext(decoded, 0, decoded.length); }
public String generateToken(String authServer) throws Throwable { try { if (this.stripPort) { authServer = authServer.substring(0, authServer.indexOf(":")); } if (log.isDebugEnabled()) { log.debug("init " + authServer); } /* Using the SPNEGO OID is the correct method. * Kerberos v5 works for IIS but not JBoss. Unwrapping * the initial token when using SPNEGO OID looks like what is * described here... * * http://msdn.microsoft.com/en-us/library/ms995330.aspx * * Another helpful URL... * * http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/tsec_SPNEGO_token.html * * Unfortunately SPNEGO is JRE >=1.6. */ /** Try SPNEGO by default, fall back to Kerberos later if error */ negotiationOid = new Oid(SPNEGO_OID); boolean tryKerberos = false; try { GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName("HTTP/" + authServer, null); gssContext = manager.createContext( serverName.canonicalize(negotiationOid), negotiationOid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); } catch (GSSException ex) { log.error("generateToken", ex); // BAD MECH means we are likely to be using 1.5, fall back to Kerberos MECH. // Rethrow any other exception. if (ex.getMajor() == GSSException.BAD_MECH) { log.debug("GSSException BAD_MECH, retry with Kerberos MECH"); tryKerberos = true; } else { throw ex; } } if (tryKerberos) { /* Kerberos v5 GSS-API mechanism defined in RFC 1964.*/ log.debug("Using Kerberos MECH " + KERBEROS_OID); negotiationOid = new Oid(KERBEROS_OID); GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName("HTTP/" + authServer, null); gssContext = manager.createContext( serverName.canonicalize(negotiationOid), negotiationOid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); } if (token == null) { token = new byte[0]; } token = gssContext.initSecContext(token, 0, token.length); if (token == null) { throw new Exception("GSS security context initialization failed"); } /* * IIS accepts Kerberos and SPNEGO tokens. Some other servers Jboss, Glassfish? * seem to only accept SPNEGO. Below wraps Kerberos into SPNEGO token. */ if (spengoGenerator != null && negotiationOid.toString().equals(KERBEROS_OID)) { token = spengoGenerator.generateSpnegoDERObject(token); } String tokenstr = new String(Base64.encode(token)); if (log.isDebugEnabled()) { log.debug("Sending response '" + tokenstr + "' back to the auth server"); } return "Negotiate " + tokenstr; } catch (GSSException gsse) { log.error("generateToken", gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) throw new Exception(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.NO_CRED) throw new Exception(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new Exception(gsse.getMessage(), gsse); // other error throw new Exception(gsse.getMessage()); } catch (IOException ex) { throw new Exception(ex.getMessage()); } }
public void authenticate(AuthenticationProtocolClient authenticationprotocolclient, String s) throws IOException, TerminatedStateException { try { logger.finest("Registering gss-ssh return messages."); authenticationprotocolclient.registerMessage( com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiResponse.class, 60); authenticationprotocolclient.registerMessage( com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiToken.class, 61); authenticationprotocolclient.registerMessage( com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiError.class, 64); authenticationprotocolclient.registerMessage( com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiErrtok.class, 65); logger.finest("Sending gssapi user auth request."); ByteArrayWriter bytearraywriter = new ByteArrayWriter(); bytearraywriter.writeUINT32(new UnsignedInteger32(1L)); byte abyte0[] = GSSConstants.MECH_OID.getDER(); bytearraywriter.writeBinaryString(abyte0); logger.finest("Username:"******"gssapi", bytearraywriter.toByteArray()); authenticationprotocolclient.sendMessage(sshmsguserauthrequest); logger.finest("Receiving user auth response:"); SshMsgUserauthGssapiResponse sshmsguserauthgssapiresponse = (SshMsgUserauthGssapiResponse) authenticationprotocolclient.readMessage(60); ByteArrayReader bytearrayreader = new ByteArrayReader(sshmsguserauthgssapiresponse.getRequestData()); byte abyte1[] = bytearrayreader.readBinaryString(); if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "Mechanism requested: " + GSSConstants.MECH_OID); logger.log(Level.FINEST, "Mechanism selected: " + new Oid(abyte1)); logger.log(Level.FINEST, "Verify that selected mechanism is GSSAPI."); } if (!GSSConstants.MECH_OID.equals(new Oid(abyte1))) { logger.warning("Mechanism do not match!"); throw new IOException("Mechanism do not match!"); } logger.finest("Creating GSS context base on grid credentials."); GlobusGSSManagerImpl globusgssmanagerimpl = new GlobusGSSManagerImpl(); HostAuthorization gssAuth = new HostAuthorization(null); GSSName targetName = gssAuth.getExpectedName(null, hostname); GSSContext gsscontext = globusgssmanagerimpl.createContext( targetName, new Oid(abyte1), gsscredential, GSSCredential.INDEFINITE_LIFETIME - 1); gsscontext.requestCredDeleg(true); gsscontext.requestMutualAuth(true); gsscontext.requestReplayDet(true); gsscontext.requestSequenceDet(true); // MOD // gsscontext.requestConf(false); gsscontext.requestConf(true); Object type = GSIConstants.DELEGATION_TYPE_LIMITED; gsscontext.requestCredDeleg(false); ((ExtendedGSSContext) gsscontext).setOption(GSSConstants.DELEGATION_TYPE, type); logger.finest("Starting GSS token exchange."); byte abyte2[] = new byte[0]; do { if (gsscontext.isEstablished()) break; byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length); if (abyte3 != null) { ByteArrayWriter bytearraywriter1 = new ByteArrayWriter(); bytearraywriter1.writeBinaryString(abyte3); SshMsgUserauthGssapiToken sshmsguserauthgssapitoken = new SshMsgUserauthGssapiToken(bytearraywriter1.toByteArray()); authenticationprotocolclient.sendMessage(sshmsguserauthgssapitoken); } if (!gsscontext.isEstablished()) { SshMsgUserauthGssapiToken sshmsguserauthgssapitoken1 = (SshMsgUserauthGssapiToken) authenticationprotocolclient.readMessage(61); ByteArrayReader bytearrayreader1 = new ByteArrayReader(sshmsguserauthgssapitoken1.getRequestData()); abyte2 = bytearrayreader1.readBinaryString(); } } while (true); logger.log(Level.FINEST, "Sending gssapi exchange complete."); SshMsgUserauthGssapiExchangeComplete sshmsguserauthgssapiexchangecomplete = new SshMsgUserauthGssapiExchangeComplete(); authenticationprotocolclient.sendMessage(sshmsguserauthgssapiexchangecomplete); if (logger.isLoggable(Level.FINEST)) { logger.log( Level.FINEST, "Context established.\nInitiator : " + gsscontext.getSrcName() + "\nAcceptor : " + gsscontext.getTargName() + "\nLifetime : " + gsscontext.getLifetime() + "\nIntegrity : " + gsscontext.getIntegState() + "\nConfidentiality : " + gsscontext.getConfState() + "\nAnonymity : " + gsscontext.getAnonymityState()); } } catch (Throwable t) { logger.log(Level.WARNING, "Got Exception: ", t); throw new TerminatedStateException(AuthenticationProtocolState.FAILED); } }