use of org.ietf.jgss.GSSException in project tigervnc by TigerVNC.
the class GSSContextKrb5 method create.
public void create(String user, String host) throws JSchException {
try {
// RFC 1964
Oid krb5 = new Oid("1.2.840.113554.1.2.2");
// Kerberos Principal Name Form
Oid principalName = new Oid("1.2.840.113554.1.2.2.1");
GSSManager mgr = GSSManager.getInstance();
GSSCredential crd = null;
/*
try{
GSSName _user=mgr.createName(user, principalName);
crd=mgr.createCredential(_user,
GSSCredential.DEFAULT_LIFETIME,
krb5,
GSSCredential.INITIATE_ONLY);
}
catch(GSSException crdex){
}
*/
String cname = host;
try {
cname = InetAddress.getByName(cname).getCanonicalHostName();
} catch (UnknownHostException e) {
}
GSSName _host = mgr.createName("host/" + cname, principalName);
context = mgr.createContext(_host, krb5, crd, GSSContext.DEFAULT_LIFETIME);
// RFC4462 3.4. GSS-API Session
//
// When calling GSS_Init_sec_context(), the client MUST set
// integ_req_flag to "true" to request that per-message integrity
// protection be supported for this context. In addition,
// deleg_req_flag MAY be set to "true" to request access delegation, if
// requested by the user.
//
// Since the user authentication process by its nature authenticates
// only the client, the setting of mutual_req_flag is not needed for
// this process. This flag SHOULD be set to "false".
// TODO: OpenSSH's sshd does accepts 'false' for mutual_req_flag
// context.requestMutualAuth(false);
context.requestMutualAuth(true);
context.requestConf(true);
// for MIC
context.requestInteg(true);
context.requestCredDeleg(true);
context.requestAnonymity(false);
return;
} catch (GSSException ex) {
throw new JSchException(ex.toString());
}
}
use of org.ietf.jgss.GSSException in project async-http-client by AsyncHttpClient.
the class SpnegoEngine method generateToken.
public String generateToken(String host) throws SpnegoEngineException {
GSSContext gssContext = null;
// base64 decoded challenge
byte[] token = null;
Oid negotiationOid;
try {
/*
* 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;
String spn = getCompleteServicePrincipalName(host);
try {
GSSManager manager = GSSManager.getInstance();
GSSName serverName = manager.createName(spn, GSSName.NT_HOSTBASED_SERVICE);
GSSCredential myCred = null;
if (username != null || loginContextName != null || (customLoginConfig != null && !customLoginConfig.isEmpty())) {
String contextName = loginContextName;
if (contextName == null) {
contextName = "";
}
LoginContext loginContext = new LoginContext(contextName, null, getUsernamePasswordHandler(), getLoginConfiguration());
loginContext.login();
final Oid negotiationOidFinal = negotiationOid;
final PrivilegedExceptionAction<GSSCredential> action = () -> manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, negotiationOidFinal, GSSCredential.INITIATE_AND_ACCEPT);
myCred = Subject.doAs(loginContext.getSubject(), action);
}
gssContext = manager.createContext(useCanonicalHostname ? serverName.canonicalize(negotiationOid) : serverName, negotiationOid, myCred, GSSContext.DEFAULT_LIFETIME);
gssContext.requestMutualAuth(true);
gssContext.requestCredDeleg(true);
} catch (GSSException ex) {
log.error("generateToken", ex);
// 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(spn, GSSName.NT_HOSTBASED_SERVICE);
gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, GSSContext.DEFAULT_LIFETIME);
gssContext.requestMutualAuth(true);
gssContext.requestCredDeleg(true);
}
// TODO suspicious: this will always be null because no value has been assigned before. Assign directly?
if (token == null) {
token = new byte[0];
}
token = gssContext.initSecContext(token, 0, token.length);
if (token == null) {
throw new SpnegoEngineException("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 (spnegoGenerator != null && negotiationOid.toString().equals(KERBEROS_OID)) {
token = spnegoGenerator.generateSpnegoDERObject(token);
}
gssContext.dispose();
String tokenstr = Base64.getEncoder().encodeToString(token);
log.debug("Sending response '{}' back to the server", tokenstr);
return tokenstr;
} catch (GSSException gsse) {
log.error("generateToken", gsse);
if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
throw new SpnegoEngineException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.NO_CRED)
throw new SpnegoEngineException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN)
throw new SpnegoEngineException(gsse.getMessage(), gsse);
// other error
throw new SpnegoEngineException(gsse.getMessage());
} catch (IOException | LoginException | PrivilegedActionException ex) {
throw new SpnegoEngineException(ex.getMessage());
}
}
use of org.ietf.jgss.GSSException in project qpid-broker-j by apache.
the class SpnegoAuthenticator method doAuthenticate.
private AuthenticationResult doAuthenticate(final Subject subject, final byte[] negotiateToken) {
GSSContext context = null;
try {
final int credentialLifetime;
if (String.valueOf(System.getProperty(StandardSystemProperty.JAVA_VENDOR.key())).toUpperCase().contains("IBM")) {
credentialLifetime = GSSCredential.INDEFINITE_LIFETIME;
} else {
credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
}
final GSSManager manager = GSSManager.getInstance();
final PrivilegedExceptionAction<GSSCredential> credentialsAction = () -> manager.createCredential(null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY);
final GSSContext gssContext = manager.createContext(Subject.doAs(subject, credentialsAction));
context = gssContext;
final PrivilegedExceptionAction<byte[]> acceptAction = () -> gssContext.acceptSecContext(negotiateToken, 0, negotiateToken.length);
final byte[] outToken = Subject.doAs(subject, acceptAction);
if (outToken == null) {
LOGGER.debug("Ticket validation failed");
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR);
}
final PrivilegedAction<String> authenticationAction = () -> {
if (gssContext.isEstablished()) {
GSSName gssName = null;
try {
gssName = gssContext.getSrcName();
} catch (final GSSException e) {
LOGGER.error("Unable to get src name from gss context", e);
}
if (gssName != null) {
return stripRealmNameIfRequired(gssName.toString());
}
}
return null;
};
final String principalName = Subject.doAs(subject, authenticationAction);
if (principalName != null) {
TokenCarryingPrincipal principal = new TokenCarryingPrincipal() {
private Map<String, String> _tokens = Collections.singletonMap(RESPONSE_AUTH_HEADER_NAME, NEGOTIATE_PREFIX + Base64.getEncoder().encodeToString(outToken));
@Override
public Map<String, String> getTokens() {
return _tokens;
}
@Override
public ConfiguredObject<?> getOrigin() {
return _kerberosProvider;
}
@Override
public String getName() {
return principalName;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TokenCarryingPrincipal)) {
return false;
}
final TokenCarryingPrincipal that = (TokenCarryingPrincipal) o;
if (!getName().equals(that.getName())) {
return false;
}
if (!getTokens().equals(that.getTokens())) {
return false;
}
return getOrigin() != null ? getOrigin().equals(that.getOrigin()) : that.getOrigin() == null;
}
@Override
public int hashCode() {
int result = getName().hashCode();
result = 31 * result + (getOrigin() != null ? getOrigin().hashCode() : 0);
result = 31 * result + getTokens().hashCode();
return result;
}
};
return new AuthenticationResult(principal);
}
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR);
} catch (GSSException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Ticket validation failed", e);
}
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
} catch (PrivilegedActionException e) {
final Exception cause = e.getException();
if (cause instanceof GSSException) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Service login failed", e);
}
} else {
LOGGER.error("Service login failed", e);
}
return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
} finally {
if (context != null) {
try {
context.dispose();
} catch (GSSException e) {
// Ignore
}
}
}
}
use of org.ietf.jgss.GSSException in project ats-framework by Axway.
the class GssClient method loginViaJAAS.
/**
* Login to Kerberos KDC and accquire a TGT.
*
* @throws GSSException
*/
private void loginViaJAAS() throws GSSException {
try {
JaasKerberosConfiguration config = createGssKerberosConfiguration();
if (clientPrincipalPassword != null) {
config.setPassword(clientPrincipalPassword.toCharArray());
}
if (clientKeytab != null) {
config.setKeytab(clientKeytab.toString());
}
config.initialize();
LoginContext loginContext = null;
if (config.getCallbackHandler() != null) {
loginContext = new LoginContext("other", config.getCallbackHandler());
} else {
loginContext = new LoginContext("other");
}
loginContext.login();
// Subject will be populated with the Kerberos Principal name and the TGT.
// Krb5LoginModule obtains a TGT (KerberosTicket) for the user either from the KDC
// or from an existing ticket cache, and stores this TGT in the private credentials
// set of a Subject
subject = loginContext.getSubject();
log.debug("Logged in successfully as subject=\n" + subject.toString());
} catch (LoginException e) {
log.error(e);
throw new GSSException(GSSException.DEFECTIVE_CREDENTIAL, GSSException.BAD_STATUS, "Kerberos client '" + clientPrincipalName + "' failed to login to KDC. Error: " + e.getMessage());
}
}
use of org.ietf.jgss.GSSException in project wildfly by wildfly.
the class CSIv2Util method createGSSUPMechOID.
/**
* <p>
* Create an ASN.1, DER encoded representation for the GSSUP OID mechanism.
* </p>
*
* @return the DER encoded representation of the GSSUP OID.
*/
public static byte[] createGSSUPMechOID() {
// kudos to org.ietf.jgss.Oid for the Oid utility need to strip the "oid:" part of the GSSUPMechOID first.
byte[] retval = {};
try {
Oid oid = new Oid(GSSUPMechOID.value.substring(4));
retval = oid.getDER();
} catch (GSSException e) {
IIOPLogger.ROOT_LOGGER.caughtExceptionEncodingGSSUPMechOID(e);
}
return retval;
}
Aggregations