use of org.ietf.jgss.GSSException in project wildfly by wildfly.
the class PropagateIdentityServlet method doGet.
// Protected methods -----------------------------------------------------
/**
* Retrieves a {@link GSSCredential} from {@link DelegationCredentialContext#getDelegCredential()}. If it's null error 401
* (SC_UNAUTHORIZED) is returned, otherwise {@link GSSTestClient} is used retrieve name of propagated identity from
* {@link GSSTestServer}.
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
LOGGER.debug("New request coming.");
final GSSCredential credential = DelegationCredentialContext.getDelegCredential();
if (credential == null) {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "GSSCredential not found");
} else {
resp.setContentType("text/plain");
final PrintWriter writer = resp.getWriter();
final GSSTestClient client = new GSSTestClient(StringUtils.strip(req.getServerName(), "[]"), GSSTestConstants.PORT, GSSTestConstants.PRINCIPAL);
LOGGER.trace("Client for identity propagation created: " + client);
try {
writer.print(client.getName(credential));
} catch (GSSException e) {
throw new ServletException("Propagation failed.", e);
}
}
}
use of org.ietf.jgss.GSSException in project wildfly by wildfly.
the class GSSTestClient method getName.
// Public methods --------------------------------------------------------
/**
* Retrieves the name of calling identity (based on given gssCredential) retrieved from {@link GSSTestServer}.
*
* @param gssCredential
* @return
* @throws IOException
* @throws GSSException
*/
public String getName(final GSSCredential gssCredential) throws IOException, GSSException {
LOGGER.trace("getName() called with GSSCredential:\n" + gssCredential);
// Create an unbound socket
final Socket socket = new Socket();
GSSContext gssContext = null;
try {
socket.connect(new InetSocketAddress(host, port), GSSTestConstants.SOCKET_TIMEOUT);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
LOGGER.debug("Sending NAME command.");
dos.writeInt(GSSTestConstants.CMD_NAME);
dos.flush();
GSSManager manager = GSSManager.getInstance();
gssContext = manager.createContext(manager.createName(spn, null), Constants.KERBEROS_V5, gssCredential, GSSContext.DEFAULT_LIFETIME);
// gssContext.requestCredDeleg(true);
gssContext.requestMutualAuth(true);
gssContext.requestConf(true);
gssContext.requestInteg(true);
byte[] token = new byte[0];
while (!gssContext.isEstablished()) {
token = gssContext.initSecContext(token, 0, token.length);
if (token != null) {
dos.writeInt(token.length);
dos.write(token);
dos.flush();
}
if (!gssContext.isEstablished()) {
token = new byte[dis.readInt()];
dis.readFully(token);
}
}
token = new byte[dis.readInt()];
dis.readFully(token);
MessageProp msgProp = new MessageProp(false);
final byte[] nameBytes = gssContext.unwrap(token, 0, token.length, msgProp);
return new String(nameBytes, GSSTestConstants.CHAR_ENC);
} catch (IOException e) {
LOGGER.error("IOException occurred.", e);
throw e;
} finally {
try {
socket.close();
} catch (IOException e) {
LOGGER.error("IOException occurred", e);
}
if (gssContext != null) {
try {
gssContext.dispose();
} catch (GSSException e) {
LOGGER.error("GSSException occurred", e);
}
}
}
}
use of org.ietf.jgss.GSSException in project wildfly by wildfly.
the class JBossNegotiateScheme method authenticate.
/**
* Produces Negotiate authorization Header based on token created by processChallenge.
*
* @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
* from JAAS will be used instead.
* @param request The request being authenticated
*
* @throws AuthenticationException if authorization string cannot be generated due to an authentication failure
*
* @return an Negotiate authorization Header
*/
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (state == State.TOKEN_GENERATED) {
// hack for auto redirects
return new BasicHeader("X-dummy", "Token already generated");
}
if (state != State.CHALLENGE_RECEIVED) {
throw new IllegalStateException("Negotiation authentication process has not been initiated");
}
try {
String key = null;
if (isProxy()) {
key = ExecutionContext.HTTP_PROXY_HOST;
} else {
key = HttpCoreContext.HTTP_TARGET_HOST;
}
HttpHost host = (HttpHost) context.getAttribute(key);
if (host == null) {
throw new AuthenticationException("Authentication host is not set " + "in the execution context");
}
String authServer;
if (!this.stripPort && host.getPort() > 0) {
authServer = host.toHostString();
} else {
authServer = host.getHostName();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("init " + authServer);
}
final Oid negotiationOid = new Oid(SPNEGO_OID);
final GSSManager manager = GSSManager.getInstance();
final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, 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) {
state = State.FAILED;
throw new AuthenticationException("GSS security context initialization failed");
}
state = State.TOKEN_GENERATED;
String tokenstr = new String(base64codec.encode(token));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending response '" + tokenstr + "' back to the auth server");
}
CharArrayBuffer buffer = new CharArrayBuffer(32);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Negotiate ");
buffer.append(tokenstr);
return new BufferedHeader(buffer);
} catch (GSSException gsse) {
state = State.FAILED;
if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.NO_CRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN)
throw new AuthenticationException(gsse.getMessage(), gsse);
// other error
throw new AuthenticationException(gsse.getMessage());
}
}
use of org.ietf.jgss.GSSException in project kafka by apache.
the class SaslServerAuthenticator method createSaslKerberosServer.
private SaslServer createSaslKerberosServer(final AuthCallbackHandler saslServerCallbackHandler, final Map<String, ?> configs) throws IOException {
// server is using a JAAS-authenticated subject: determine service principal name and hostname from kafka server's subject.
final Principal servicePrincipal = subject.getPrincipals().iterator().next();
KerberosName kerberosName;
try {
kerberosName = KerberosName.parse(servicePrincipal.getName());
} catch (IllegalArgumentException e) {
throw new KafkaException("Principal has name with unexpected format " + servicePrincipal);
}
final String servicePrincipalName = kerberosName.serviceName();
final String serviceHostname = kerberosName.hostName();
LOG.debug("Creating SaslServer for {} with mechanism {}", kerberosName, saslMechanism);
// As described in http://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/jgss-features.html:
// "To enable Java GSS to delegate to the native GSS library and its list of native mechanisms,
// set the system property "sun.security.jgss.native" to true"
// "In addition, when performing operations as a particular Subject, for example, Subject.doAs(...)
// or Subject.doAsPrivileged(...), the to-be-used GSSCredential should be added to Subject's
// private credential set. Otherwise, the GSS operations will fail since no credential is found."
boolean usingNativeJgss = Boolean.getBoolean("sun.security.jgss.native");
if (usingNativeJgss) {
try {
GSSManager manager = GSSManager.getInstance();
// This Oid is used to represent the Kerberos version 5 GSS-API mechanism. It is defined in
// RFC 1964.
Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2");
GSSName gssName = manager.createName(servicePrincipalName + "@" + serviceHostname, GSSName.NT_HOSTBASED_SERVICE);
GSSCredential cred = manager.createCredential(gssName, GSSContext.INDEFINITE_LIFETIME, krb5Mechanism, GSSCredential.ACCEPT_ONLY);
subject.getPrivateCredentials().add(cred);
} catch (GSSException ex) {
LOG.warn("Cannot add private credential to subject; clients authentication may fail", ex);
}
}
try {
return Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() {
public SaslServer run() throws SaslException {
return Sasl.createSaslServer(saslMechanism, servicePrincipalName, serviceHostname, configs, saslServerCallbackHandler);
}
});
} catch (PrivilegedActionException e) {
throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication", e.getCause());
}
}
use of org.ietf.jgss.GSSException in project tomcat by apache.
the class LockOutRealm method authenticate.
/**
* {@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;
}
Aggregations