krb5loginmodule.java

来自「JAVA 所有包」· Java 代码 · 共 1,143 行 · 第 1/3 页

JAVA
1,143
字号
		     +" from the user");	    }	}    }        private void promptForPass(boolean getPasswdFromSharedState) 	throws LoginException {	if (getPasswdFromSharedState) {	    // use the password saved by the first module in the stack	    password = (char[])sharedState.get(PWD);	    if (password == null) {		if (debug) {		    System.out.println			("Password from shared state is null");		}		throw new LoginException		    ("Password can not be obtained from sharedstate ");	    }	    if (debug) {		System.out.println		    ("password is " + new String(password));	    }	    return;	}	if (doNotPrompt) {	    throw new LoginException		("Unable to obtain password from user\n");	} else {	    if (callbackHandler == null)		throw new LoginException("No CallbackHandler "					 + "available "					 + "to garner authentication " 					 + "information from the user");	    try {		Callback[] callbacks = new Callback[1];		String userName = krb5PrincName.toString();		MessageFormat form = new MessageFormat(					 rb.getString(					 "Kerberos password for [username]: "));	        Object[] source = {userName};		callbacks[0] = new PasswordCallback(						    form.format(source),						    false);		callbackHandler.handle(callbacks);		char[] tmpPassword = ((PasswordCallback)				      callbacks[0]).getPassword();		if (tmpPassword == null) {		    // treat a NULL password as an empty password		    tmpPassword = new char[0];		}		password = new char[tmpPassword.length];		System.arraycopy(tmpPassword, 0,				 password, 0, tmpPassword.length);		((PasswordCallback)callbacks[0]).clearPassword();				// clear tmpPassword		for (int i = 0; i < tmpPassword.length; i++)		    tmpPassword[i] = ' ';		tmpPassword = null;		if (debug) {		    System.out.println("\t\t[Krb5LoginModule] " +				       "user entered username: " +				       krb5PrincName);		    System.out.println();		}	    } catch (java.io.IOException ioe) {		throw new LoginException(ioe.getMessage());	    } catch (UnsupportedCallbackException uce) {		throw new LoginException(uce.getMessage()					 +" not available to garner " 					 +" authentication information " 					 + "from the user");	    }	}	    }    private void validateConfiguration() throws LoginException {	if (doNotPrompt && !useTicketCache && !useKeyTab)	    throw new LoginException		("Configuration Error" 		 + " - either doNotPrompt should be "		 + " false or useTicketCache/useKeyTab "		 + " should be true");	if (ticketCacheName != null && !useTicketCache)	    throw new LoginException		("Configuration Error " 		 + " - useTicketCache should be set "		 + "to true to use the ticket cache" 		 + ticketCacheName);	if (keyTabName != null & !useKeyTab)	    throw new LoginException		("Configuration Error - useKeyTab should be set to true "		 + "to use the keytab" + keyTabName);	if (storeKey && doNotPrompt && !useKeyTab) 	    throw new LoginException		("Configuration Error - either doNotPrompt "		 + "should be set to false or "		 + "useKeyTab must be set to true for storeKey option");	if (renewTGT && !useTicketCache)	    throw new LoginException		("Configuration Error" 		 + " - either useTicketCache should be "		 + " true or renewTGT should be false");    }      private boolean isCurrent(Credentials creds)    {	Date endTime = creds.getEndTime();	if (endTime != null) {	    return (System.currentTimeMillis() <= endTime.getTime());	}	return true;    }    private Credentials renewCredentials(Credentials creds)     {	Credentials lcreds;	try {	    if (!creds.isRenewable())		throw new RefreshFailedException("This ticket" +				" is not renewable");	    if (System.currentTimeMillis() > cred.getRenewTill().getTime())		throw new RefreshFailedException("This ticket is past "                                             + "its last renewal time.");	    lcreds = creds.renew();	    if (debug)		System.out.println("Renewed Kerberos Ticket");	} catch (Exception e) {	    lcreds = null;	    if (debug)		System.out.println("Ticket could not be renewed : "				+ e.getMessage());	}	return lcreds;    }    /**     * <p> This method is called if the LoginContext's     * overall authentication succeeded     * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL     * LoginModules succeeded).     *     * <p> If this LoginModule's own authentication attempt     * succeeded (checked by retrieving the private state saved by the     * <code>login</code> method), then this method associates a     * <code>Krb5Principal</code>     * with the <code>Subject</code> located in the     * <code>LoginModule</code>. It adds Kerberos Credentials to the     *  the Subject's private credentials set. If this LoginModule's own     * authentication attempted failed, then this method removes     * any state that was originally saved.     *     * <p>     *     * @exception LoginException if the commit fails.     *     * @return true if this LoginModule's own login and commit     *		attempts succeeded, or false otherwise.     */    public boolean commit() throws LoginException {	/*	 * Let us add the Krb5 Creds to the Subject's 	 * private credentials. The credentials are of type	 * KerberosKey or KerberosTicket	 */	if (succeeded == false) {	    return false;	} else {	    if (isInitiator && (cred == null)) {		succeeded = false;		throw new LoginException("Null Client Credential");	    }	    if (subject.isReadOnly()) {	        cleanKerberosCred();		throw new LoginException("Subject is Readonly");	    }	    /*	     * Add the Principal (authenticated identity)	     * to the Subject's principal set and	     * add the credentials (TGT or Service key) to the	     * Subject's private credentials	     */	    Set privCredSet =  subject.getPrivateCredentials();	    Set princSet  = subject.getPrincipals();	    kerbClientPrinc = new KerberosPrincipal(principal.getName());		    // create Kerberos Ticket 	    if (isInitiator) {		kerbTicket = Krb5Util.credsToTicket(cred);	    }	    if (storeKey) {		if (encKeys == null || encKeys.length <= 0) {		    succeeded = false;		    throw new LoginException("Null Server Key ");		}		kerbKeys = new KerberosKey[encKeys.length];		for (int i = 0; i < encKeys.length; i ++) {	            Integer temp = encKeys[i].getKeyVersionNumber();		    kerbKeys[i] = new KerberosKey(kerbClientPrinc,					  encKeys[i].getBytes(),					  encKeys[i].getEType(),					  (temp == null?					  0: temp.intValue()));                }			    }	    // Let us add the kerbClientPrinc,kerbTicket and kerbKey (if	    // storeKey is true)	    if (!princSet.contains(kerbClientPrinc))		princSet.add(kerbClientPrinc);	    // add the TGT	    if (kerbTicket != null) {		if (!privCredSet.contains(kerbTicket)) 			    privCredSet.add(kerbTicket);	    }	    if (storeKey) {		for (int i = 0; i < kerbKeys.length; i++) {		    if (!privCredSet.contains(kerbKeys[i])) {	    			privCredSet.add(kerbKeys[i]);		    }		    encKeys[i].destroy();		    encKeys[i] = null;		    if (debug) {		        System.out.println("Added server's key"					+ kerbKeys[i]);		    		        System.out.println("\t\t[Krb5LoginModule] " +				       "added Krb5Principal  " + 				       kerbClientPrinc.toString()				       + " to Subject");		    }					}	    }	}	commitSucceeded = true;	if (debug)	    System.out.println("Commit Succeeded \n");	return true;    }        /**     * <p> This method is called if the LoginContext's     * overall authentication failed.     * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL      * LoginModules did not succeed).     *     * <p> If this LoginModule's own authentication attempt     * succeeded (checked by retrieving the private state saved by the     * <code>login</code> and <code>commit</code> methods),     * then this method cleans up any state that was originally saved.     *     * <p>     *     * @exception LoginException if the abort fails.     *     * @return false if this LoginModule's own login and/or commit attempts     *		failed, and true otherwise.     */    public boolean abort() throws LoginException {	if (succeeded == false) {	    return false;	} else if (succeeded == true && commitSucceeded == false) {	    // login succeeded but overall authentication failed	    succeeded = false;	    cleanKerberosCred();	} else {	    // overall authentication succeeded and commit succeeded,	    // but someone else's commit failed	    logout();	}	return true;    }        /**     * Logout the user.     *     * <p> This method removes the <code>Krb5Principal</code>     * that was added by the <code>commit</code> method.     *     * <p>     *     * @exception LoginException if the logout fails.     *     * @return true in all cases since this <code>LoginModule</code>     *          should not be ignored.     */    public boolean logout() throws LoginException {        if (debug) {            System.out.println("\t\t[Krb5LoginModule]: " +                "Entering logout");        }        if (subject.isReadOnly()) {	    cleanKerberosCred();            throw new LoginException("Subject is Readonly");        }		subject.getPrincipals().remove(kerbClientPrinc);	   // Let us remove all Kerberos credentials stored in the Subject 	Iterator it = subject.getPrivateCredentials().iterator();	while (it.hasNext()) {	    Object o = it.next();	    if (o instanceof KerberosTicket ||		o instanceof KerberosKey) {		it.remove();	    }	}	// clean the kerberos ticket and keys	cleanKerberosCred();	succeeded = false;	commitSucceeded = false;	if (debug) {            System.out.println("\t\t[Krb5LoginModule]: " +			       "logged out Subject");        }	return true;    }    /**     * Clean Kerberos credentials     */     private void cleanKerberosCred() throws LoginException {	// Clean the ticket and server key	try {	    if (kerbTicket != null)		kerbTicket.destroy();	    if (kerbKeys != null) {	        for (int i = 0; i < kerbKeys.length; i++) {		    kerbKeys[i].destroy();  		}            }	} catch (DestroyFailedException e) {	    throw new LoginException		("Destroy Failed on Kerberos Private Credentials");	}	kerbTicket = null;	kerbKeys = null;	kerbClientPrinc = null;    }    /**     * Clean out the state      */    private void cleanState() {       	// save input as shared state only if	// authentication succeeded	if (succeeded) {	    if (storePass &&		!sharedState.containsKey(NAME) &&		!sharedState.containsKey(PWD)) {		sharedState.put(NAME, username);		sharedState.put(PWD, password);	    }	}	username = null;	password = null;	if (krb5PrincName != null && krb5PrincName.length() != 0)	    krb5PrincName.delete(0, krb5PrincName.length());	krb5PrincName = null;	if (clearPass) {	    sharedState.remove(NAME);	    sharedState.remove(PWD);	}    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?