public static void main(String[] args) throws Exception { GSSCredential cred = null; GSSContext ctx = GSSManager.getInstance().createContext(cred); String var = /*0000*/ "60 1C 06 06 2B 06 01 05 05 02 A0 12 30 10 A0 0E " + /*0010*/ "30 0C 06 0A 2B 06 01 04 01 82 37 02 02 0A "; byte[] token = new byte[var.length()/3]; for (int i=0; i<token.length; i++) { token[i] = Integer.valueOf(var.substring(3*i,3*i+2), 16).byteValue(); } try { ctx.acceptSecContext(token, 0, token.length); } catch (GSSException gsse) { System.out.println("Expected exception: " + gsse); } }
static void testBad(String s) throws Exception { System.err.println("Trying " + s); try { new ObjectIdentifier(s); throw new Exception("should be invalid ObjectIdentifier"); } catch (IOException ioe) { System.err.println(ioe); } try { new Oid(s); throw new Exception("should be invalid Oid"); } catch (GSSException gsse) { ; } try { new EncryptedPrivateKeyInfo(s, new byte[8]); throw new Exception("should be invalid algorithm"); } catch (NoSuchAlgorithmException e) { ; } }
/** * 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); }
/** * {@inheritDoc} */ @Override public Principal authenticate(GSSContext gssContext, boolean storeCreds) { if (gssContext.isEstablished()) { String username = null; GSSName name = null; try { name = gssContext.getSrcName(); } catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); return null; } username = name.toString(); Principal authenticatedUser = super.authenticate(gssContext, storeCreds); return filterLockedAccounts(username, authenticatedUser); } // Fail in all other cases return null; }
protected byte[] generateGSSToken( final byte[] input, final Oid oid ) throws GSSException { byte[] token = input; if (token == null) { token = new byte[0]; } GSSManager manager = getManager(); GSSName serverName = manager.createName(servicePrincipalName, servicePrincipalOid); GSSContext gssContext = manager.createContext(serverName.canonicalize(oid), oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); // Get client to login if not already done return gssClient.negotiate(gssContext, token); }
/** * Called when SPNEGO client-service authentication is taking place. * * @param context * @param negotiationToken * @return * @throws GSSException */ public byte[] negotiate( GSSContext context, byte[] negotiationToken ) throws GSSException { if (subject == null) { loginViaJAAS(); // throw GSSException if fail to login } // If we do not have the service ticket it will be retrieved // from the TGS on a call to initSecContext(). NegotiateContextAction negotiationAction = new NegotiateContextAction(context, negotiationToken); // Run the negotiation as the initiator // The service ticket will then be cached in the Subject's // private credentials, as the subject. negotiationToken = (byte[]) Subject.doAs(subject, negotiationAction); if (negotiationAction.getGSSException() != null) { throw negotiationAction.getGSSException(); } return negotiationToken; }
public Object run() { try { // If we do not have the service ticket it will be retrieved // from the TGS on the first call to initSecContext(). The // subject's private credentials are checked for the service ticket. // If we run this action as the initiator subject, the service ticket // will be stored in the subject's credentials and will not need // to be retrieved next time the client wishes to talk to the // server (acceptor). Subject subject = Subject.getSubject(AccessController.getContext()); int beforeNumSubjectCreds = traceBeforeNegotiate(); negotiationToken = context.initSecContext(negotiationToken, 0, negotiationToken.length); traceAfterNegotiate(beforeNumSubjectCreds); } catch (GSSException e) { // Trace out some info traceServiceTickets(); exception = e; } return negotiationToken; }
public static String validateServiceTicket(Subject subject, final byte[] serviceTicket) throws GSSException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException, PrivilegedActionException { // Kerberos version 5 OID Oid krb5Oid = KerberosUtils.getOidInstance("GSS_KRB5_MECH_OID"); // Accept the context and return the client principal name. return Subject.doAs(subject, new PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { String clientName = null; // Identify the server that communications are being made to. GSSManager manager = GSSManager.getInstance(); GSSContext context = manager.createContext((GSSCredential) null); context.acceptSecContext(serviceTicket, 0, serviceTicket.length); clientName = context.getSrcName().toString(); return clientName; } }); }
public static Oid getOidInstance(String oidName) throws ClassNotFoundException, GSSException, NoSuchFieldException, IllegalAccessException { Class<?> oidClass; if (IBM_JAVA) { if ("NT_GSS_KRB5_PRINCIPAL".equals(oidName)) { // IBM JDK GSSUtil class does not have field for krb5 principal oid return new Oid("1.2.840.113554.1.2.2.1"); } oidClass = Class.forName("com.ibm.security.jgss.GSSUtil"); } else { oidClass = Class.forName("sun.security.jgss.GSSUtil"); } Field oidField = oidClass.getDeclaredField(oidName); return (Oid)oidField.get(oidClass); }
/** * Logout. Since server uses LoginContext to login/pre-authenticate, we must * also logout when we are done using this object. * * <p> * Generally, instantiators of this class should be the only to call * dispose() as it indicates that this class will no longer be used. * </p> */ public void dispose() { if (null != this.serverCredentials) { try { this.serverCredentials.dispose(); } catch (GSSException e) { LOGGER.log(Level.WARNING, "Dispose failed.", e); } } if (null != this.loginContext) { try { this.loginContext.logout(); } catch (LoginException le) { LOGGER.log(Level.WARNING, "Logout failed.", le); } } }
/** * @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(service + "@" + 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); }
public static Oid getOidInstance(String oidName) throws ClassNotFoundException, GSSException, NoSuchFieldException, IllegalAccessException { Class<?> oidClass; if (IBM_JAVA) { if ("NT_GSS_KRB5_PRINCIPAL".equals(oidName)) { // IBM JDK GSSUtil class does not have field for krb5 principal oid return new Oid("1.2.840.113554.1.2.2.1"); } oidClass = Class.forName("com.ibm.security.jgss.GSSUtil"); } else { oidClass = Class.forName("sun.security.jgss.GSSUtil"); } Field oidField = oidClass.getDeclaredField(oidName); return (Oid) oidField.get(oidClass); }
@Test public void shouldFailAuthenticateWithPlainTextNoCredentials() throws Exception { final Cluster cluster = Cluster.build().create(); final Client client = cluster.connect(); try { client.submit("1+1").all().get(); fail("This should not succeed as the client did not provide credentials"); } catch(Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertEquals(GSSException.class, root.getClass()); // removed this assert as the text of the message changes based on kerberos config - stupid kerberos // assertThat(root.getMessage(), startsWith("Invalid name provided")); } finally { cluster.close(); } }
/** * Returns the GSS-API interface for creating a security context. * * @param subject the person to be authenticated * @return GSSCredential to be used for creating a security context. * @throws PrivilegedActionException */ public static GSSCredential getClientCredential(final Subject subject) throws PrivilegedActionException { final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { public GSSCredential run() throws GSSException { return MANAGER.createCredential( null , GSSCredential.DEFAULT_LIFETIME , SpnegoProvider.SPNEGO_OID , GSSCredential.INITIATE_ONLY); } }; return Subject.doAs(subject, action); }
/** * Returns the {@link GSSCredential} the server uses for pre-authentication. * * @param subject account server uses for pre-authentication * @return credential that allows server to authenticate clients * @throws PrivilegedActionException */ static GSSCredential getServerCredential(final Subject subject) throws PrivilegedActionException { final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { public GSSCredential run() throws GSSException { return MANAGER.createCredential( null , GSSCredential.INDEFINITE_LIFETIME , SpnegoProvider.SPNEGO_OID , GSSCredential.ACCEPT_ONLY); } }; return Subject.doAs(subject, action); }
/** * Process Kerberos token and get user name. * * @param gssToken GSS token * @return username Username of the logged in user if GSSToken can be decrypted correctly else return null * @throws GSSException */ public static String processToken(byte[] gssToken, GSSCredential gssCredentials) throws GSSException { GSSContext context = gssManager.createContext(gssCredentials); // Decrypt the kerberos ticket (GSS token) context.acceptSecContext(gssToken, 0, gssToken.length); // If we cannot decrypt the GSS Token properly we return the username as null. if (!context.isEstablished()) { log.error("Unable to decrypt the kerberos ticket as context was not established."); return null; } String loggedInUserName = context.getSrcName().toString(); String target = context.getTargName().toString(); if (log.isDebugEnabled()) { String msg = "Extracted details from GSS Token, LoggedIn User : " + loggedInUserName + " , Intended target : " + target; log.debug(msg); } return loggedInUserName; }
@Test public void testProcessLocalInvalidTokenException() throws Exception{ initCommonMocks(); setMockHttpSession(); setMockAuthenticationContext(); setMockIWAAuthenticationUtil(); setMockUserCoreUtil(); mockSession.setAttribute(IWAConstants.KERBEROS_TOKEN, Base64.encode("invalidKerberosTokenString".getBytes())); when(IWAAuthenticationUtil.processToken(any(byte[].class))).thenThrow(new GSSException(0)); try { iwaLocalAuthenticator.processAuthenticationResponse( mockHttpRequest, mockHttpResponse, mockAuthenticationContext); Assert.fail("Response processed with invalid kerberos token"); } catch (AuthenticationFailedException e) { Assert.assertTrue(e.getMessage().contains("Error while processing the GSS Token"), "Exception message has changed or exception thrown from an unintended code segment."); } }
@Test public void testCreateCredentialExceptions() throws Exception { setMockHttpSession(); setMockIWAAuthenticationUtil(); Map<String, String> map = new HashMap<>(); map.put(SPN_NAME, SPN_NAME_VALUE); map.put(SPN_PASSWORD, SPN_PASSWORD_VALUE); map.put(USER_STORE_DOMAINS, USER_STORE_DOMAINS_VALUE); when(mockAuthenticationContext.getAuthenticatorProperties()).thenReturn(map); mockSession.setAttribute(IWAConstants.KERBEROS_TOKEN, Base64.encode(token)); when(mockHttpRequest.getSession(anyBoolean())).thenReturn(mockSession); when(mockHttpRequest.getSession()).thenReturn(mockSession); when(IWAAuthenticationUtil.createCredentials(anyString(), any(char[].class))).thenThrow(new GSSException(0)); try { iwaFederatedAuthenticator.processAuthenticationResponse( mockHttpRequest, mockHttpResponse, mockAuthenticationContext); Assert.fail("Authentication response processed without creating GSSCredentials"); } catch (AuthenticationFailedException e) { Assert.assertTrue(e.getMessage().contains("Cannot create kerberos credentials for server")); } }
private Kerb5Context createContext(String host) throws GSSException{ Kerb5Context kerb5Context = new Kerb5Context( host, service, user, userLifetime, contextLifetime ); kerb5Context.getGSSContext().requestAnonymity(false); kerb5Context.getGSSContext().requestSequenceDet(false); kerb5Context.getGSSContext().requestMutualAuth(false); kerb5Context.getGSSContext().requestConf(false); kerb5Context.getGSSContext().requestInteg(false); kerb5Context.getGSSContext().requestReplayDet(false); return kerb5Context; }
/** * Encodes the authentication packet for supported authentication methods. * * @param request the socks proxy request data * @return the encoded buffer, if null then authentication step is over * and handshake process can jump immediately to the next step without waiting * for a server reply. * @throws UnsupportedEncodingException if some string charset convertion fails * @throws GSSException when something fails while using GSSAPI */ private IoBuffer encodeAuthenticationPacket(final SocksProxyRequest request) throws UnsupportedEncodingException, GSSException { byte method = ((Byte) getSession().getAttribute(Socks5LogicHandler.SELECTED_AUTH_METHOD)).byteValue(); switch (method) { case SocksProxyConstants.NO_AUTH: // In this case authentication is immediately considered as successfull // Next writeRequest() call will send the proxy request getSession().setAttribute(HANDSHAKE_STEP, SocksProxyConstants.SOCKS5_REQUEST_STEP); break; case SocksProxyConstants.GSSAPI_AUTH: return encodeGSSAPIAuthenticationPacket(request); case SocksProxyConstants.BASIC_AUTH: // The basic auth scheme packet is sent byte[] user = request.getUserName().getBytes("ASCII"); byte[] pwd = request.getPassword().getBytes("ASCII"); IoBuffer buf = IoBuffer.allocate(3 + user.length + pwd.length); buf.put(SocksProxyConstants.BASIC_AUTH_SUBNEGOTIATION_VERSION); buf.put((byte) user.length); buf.put(user); buf.put((byte) pwd.length); buf.put(pwd); return buf; } return null; }
private static GSSCredential getGSSCredential(final String userName) throws SaslException { try { Oid krb5Mechanism = new Oid(GSSAPI_OID); GSSManager manager = GSSManager.getInstance(); GSSName name = manager.createName(userName, GSSName.NT_USER_NAME); return manager.createCredential(name, GSSCredential.INDEFINITE_LIFETIME, krb5Mechanism, GSSCredential.INITIATE_ONLY); } catch (GSSException e) { throw new SaslException("Unable to create GSSAPI credential", e); } }
public AuthenticationMechanismOutcome 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()) { if (respToken != null) { // There will be no further challenge but we do have a token so set it here. exchange.getResponseHeaders().add(WWW_AUTHENTICATE, NEGOTIATE_PREFIX + FlexBase64.encodeString(respToken, false)); } IdentityManager identityManager = securityContext.getIdentityManager(); final Account account = identityManager.verify(new GSSContextCredential(negContext.getGssContext())); if (account != null) { securityContext.authenticationComplete(account, name, false); return AuthenticationMechanismOutcome.AUTHENTICATED; } else { return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } } else { // This isn't a failure but as the context is not established another round trip with the client is needed. return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } }
static GSSLibStub getInstance(Oid mech) throws GSSException { GSSLibStub s = table.get(mech); if (s == null) { s = new GSSLibStub(mech); table.put(mech, s); } return s; }
/** * Constructor * @throws java.io.IOException If negotiator cannot be constructed */ public NegotiatorImpl(HttpCallerInfo hci) throws IOException { try { init(hci); } catch (GSSException e) { if (DEBUG) { System.out.println("Negotiate support not initiated, will " + "fallback to other scheme if allowed. Reason:"); e.printStackTrace(); } IOException ioe = new IOException("Negotiate support not initiated"); ioe.initCause(e); throw ioe; } }
/** * Return the rest tokens of GSS, in SPNEGO, it's called NegTokenTarg * @param token the token received from server * @return the next token * @throws java.io.IOException if the token cannot be created successfully */ @Override public byte[] nextToken(byte[] token) throws IOException { try { return context.initSecContext(token, 0, token.length); } catch (GSSException e) { if (DEBUG) { System.out.println("Negotiate support cannot continue. Reason:"); e.printStackTrace(); } IOException ioe = new IOException("Negotiate support cannot continue"); ioe.initCause(e); throw ioe; } }
public void connect() throws IOException { lia.gsi.ssh.GSIAuthenticationClient gsiAuth = null; try { gsiAuth = new lia.gsi.ssh.GSIAuthenticationClient(); gsiAuth.setUsername(username); } catch (GSSException e) { throw new IOException("Cannot load grid credentials."); } conn = new SshClient(); SshToolsConnectionProfile properties = new SshToolsConnectionProfile(); // TODO: add new "port" parameter properties.setPort(port); properties.setForwardingAutoStartMode(false); properties.setHost(hostname); properties.setUsername(username); conn.setUseDefaultForwarding(false); conn.connect(properties); try { // Authenticate the user int result = conn.authenticate(gsiAuth, hostname); if (result != AuthenticationProtocolState.COMPLETE) { throw new IOException("GSI authentication failed"); } // Open a session channel sess = conn.openSessionChannel(); sess.requestPseudoTerminal("javash", 0, 0, 0, 0, ""); } catch (Throwable t) { throw new IOException(t.getMessage()); } }
public String getContact() { String gid = null; try { gid = getCredentials().getName().toString(); } catch (GSSException e) { return null; } StringBuffer url = new StringBuffer(); url.append(getHost()).append(":").append(String.valueOf(getPort())).append(":").append(gid); return url.toString(); }
private byte[] acqurieServiceTicket(Subject userSubject, String servicePrincipalName) { byte[] serviceTicket = null; try { serviceTicket = KerberosTicketOperations.acquireServiceTicket(userSubject, servicePrincipalName); } catch (GSSException | PrivilegedActionException | IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) { String errorMsg = "Error while acquiring service ticket for service '" + servicePrincipalName + "'"; logger.error(errorMsg); throw new AuthenticationFailedException(errorMsg, e); } return serviceTicket; }