下面列出了org.apache.http.auth.InvalidCredentialsException#org.ietf.jgss.GSSException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* {@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;
}
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) {
;
}
}
@Override
public Object run() {
try {
Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2");
Oid krb5PrincipalNameType = new Oid("1.2.840.113554.1.2.2.1");
final GSSManager manager = GSSManager.getInstance();
final GSSName clientName = manager.createName(clientPrincipalName, krb5PrincipalNameType);
final GSSCredential clientCred = manager.createCredential(clientName, 8 * 3600, krb5Mechanism,
GSSCredential.INITIATE_ONLY);
final GSSName serverName = manager.createName(serverPrincipalName, krb5PrincipalNameType);
final GSSContext context = manager.createContext(serverName, krb5Mechanism, clientCred,
GSSContext.DEFAULT_LIFETIME);
byte[] inToken = new byte[0];
byte[] outToken = context.initSecContext(inToken, 0, inToken.length);
if (outToken == null) {
throw new FailedRequestException("could not initialize the security context");
}
context.requestMutualAuth(true);
outputToken.append(new String(Base64.getEncoder().encode(outToken)));
context.dispose();
} catch (GSSException exception) {
throw new FailedRequestException(exception.getMessage(), exception);
}
return null;
}
/**
* {@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;
}
/**
* Authenticating requests with SPNEGO means that a request will execute before the client is sure that the
* server is mutually authenticated. This means that, at best, if mutual auth is requested, the client cannot
* trust that the server is giving accurate information, or in the case that the client has already sent data,
* further communication with the server should not happen.
* @param returnChallenge The Negotiate challenge from the response headers of a successful executed request
* @throws AuthenticationException If the response header does not allow for mutual authentication to be established.
*/
public void ensureMutualAuth(String returnChallenge) throws AuthenticationException {
try {
processChallenge(returnChallenge);
} catch (MalformedChallengeException mce) {
throw new AuthenticationException("Received invalid response header for mutual authentication", mce);
}
try {
String token = getNegotiateToken();
if (!spnegoNegotiator.established() || token != null) {
throw new AuthenticationException("Could not complete SPNEGO Authentication, Mutual Authentication Failed");
}
} catch (GSSException gsse) {
throw new AuthenticationException("Could not complete SPNEGO Authentication", gsse);
}
}
private static <T> T doAs(Subject subject, GssSupplier<T> action) throws GSSException {
try {
return Subject.doAs(subject, (PrivilegedExceptionAction<T>) action::get);
} catch (PrivilegedActionException e) {
Throwable t = e.getCause();
if (t instanceof GSSException) {
throw (GSSException)t;
} else if (t instanceof Error) {
throw (Error)t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException)t;
} else {
throw new RuntimeException(t);
}
}
}
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) {
;
}
}
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) {
;
}
}
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);
}
@Override
protected byte[] generateToken(final byte[] input, final String authServer) throws GSSException {
// This is done to avoid issues with Keberos service ticket replay detection on the service side.
synchronized( KnoxSpnegoAuthScheme.class ) {
long now;
// This just insures that the system clock has advanced to a different nanosecond.
// Kerberos uses microsecond resolution and 1ms=1000ns.
while( ( now = System.nanoTime() ) == nano ) {
try {
Thread.sleep( 0 );
} catch( InterruptedException e ) {
Thread.currentThread().interrupt();
}
}
nano = now;
return super.generateToken( input, authServer );
}
}
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);
}
}
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);
}
/**
* Creates the negotiator if it is not yet created, or does nothing if the negotiator is already initialized.
* @param requestURI request being authenticated
* @param spnegoCredentials The user and service principals
* @throws UnknownHostException If the service principal is host based, and if the request URI cannot be resolved to a FQDN
* @throws AuthenticationException If the service principal is malformed
* @throws GSSException If the negotiator cannot be created.
*/
private void initializeNegotiator(URI requestURI, SpnegoCredentials spnegoCredentials) throws UnknownHostException, AuthenticationException, GSSException {
// Initialize negotiator
if (spnegoNegotiator == null) {
// Determine host principal
String servicePrincipal = spnegoCredentials.getServicePrincipalName();
if (spnegoCredentials.getServicePrincipalName().contains(HOSTNAME_PATTERN)) {
String fqdn = getFQDN(requestURI);
String[] components = spnegoCredentials.getServicePrincipalName().split("[/@]");
if (components.length != 3 || !components[1].equals(HOSTNAME_PATTERN)) {
throw new AuthenticationException("Malformed service principal name [" + spnegoCredentials.getServicePrincipalName()
+ "]. To use host substitution, the principal must be of the format [serviceName/[email protected]].");
}
servicePrincipal = components[0] + "/" + fqdn.toLowerCase() + "@" + components[2];
}
User userInfo = spnegoCredentials.getUserProvider().getUser();
KerberosPrincipal principal = userInfo.getKerberosPrincipal();
if (principal == null) {
throw new EsHadoopIllegalArgumentException("Could not locate Kerberos Principal on currently logged in user.");
}
spnegoNegotiator = new SpnegoNegotiator(principal.getName(), servicePrincipal);
}
}
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);
}
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);
}
}
/**
* 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;
}
}
public static void main(String[] argv) throws Exception {
GSSManager man = GSSManager.getInstance();
String s = "[email protected]";
GSSName name = man.createName(s, GSSName.NT_USER_NAME);
byte[] exported = name.export();
// Offset of the length of the mech name. Length in big endian
int lenOffset = exported.length - s.length() - 4;
// Make it huge
exported[lenOffset] = 0x7f;
try {
man.createName(exported, GSSName.NT_EXPORT_NAME);
} catch (GSSException gsse) {
System.out.println(gsse);
}
}
@Override
public byte[] initSecContext ( byte[] token, int off, int len ) throws SmbException {
try {
return this.gssContext.initSecContext(token, off, len);
}
catch ( GSSException e ) {
throw new SmbAuthException("GSSAPI mechanism failed", e);
}
}
/**
* 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;
}
}
/**
* Checks the correct bound
* @param a get a creds for this principal, null for default one
* @param b expected name, null for still unbound, "NOCRED" for no creds
* @param objs princs, keys and keytabs in the subject
*/
private static void check(final String a, String b, Object... objs)
throws Exception {
Subject subj = new Subject();
for (Object obj: objs) {
if (obj instanceof KerberosPrincipal) {
subj.getPrincipals().add((KerberosPrincipal)obj);
} else if (obj instanceof KerberosKey || obj instanceof KeyTab) {
subj.getPrivateCredentials().add(obj);
}
}
final GSSManager man = GSSManager.getInstance();
try {
String result = Subject.doAs(
subj, new PrivilegedExceptionAction<String>() {
@Override
public String run() throws GSSException {
GSSCredential cred = man.createCredential(
a == null ? null : man.createName(r(a), null),
GSSCredential.INDEFINITE_LIFETIME,
GSSUtil.GSS_KRB5_MECH_OID,
GSSCredential.ACCEPT_ONLY);
GSSName name = cred.getName();
return name == null ? null : name.toString();
}
});
if (!Objects.equals(result, r(b))) {
throw new Exception("Check failed: getInstance(" + a
+ ") has name " + result + ", not " + b);
}
} catch (PrivilegedActionException e) {
if (!"NOCRED".equals(b)) {
throw new Exception("Check failed: getInstance(" + a
+ ") is null " + ", but not one with name " + b);
}
}
}
protected GSSContext createGSSContext() throws GSSException {
boolean useKerberosOid = PropertyUtils.isTrue(
messageContext.getContextualProperty(PROPERTY_USE_KERBEROS_OID));
Oid oid = new Oid(useKerberosOid ? KERBEROS_OID : SPNEGO_OID);
GSSManager gssManager = GSSManager.getInstance();
String spn = getCompleteServicePrincipalName();
GSSName gssService = gssManager.createName(spn, null);
return gssManager.createContext(gssService.canonicalize(oid),
oid, null, GSSContext.DEFAULT_LIFETIME);
}
@Override
public void dispose () throws SmbException {
if ( this.gssContext != null ) {
try {
this.gssContext.dispose();
}
catch ( GSSException e ) {
throw new SmbException("Context disposal failed", e);
}
}
}
private String generateTicket() throws GSSException {
final GSSManager manager = GSSManager.getInstance();
// Oid for kerberos principal name
Oid krb5PrincipalOid = new Oid("1.2.840.113554.1.2.2.1");
Oid KERB_V5_OID = new Oid("1.2.840.113554.1.2.2");
final GSSName clientName = manager.createName(principal,
krb5PrincipalOid);
final GSSCredential clientCred = manager.createCredential(clientName,
8 * 3600,
KERB_V5_OID,
GSSCredential.INITIATE_ONLY);
final GSSName serverName = manager.createName(principal, krb5PrincipalOid);
final GSSContext context = manager.createContext(serverName,
KERB_V5_OID,
clientCred,
GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true);
context.requestConf(false);
context.requestInteg(true);
final byte[] outToken = context.initSecContext(new byte[0], 0, 0);
StringBuffer outputBuffer = new StringBuffer();
outputBuffer.append("Negotiate ");
outputBuffer.append(Bytes.toString(Base64.getEncoder().encode(outToken)));
System.out.print("Ticket is: " + outputBuffer);
return outputBuffer.toString();
}
@Override
protected byte[] generateGSSToken(byte[] input, Oid oid, String authServer, Credentials credentials) throws GSSException {
KerberosUsernamePasswordAuthenticator authenticator = new KerberosUsernamePasswordAuthenticator(kerberosConfig) {
// Disable strict check for the configured kerberos realm, which is on super-method
@Override
protected String getKerberosPrincipal(String username) throws LoginException {
if (username.contains("@")) {
return username;
} else {
return username + "@" + config.getKerberosRealm();
}
}
};
try {
Subject clientSubject = authenticator.authenticateSubject(username, password);
ByteArrayHolder holder = Subject.doAs(clientSubject, new ClientAcceptSecContext(input, oid, authServer));
return holder.bytes;
} catch (Exception le) {
throw new RuntimeException(le);
} finally {
authenticator.logoutSubject();
}
}
public static void main(String[] argv) throws Exception {
try {
GSSManager manager = GSSManager.getInstance();
GSSName name = manager.createName("anonymous", GSSName.NT_ANONYMOUS);
boolean anonymous = name.isAnonymous();
if (anonymous == false) {
throw new RuntimeException("GSSName.isAnonymous() returns false for GSSName.NT_ANONYMOUS");
}
} catch (GSSException e) {
System.out.println("Not supported, ignored!");
}
}
public byte[] run() {
try {
serviceTickets = serverContext.acceptSecContext(tokens, 0, tokens.length);
} catch (GSSException e) {
throw new RuntimeException(e);
}
return null;
}
public static void main(String[] args)
throws Exception {
OneKDC kdc = new OneKDC(null);
kdc.writeJAASConf();
// Rewrite keytab, 3 set of keys with different kvno
KeyTab ktab = KeyTab.create(OneKDC.KTAB);
p = new PrincipalName(
OneKDC.SERVER+"@"+OneKDC.REALM, PrincipalName.KRB_NT_SRV_HST);
ktab.addEntry(p, "pass1".toCharArray(), 1, true);
ktab.addEntry(p, "pass3".toCharArray(), 3, true);
ktab.addEntry(p, "pass2".toCharArray(), 2, true);
ktab.save();
char[] pass = "pass2".toCharArray();
kdc.addPrincipal(OneKDC.SERVER, pass);
go(OneKDC.SERVER, "com.sun.security.jgss.krb5.accept", pass);
pass = "pass3".toCharArray();
kdc.addPrincipal(OneKDC.SERVER, pass);
// "server" initiate also, check pass2 is used at authentication
go(OneKDC.SERVER, "server", pass);
try {
pass = "pass4".toCharArray();
kdc.addPrincipal(OneKDC.SERVER, pass);
go(OneKDC.SERVER, "com.sun.security.jgss.krb5.accept", pass);
throw new Exception("This test should fail");
} catch (GSSException gsse) {
// Since 7197159, different kvno is accepted, this return code
// will never be thrown out again.
//KrbException ke = (KrbException)gsse.getCause();
//if (ke.returnCode() != Krb5.KRB_AP_ERR_BADKEYVER) {
// throw new Exception("Not expected failure code: " +
// ke.returnCode());
//}
}
}
/**
* 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 static void main(String[] argv) throws Exception {
GSSManager man = GSSManager.getInstance();
String s = "[email protected]";
GSSName name = man.createName(s, GSSName.NT_USER_NAME);
byte[] exported = name.export();
// Offset of the length of the mech name. Length in big endian
int lenOffset = exported.length - s.length() - 4;
// Make it huge
exported[lenOffset] = 0x7f;
try {
man.createName(exported, GSSName.NT_EXPORT_NAME);
} catch (GSSException gsse) {
System.out.println(gsse);
}
}
/**
* 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;
}
}