use of org.ietf.jgss.GSSCredential in project calcite-avatica by apache.
the class HttpServerSpnegoWithJaasTest method testAuthenticatedClientsAllowed.
@Test
public void testAuthenticatedClientsAllowed() throws Exception {
Assume.assumeThat("Test disabled on Windows", File.separatorChar, is('/'));
// Create the subject for the client
final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(SpnegoTestUtil.CLIENT_PRINCIPAL, clientKeytab);
final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
// Make sure the subject has a principal
assertFalse(clientPrincipals.isEmpty());
// Get a TGT for the subject (might have many, different encryption types). The first should
// be the default encryption type.
Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
assertFalse(privateCredentials.isEmpty());
KerberosTicket tgt = privateCredentials.iterator().next();
assertNotNull(tgt);
LOG.info("Using TGT with etype: {}", tgt.getSessionKey().getAlgorithm());
// The name of the principal
final String principalName = clientPrincipals.iterator().next().getName();
// Run this code, logged in as the subject (the client)
byte[] response = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {
@Override
public byte[] run() throws Exception {
// Logs in with Kerberos via GSS
GSSManager gssManager = GSSManager.getInstance();
Oid oid = new Oid(SpnegoTestUtil.JGSS_KERBEROS_TICKET_OID);
GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
// Passes the GSSCredential into the HTTP client implementation
final AvaticaCommonsHttpClientSpnegoImpl httpClient = new AvaticaCommonsHttpClientSpnegoImpl(httpServerUrl, credential);
return httpClient.send(new byte[0]);
}
});
// We should get a response which is "OK" with our client's name
assertNotNull(response);
assertEquals("OK " + SpnegoTestUtil.CLIENT_PRINCIPAL, new String(response, StandardCharsets.UTF_8));
}
use of org.ietf.jgss.GSSCredential 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.GSSCredential in project hbase by apache.
the class TestSpnegoHttpServer method testAllowedClient.
@Test
public void testAllowedClient() throws Exception {
// Create the subject for the client
final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab);
final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
// Make sure the subject has a principal
assertFalse(clientPrincipals.isEmpty());
// Get a TGT for the subject (might have many, different encryption types). The first should
// be the default encryption type.
Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
assertFalse(privateCredentials.isEmpty());
KerberosTicket tgt = privateCredentials.iterator().next();
assertNotNull(tgt);
// The name of the principal
final String principalName = clientPrincipals.iterator().next().getName();
// Run this code, logged in as the subject (the client)
HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
@Override
public HttpResponse run() throws Exception {
// Logs in with Kerberos via GSS
GSSManager gssManager = GSSManager.getInstance();
// jGSS Kerberos login constant
Oid oid = new Oid("1.2.840.113554.1.2.2");
GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
HttpClientContext context = HttpClientContext.create();
Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();
HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build();
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
URL url = new URL(getServerURL(server), "/echo?a=b");
context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
context.setCredentialsProvider(credentialsProvider);
context.setAuthSchemeRegistry(authRegistry);
HttpGet get = new HttpGet(url.toURI());
return client.execute(get, context);
}
});
assertNotNull(resp);
assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode());
assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim());
}
use of org.ietf.jgss.GSSCredential 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.GSSCredential in project zookeeper by apache.
the class ZooKeeperSaslClient method createSaslClient.
private SaslClient createSaslClient(final String servicePrincipal, final String loginContext) throws LoginException {
try {
if (!initializedLogin) {
synchronized (this) {
if (login == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("JAAS loginContext is: " + loginContext);
}
// note that the login object is static: it's shared amongst all zookeeper-related connections.
// in order to ensure the login is initialized only once, it must be synchronized the code snippet.
login = new Login(loginContext, new ClientCallbackHandler(null), clientConfig);
login.startThreadIfNeeded();
initializedLogin = true;
}
}
}
Subject subject = login.getSubject();
SaslClient saslClient;
// if empty, use DIGEST-MD5; otherwise, use GSSAPI.
if (subject.getPrincipals().isEmpty()) {
// no principals: must not be GSSAPI: use DIGEST-MD5 mechanism instead.
LOG.info("Client will use DIGEST-MD5 as SASL mechanism.");
String[] mechs = { "DIGEST-MD5" };
String username = (String) (subject.getPublicCredentials().toArray()[0]);
String password = (String) (subject.getPrivateCredentials().toArray()[0]);
// "zk-sasl-md5" is a hard-wired 'domain' parameter shared with zookeeper server code (see ServerCnxnFactory.java)
saslClient = Sasl.createSaslClient(mechs, username, "zookeeper", "zk-sasl-md5", null, new ClientCallbackHandler(password));
return saslClient;
} else {
// GSSAPI.
boolean usingNativeJgss = clientConfig.getBoolean(ZKConfig.JGSS_NATIVE);
if (usingNativeJgss) {
// """
try {
GSSManager manager = GSSManager.getInstance();
Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2");
GSSCredential cred = manager.createCredential(null, GSSContext.DEFAULT_LIFETIME, krb5Mechanism, GSSCredential.INITIATE_ONLY);
subject.getPrivateCredentials().add(cred);
if (LOG.isDebugEnabled()) {
LOG.debug("Added private credential to subject: " + cred);
}
} catch (GSSException ex) {
LOG.warn("Cannot add private credential to subject; " + "authentication at the server may fail", ex);
}
}
final Object[] principals = subject.getPrincipals().toArray();
// determine client principal from subject.
final Principal clientPrincipal = (Principal) principals[0];
final KerberosName clientKerberosName = new KerberosName(clientPrincipal.getName());
// assume that server and client are in the same realm (by default; unless the system property
// "zookeeper.server.realm" is set).
String serverRealm = clientConfig.getProperty(ZKClientConfig.ZOOKEEPER_SERVER_REALM, clientKerberosName.getRealm());
KerberosName serviceKerberosName = new KerberosName(servicePrincipal + "@" + serverRealm);
final String serviceName = serviceKerberosName.getServiceName();
final String serviceHostname = serviceKerberosName.getHostName();
final String clientPrincipalName = clientKerberosName.toString();
try {
saslClient = Subject.doAs(subject, new PrivilegedExceptionAction<SaslClient>() {
public SaslClient run() throws SaslException {
LOG.info("Client will use GSSAPI as SASL mechanism.");
String[] mechs = { "GSSAPI" };
LOG.debug("creating sasl client: client=" + clientPrincipalName + ";service=" + serviceName + ";serviceHostname=" + serviceHostname);
SaslClient saslClient = Sasl.createSaslClient(mechs, clientPrincipalName, serviceName, serviceHostname, null, new ClientCallbackHandler(null));
return saslClient;
}
});
return saslClient;
} catch (Exception e) {
LOG.error("Exception while trying to create SASL client", e);
e.printStackTrace();
return null;
}
}
} catch (LoginException e) {
// We throw LoginExceptions...
throw e;
} catch (Exception e) {
// ..but consume (with a log message) all other types of exceptions.
LOG.error("Exception while trying to create SASL client: " + e);
return null;
}
}
Aggregations